Upgraded phpmyadmin to 4.0.4 (All Languages) - No modifications yet
[openemr.git] / phpmyadmin / libraries / database_interface.lib.php
blobde697ec119d332ec8449f200c5a449c21f4e7faa
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Common Option Constants For DBI Functions
6 * @package PhpMyAdmin-DBI
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
13 * Force STORE_RESULT method, ignored by classic MySQL.
15 define('PMA_DBI_QUERY_STORE', 1);
16 /**
17 * Do not read whole query.
19 define('PMA_DBI_QUERY_UNBUFFERED', 2);
20 /**
21 * Get session variable.
23 define('PMA_DBI_GETVAR_SESSION', 1);
24 /**
25 * Get global variable.
27 define('PMA_DBI_GETVAR_GLOBAL', 2);
29 /**
30 * Checks whether database extension is loaded
32 * @param string $extension mysql extension to check
34 * @return bool
36 function PMA_DBI_checkDbExtension($extension = 'mysql')
38 if ($extension == 'drizzle' && function_exists('drizzle_create')) {
39 return true;
40 } else if (function_exists($extension . '_connect')) {
41 return true;
44 return false;
47 if (defined('TESTSUITE')) {
48 /**
49 * For testsuite we use dummy driver which can fake some queries.
51 include_once './libraries/dbi/dummy.lib.php';
52 } else {
54 /**
55 * check for requested extension
57 if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
59 // if it fails try alternative extension ...
60 // and display an error ...
62 /**
63 * @todo add different messages for alternative extension
64 * and complete fail (no alternative extension too)
66 PMA_warnMissingExtension(
67 $GLOBALS['cfg']['Server']['extension'],
68 false,
69 PMA_Util::showDocu('faq', 'faqmysql')
72 if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
73 $alternativ_extension = 'mysqli';
74 } else {
75 $alternativ_extension = 'mysql';
78 if (! PMA_DBI_checkDbExtension($alternativ_extension)) {
79 // if alternative fails too ...
80 PMA_warnMissingExtension(
81 $GLOBALS['cfg']['Server']['extension'],
82 true,
83 PMA_Util::showDocu('faq', 'faqmysql')
87 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
88 unset($alternativ_extension);
91 /**
92 * Including The DBI Plugin
94 include_once './libraries/dbi/'
95 . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php';
99 /**
100 * runs a query
102 * @param string $query SQL query to execte
103 * @param mixed $link optional database link to use
104 * @param int $options optional query options
105 * @param bool $cache_affected_rows whether to cache affected rows
107 * @return mixed
109 function PMA_DBI_query($query, $link = null, $options = 0,
110 $cache_affected_rows = true
112 $res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
113 or PMA_Util::mysqlDie(PMA_DBI_getError($link), $query);
114 return $res;
118 * Stores query data into session data for debugging purposes
120 * @param string $query Query text
121 * @param resource $link database link
122 * @param resource $result Query result
123 * @param integer $time Time to execute query
125 * @return void
127 function PMA_DBI_DBG_query($query, $link, $result, $time)
129 $hash = md5($query);
131 if (isset($_SESSION['debug']['queries'][$hash])) {
132 $_SESSION['debug']['queries'][$hash]['count']++;
133 } else {
134 $_SESSION['debug']['queries'][$hash] = array();
135 if ($result == false) {
136 $_SESSION['debug']['queries'][$hash]['error']
137 = '<b style="color:red">' . mysqli_error($link) . '</b>';
139 $_SESSION['debug']['queries'][$hash]['count'] = 1;
140 $_SESSION['debug']['queries'][$hash]['query'] = $query;
141 $_SESSION['debug']['queries'][$hash]['time'] = $time;
144 $trace = array();
145 foreach (debug_backtrace() as $trace_step) {
146 $trace[]
147 = (isset($trace_step['file'])
148 ? PMA_Error::relPath($trace_step['file'])
149 : '')
150 . (isset($trace_step['line'])
151 ? '#' . $trace_step['line'] . ': '
152 : '')
153 . (isset($trace_step['class']) ? $trace_step['class'] : '')
154 . (isset($trace_step['type']) ? $trace_step['type'] : '')
155 . (isset($trace_step['function']) ? $trace_step['function'] : '')
156 . '('
157 . (isset($trace_step['params'])
158 ? implode(', ', $trace_step['params'])
159 : ''
161 . ')'
164 $_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
168 * runs a query and returns the result
170 * @param string $query query to run
171 * @param resource $link mysql link resource
172 * @param integer $options query options
173 * @param bool $cache_affected_rows whether to cache affected row
175 * @return mixed
177 function PMA_DBI_try_query($query, $link = null, $options = 0,
178 $cache_affected_rows = true
180 if (empty($link)) {
181 if (isset($GLOBALS['userlink'])) {
182 $link = $GLOBALS['userlink'];
183 } else {
184 return false;
188 if ($GLOBALS['cfg']['DBG']['sql']) {
189 $time = microtime(true);
192 $result = PMA_DBI_real_query($query, $link, $options);
194 if ($cache_affected_rows) {
195 $GLOBALS['cached_affected_rows'] = PMA_DBI_affected_rows($link, false);
198 if ($GLOBALS['cfg']['DBG']['sql']) {
199 $time = microtime(true) - $time;
200 PMA_DBI_DBG_query($query, $link, $result, $time);
202 if ($result != false && PMA_Tracker::isActive() == true ) {
203 PMA_Tracker::handleQuery($query);
206 return $result;
210 * Run multi query statement and return results
212 * @param string $multi_query multi query statement to execute
213 * @param mysqli $link mysqli object
215 * @return mysqli_result collection | boolean(false)
217 function PMA_DBI_try_multi_query($multi_query = '', $link = null)
220 if (empty($link)) {
221 if (isset($GLOBALS['userlink'])) {
222 $link = $GLOBALS['userlink'];
223 } else {
224 return false;
228 return PMA_DBI_real_multi_query($link, $multi_query);
233 * converts charset of a mysql message, usually coming from mysql_error(),
234 * into PMA charset, usally UTF-8
235 * uses language to charset mapping from mysql/share/errmsg.txt
236 * and charset names to ISO charset from information_schema.CHARACTER_SETS
238 * @param string $message the message
240 * @return string $message
242 function PMA_DBI_convert_message($message)
244 // latin always last!
245 $encodings = array(
246 'japanese' => 'EUC-JP', //'ujis',
247 'japanese-sjis' => 'Shift-JIS', //'sjis',
248 'korean' => 'EUC-KR', //'euckr',
249 'russian' => 'KOI8-R', //'koi8r',
250 'ukrainian' => 'KOI8-U', //'koi8u',
251 'greek' => 'ISO-8859-7', //'greek',
252 'serbian' => 'CP1250', //'cp1250',
253 'estonian' => 'ISO-8859-13', //'latin7',
254 'slovak' => 'ISO-8859-2', //'latin2',
255 'czech' => 'ISO-8859-2', //'latin2',
256 'hungarian' => 'ISO-8859-2', //'latin2',
257 'polish' => 'ISO-8859-2', //'latin2',
258 'romanian' => 'ISO-8859-2', //'latin2',
259 'spanish' => 'CP1252', //'latin1',
260 'swedish' => 'CP1252', //'latin1',
261 'italian' => 'CP1252', //'latin1',
262 'norwegian-ny' => 'CP1252', //'latin1',
263 'norwegian' => 'CP1252', //'latin1',
264 'portuguese' => 'CP1252', //'latin1',
265 'danish' => 'CP1252', //'latin1',
266 'dutch' => 'CP1252', //'latin1',
267 'english' => 'CP1252', //'latin1',
268 'french' => 'CP1252', //'latin1',
269 'german' => 'CP1252', //'latin1',
272 $server_language = PMA_DBI_fetch_value(
273 'SHOW VARIABLES LIKE \'language\';',
277 if ($server_language) {
278 $found = array();
279 $match = preg_match(
280 '&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i',
281 $server_language,
282 $found
284 if ($match) {
285 $server_language = $found[1];
289 if (! empty($server_language) && isset($encodings[$server_language])) {
290 $encoding = $encodings[$server_language];
291 } else {
292 /* Fallback to CP1252 if we can not detect */
293 $encoding = 'CP1252';
296 if (function_exists('iconv')) {
297 if ((@stristr(PHP_OS, 'AIX'))
298 && (@strcasecmp(ICONV_IMPL, 'unknown') == 0)
299 && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)
301 include_once './libraries/iconv_wrapper.lib.php';
302 $message = PMA_aix_iconv_wrapper(
303 $encoding,
304 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
305 $message
307 } else {
308 $message = iconv(
309 $encoding,
310 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
311 $message
314 } elseif (function_exists('recode_string')) {
315 $message = recode_string(
316 $encoding . '..' . 'utf-8',
317 $message
319 } elseif (function_exists('libiconv')) {
320 $message = libiconv($encoding, 'utf-8', $message);
321 } elseif (function_exists('mb_convert_encoding')) {
322 // do not try unsupported charsets
323 if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
324 $message = mb_convert_encoding(
325 $message,
326 'utf-8',
327 $encoding
332 return $message;
336 * returns array with table names for given db
338 * @param string $database name of database
339 * @param mixed $link mysql link resource|object
341 * @return array tables names
343 function PMA_DBI_get_tables($database, $link = null)
345 return PMA_DBI_fetch_result(
346 'SHOW TABLES FROM ' . PMA_Util::backquote($database) . ';',
347 null,
349 $link,
350 PMA_DBI_QUERY_STORE
355 * usort comparison callback
357 * @param string $a first argument to sort
358 * @param string $b second argument to sort
360 * @return integer a value representing whether $a should be before $b in the
361 * sorted array or not
363 * @access private
365 function PMA_usort_comparison_callback($a, $b)
367 if ($GLOBALS['cfg']['NaturalOrder']) {
368 $sorter = 'strnatcasecmp';
369 } else {
370 $sorter = 'strcasecmp';
372 /* No sorting when key is not present */
373 if (! isset($a[$GLOBALS['callback_sort_by']])
374 || ! isset($b[$GLOBALS['callback_sort_by']])
376 return 0;
378 // produces f.e.:
379 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
380 return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter(
381 $a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]
383 } // end of the 'PMA_usort_comparison_callback()' function
386 * returns array of all tables in given db or dbs
387 * this function expects unquoted names:
388 * RIGHT: my_database
389 * WRONG: `my_database`
390 * WRONG: my\_database
391 * if $tbl_is_group is true, $table is used as filter for table names
392 * if $tbl_is_group is 'comment, $table is used as filter for table comments
394 * <code>
395 * PMA_DBI_get_tables_full('my_database');
396 * PMA_DBI_get_tables_full('my_database', 'my_table'));
397 * PMA_DBI_get_tables_full('my_database', 'my_tables_', true));
398 * PMA_DBI_get_tables_full('my_database', 'my_tables_', 'comment'));
399 * </code>
401 * @param string $database database
402 * @param string|bool $table table or false
403 * @param boolean|string $tbl_is_group $table is a table group
404 * @param mixed $link mysql link
405 * @param integer $limit_offset zero-based offset for the count
406 * @param boolean|integer $limit_count number of tables to return
407 * @param string $sort_by table attribute to sort by
408 * @param string $sort_order direction to sort (ASC or DESC)
410 * @todo move into PMA_Table
412 * @return array list of tables in given db(s)
414 function PMA_DBI_get_tables_full($database, $table = false,
415 $tbl_is_group = false, $link = null, $limit_offset = 0,
416 $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC'
418 if (true === $limit_count) {
419 $limit_count = $GLOBALS['cfg']['MaxTableList'];
421 // prepare and check parameters
422 if (! is_array($database)) {
423 $databases = array($database);
424 } else {
425 $databases = $database;
428 $tables = array();
430 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
431 // get table information from information_schema
432 if ($table) {
433 if (true === $tbl_is_group) {
434 $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
435 . PMA_Util::escapeMysqlWildcards(PMA_Util::sqlAddSlashes($table))
436 . '%\'';
437 } elseif ('comment' === $tbl_is_group) {
438 $sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
439 . PMA_Util::escapeMysqlWildcards(PMA_Util::sqlAddSlashes($table))
440 . '%\'';
441 } else {
442 $sql_where_table = 'AND t.`TABLE_NAME` = \''
443 . PMA_Util::sqlAddSlashes($table) . '\'';
445 } else {
446 $sql_where_table = '';
449 // for PMA bc:
450 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
452 // on non-Windows servers,
453 // added BINARY in the WHERE clause to force a case sensitive
454 // comparison (if we are looking for the db Aa we don't want
455 // to find the db aa)
456 $this_databases = array_map('PMA_Util::sqlAddSlashes', $databases);
458 if (PMA_DRIZZLE) {
459 $engine_info = PMA_Util::cacheGet('drizzle_engines', true);
460 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
461 if (isset($engine_info['InnoDB'])
462 && $engine_info['InnoDB']['module_library'] == 'innobase'
464 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat"
465 . " ON (t.ENGINE = 'InnoDB' AND stat.NAME"
466 . " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
469 // data_dictionary.table_cache may not contain any data for some tables,
470 // it's just a table cache
471 // auto_increment == 0 is cast to NULL because currently (2011.03.13 GA)
472 // Drizzle doesn't provide correct value
473 $sql = "
474 SELECT t.*,
475 t.TABLE_SCHEMA AS `Db`,
476 t.TABLE_NAME AS `Name`,
477 t.TABLE_TYPE AS `TABLE_TYPE`,
478 t.ENGINE AS `Engine`,
479 t.ENGINE AS `Type`,
480 t.TABLE_VERSION AS `Version`,-- VERSION
481 t.ROW_FORMAT AS `Row_format`,
482 coalesce(tc.ROWS, stat.NUM_ROWS)
483 AS `Rows`,-- TABLE_ROWS,
484 coalesce(tc.ROWS, stat.NUM_ROWS)
485 AS `TABLE_ROWS`,
486 tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
487 tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
488 NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
489 NULL AS `Index_length`, -- INDEX_LENGTH
490 NULL AS `Data_free`, -- DATA_FREE
491 nullif(t.AUTO_INCREMENT, 0)
492 AS `Auto_increment`,
493 t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
494 t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
495 NULL AS `Check_time`, -- CHECK_TIME
496 t.TABLE_COLLATION AS `Collation`,
497 NULL AS `Checksum`, -- CHECKSUM
498 NULL AS `Create_options`, -- CREATE_OPTIONS
499 t.TABLE_COMMENT AS `Comment`
500 FROM data_dictionary.TABLES t
501 LEFT JOIN data_dictionary.TABLE_CACHE tc
502 ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME
503 = t.TABLE_NAME
504 $stats_join
505 WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
506 " . $sql_where_table;
507 } else {
508 $sql = '
509 SELECT *,
510 `TABLE_SCHEMA` AS `Db`,
511 `TABLE_NAME` AS `Name`,
512 `TABLE_TYPE` AS `TABLE_TYPE`,
513 `ENGINE` AS `Engine`,
514 `ENGINE` AS `Type`,
515 `VERSION` AS `Version`,
516 `ROW_FORMAT` AS `Row_format`,
517 `TABLE_ROWS` AS `Rows`,
518 `AVG_ROW_LENGTH` AS `Avg_row_length`,
519 `DATA_LENGTH` AS `Data_length`,
520 `MAX_DATA_LENGTH` AS `Max_data_length`,
521 `INDEX_LENGTH` AS `Index_length`,
522 `DATA_FREE` AS `Data_free`,
523 `AUTO_INCREMENT` AS `Auto_increment`,
524 `CREATE_TIME` AS `Create_time`,
525 `UPDATE_TIME` AS `Update_time`,
526 `CHECK_TIME` AS `Check_time`,
527 `TABLE_COLLATION` AS `Collation`,
528 `CHECKSUM` AS `Checksum`,
529 `CREATE_OPTIONS` AS `Create_options`,
530 `TABLE_COMMENT` AS `Comment`
531 FROM `information_schema`.`TABLES` t
532 WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA`
533 IN (\'' . implode("', '", $this_databases) . '\')
534 ' . $sql_where_table;
537 // Sort the tables
538 $sql .= " ORDER BY $sort_by $sort_order";
540 if ($limit_count) {
541 $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
544 $tables = PMA_DBI_fetch_result(
545 $sql, array('TABLE_SCHEMA', 'TABLE_NAME'), null, $link
547 unset($sql_where_table, $sql);
549 if (PMA_DRIZZLE) {
550 // correct I_S and D_D names returned by D_D.TABLES -
551 // Drizzle generally uses lower case for them,
552 // but TABLES returns uppercase
553 foreach ((array)$database as $db) {
554 $db_upper = strtoupper($db);
555 if (!isset($tables[$db]) && isset($tables[$db_upper])) {
556 $tables[$db] = $tables[$db_upper];
557 unset($tables[$db_upper]);
562 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
563 // here, the array's first key is by schema name
564 foreach ($tables as $one_database_name => $one_database_tables) {
565 uksort($one_database_tables, 'strnatcasecmp');
567 if ($sort_order == 'DESC') {
568 $one_database_tables = array_reverse($one_database_tables);
570 $tables[$one_database_name] = $one_database_tables;
573 } // end (get information from table schema)
575 // If permissions are wrong on even one database directory,
576 // information_schema does not return any table info for any database
577 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
578 if (empty($tables) && !PMA_DRIZZLE) {
579 foreach ($databases as $each_database) {
580 if ($table || (true === $tbl_is_group)) {
581 $sql = 'SHOW TABLE STATUS FROM '
582 . PMA_Util::backquote($each_database)
583 .' LIKE \''
584 . PMA_Util::escapeMysqlWildcards(
585 PMA_Util::sqlAddSlashes($table, true)
587 . '%\'';
588 } else {
589 $sql = 'SHOW TABLE STATUS FROM '
590 . PMA_Util::backquote($each_database);
593 $useStatusCache = false;
595 if (extension_loaded('apc')
596 && isset($GLOBALS['cfg']['Server']['StatusCacheDatabases'])
597 && ! empty($GLOBALS['cfg']['Server']['StatusCacheLifetime'])
599 $statusCacheDatabases
600 = (array) $GLOBALS['cfg']['Server']['StatusCacheDatabases'];
601 if (in_array($each_database, $statusCacheDatabases)) {
602 $useStatusCache = true;
606 $each_tables = null;
608 if ($useStatusCache) {
609 $cacheKey = 'phpMyAdmin_tableStatus_'
610 . sha1($GLOBALS['cfg']['Server']['host'] . '_' . $sql);
612 $each_tables = apc_fetch($cacheKey);
615 if (!$each_tables) {
616 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
619 if ($useStatusCache) {
620 apc_store(
621 $cacheKey, $each_tables,
622 $GLOBALS['cfg']['Server']['StatusCacheLifetime']
626 // Sort naturally if the config allows it and we're sorting
627 // the Name column.
628 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
629 uksort($each_tables, 'strnatcasecmp');
631 if ($sort_order == 'DESC') {
632 $each_tables = array_reverse($each_tables);
634 } else {
635 // Prepare to sort by creating array of the selected sort
636 // value to pass to array_multisort
638 // Size = Data_length + Index_length
639 if ($sort_by == 'Data_length') {
640 foreach ($each_tables as $table_name => $table_data) {
641 ${$sort_by}[$table_name] = strtolower(
642 $table_data['Data_length'] + $table_data['Index_length']
645 } else {
646 foreach ($each_tables as $table_name => $table_data) {
647 ${$sort_by}[$table_name] = strtolower($table_data[$sort_by]);
651 if ($sort_order == 'DESC') {
652 array_multisort($$sort_by, SORT_DESC, $each_tables);
653 } else {
654 array_multisort($$sort_by, SORT_ASC, $each_tables);
657 // cleanup the temporary sort array
658 unset($$sort_by);
661 if ($limit_count) {
662 $each_tables = array_slice(
663 $each_tables, $limit_offset, $limit_count
667 foreach ($each_tables as $table_name => $each_table) {
668 if ('comment' === $tbl_is_group
669 && 0 === strpos($each_table['Comment'], $table)
671 // remove table from list
672 unset($each_tables[$table_name]);
673 continue;
676 if (! isset($each_tables[$table_name]['Type'])
677 && isset($each_tables[$table_name]['Engine'])
679 // pma BC, same parts of PMA still uses 'Type'
680 $each_tables[$table_name]['Type']
681 =& $each_tables[$table_name]['Engine'];
682 } elseif (! isset($each_tables[$table_name]['Engine'])
683 && isset($each_tables[$table_name]['Type'])) {
684 // old MySQL reports Type, newer MySQL reports Engine
685 $each_tables[$table_name]['Engine']
686 =& $each_tables[$table_name]['Type'];
689 // MySQL forward compatibility
690 // so pma could use this array as if every server is of version >5.0
691 // todo : remove and check usage in the rest of the code,
692 // MySQL 5.0 is required by current PMA version
693 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
694 $each_tables[$table_name]['TABLE_NAME']
695 =& $each_tables[$table_name]['Name'];
696 $each_tables[$table_name]['ENGINE']
697 =& $each_tables[$table_name]['Engine'];
698 $each_tables[$table_name]['VERSION']
699 =& $each_tables[$table_name]['Version'];
700 $each_tables[$table_name]['ROW_FORMAT']
701 =& $each_tables[$table_name]['Row_format'];
702 $each_tables[$table_name]['TABLE_ROWS']
703 =& $each_tables[$table_name]['Rows'];
704 $each_tables[$table_name]['AVG_ROW_LENGTH']
705 =& $each_tables[$table_name]['Avg_row_length'];
706 $each_tables[$table_name]['DATA_LENGTH']
707 =& $each_tables[$table_name]['Data_length'];
708 $each_tables[$table_name]['MAX_DATA_LENGTH']
709 =& $each_tables[$table_name]['Max_data_length'];
710 $each_tables[$table_name]['INDEX_LENGTH']
711 =& $each_tables[$table_name]['Index_length'];
712 $each_tables[$table_name]['DATA_FREE']
713 =& $each_tables[$table_name]['Data_free'];
714 $each_tables[$table_name]['AUTO_INCREMENT']
715 =& $each_tables[$table_name]['Auto_increment'];
716 $each_tables[$table_name]['CREATE_TIME']
717 =& $each_tables[$table_name]['Create_time'];
718 $each_tables[$table_name]['UPDATE_TIME']
719 =& $each_tables[$table_name]['Update_time'];
720 $each_tables[$table_name]['CHECK_TIME']
721 =& $each_tables[$table_name]['Check_time'];
722 $each_tables[$table_name]['TABLE_COLLATION']
723 =& $each_tables[$table_name]['Collation'];
724 $each_tables[$table_name]['CHECKSUM']
725 =& $each_tables[$table_name]['Checksum'];
726 $each_tables[$table_name]['CREATE_OPTIONS']
727 =& $each_tables[$table_name]['Create_options'];
728 $each_tables[$table_name]['TABLE_COMMENT']
729 =& $each_tables[$table_name]['Comment'];
731 if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
732 && $each_tables[$table_name]['Engine'] == null
734 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
735 } else {
737 * @todo difference between 'TEMPORARY' and 'BASE TABLE'
738 * but how to detect?
740 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
744 $tables[$each_database] = $each_tables;
748 // cache table data
749 // so PMA_Table does not require to issue SHOW TABLE STATUS again
750 // Note: I don't see why we would need array_merge_recursive() here,
751 // as it creates double entries for the same table (for example a double
752 // entry for Comment when changing the storage engine in Operations)
753 // Note 2: Instead of array_merge(), simply use the + operator because
754 // array_merge() renumbers numeric keys starting with 0, therefore
755 // we would lose a db name thats consists only of numbers
756 foreach ($tables as $one_database => $its_tables) {
757 if (isset(PMA_Table::$cache[$one_database])) {
758 PMA_Table::$cache[$one_database]
759 = PMA_Table::$cache[$one_database] + $tables[$one_database];
760 } else {
761 PMA_Table::$cache[$one_database] = $tables[$one_database];
764 unset($one_database, $its_tables);
766 if (! is_array($database)) {
767 if (isset($tables[$database])) {
768 return $tables[$database];
769 } elseif (isset($tables[strtolower($database)])) {
770 // on windows with lower_case_table_names = 1
771 // MySQL returns
772 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
773 // but information_schema.TABLES gives `test`
774 // bug #2036
775 // https://sourceforge.net/p/phpmyadmin/bugs/2036/
776 return $tables[strtolower($database)];
777 } else {
778 // one database but inexact letter case match
779 // as Drizzle is always case insensitive,
780 // we can safely return the only result
781 if (PMA_DRIZZLE && count($tables) == 1) {
782 $keys = array_keys($tables);
783 if (strlen(array_pop($keys)) == strlen($database)) {
784 return array_pop($tables);
787 return $tables;
789 } else {
790 return $tables;
796 * Get VIEWs in a particular database
798 * @param string $db Database name to look in
800 * @return array $views Set of VIEWs inside the database
802 function PMA_DBI_getVirtualTables($db)
805 $tables_full = PMA_DBI_get_tables_full($db);
806 $views = array();
808 foreach ($tables_full as $table=>$tmp) {
810 if (PMA_Table::isView($db, $table)) {
811 $views[] = $table;
816 return $views;
822 * returns array with databases containing extended infos about them
824 * @param string $database database
825 * @param boolean $force_stats retrieve stats also for MySQL < 5
826 * @param resource $link mysql link
827 * @param string $sort_by column to order by
828 * @param string $sort_order ASC or DESC
829 * @param integer $limit_offset starting offset for LIMIT
830 * @param bool|int $limit_count row count for LIMIT or true
831 * for $GLOBALS['cfg']['MaxDbList']
833 * @todo move into PMA_List_Database?
835 * @return array $databases
837 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
838 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
839 $limit_offset = 0, $limit_count = false
841 $sort_order = strtoupper($sort_order);
843 if (true === $limit_count) {
844 $limit_count = $GLOBALS['cfg']['MaxDbList'];
847 // initialize to avoid errors when there are no databases
848 $databases = array();
850 $apply_limit_and_order_manual = true;
852 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
854 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
855 * cause MySQL does not support natural ordering, we have to do it afterward
857 $limit = '';
858 if (!$GLOBALS['cfg']['NaturalOrder']) {
859 if ($limit_count) {
860 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
863 $apply_limit_and_order_manual = false;
866 // get table information from information_schema
867 if ($database) {
868 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
869 . PMA_Util::sqlAddSlashes($database) . '\'';
870 } else {
871 $sql_where_schema = '';
874 if (PMA_DRIZZLE) {
875 // data_dictionary.table_cache may not contain any data for some
876 // tables, it's just a table cache
877 $sql = 'SELECT
878 s.SCHEMA_NAME,
879 s.DEFAULT_COLLATION_NAME';
880 if ($force_stats) {
881 // no TABLE_CACHE data, stable results are better than
882 // constantly changing
883 $sql .= ',
884 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
885 SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
887 $sql .= '
888 FROM data_dictionary.SCHEMAS s';
889 if ($force_stats) {
890 $engine_info = PMA_Util::cacheGet('drizzle_engines', true);
891 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
892 if (isset($engine_info['InnoDB'])
893 && $engine_info['InnoDB']['module_library'] == 'innobase'
895 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS"
896 . " stat ON (t.ENGINE = 'InnoDB' AND stat.NAME"
897 . " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
900 $sql .= "
901 LEFT JOIN data_dictionary.TABLES t
902 ON t.TABLE_SCHEMA = s.SCHEMA_NAME
903 $stats_join";
905 $sql .= $sql_where_schema . '
906 GROUP BY s.SCHEMA_NAME
907 ORDER BY ' . PMA_Util::backquote($sort_by) . ' ' . $sort_order
908 . $limit;
909 } else {
910 $sql = 'SELECT
911 s.SCHEMA_NAME,
912 s.DEFAULT_COLLATION_NAME';
913 if ($force_stats) {
914 $sql .= ',
915 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
916 SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
917 SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
918 SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
919 SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
920 SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
921 AS SCHEMA_LENGTH,
922 SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
924 $sql .= '
925 FROM `information_schema`.SCHEMATA s';
926 if ($force_stats) {
927 $sql .= '
928 LEFT JOIN `information_schema`.TABLES t
929 ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
931 $sql .= $sql_where_schema . '
932 GROUP BY BINARY s.SCHEMA_NAME
933 ORDER BY BINARY ' . PMA_Util::backquote($sort_by)
934 . ' ' . $sort_order
935 . $limit;
938 $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
940 $mysql_error = PMA_DBI_getError($link);
941 if (! count($databases) && $GLOBALS['errno']) {
942 PMA_Util::mysqlDie($mysql_error, $sql);
945 // display only databases also in official database list
946 // f.e. to apply hide_db and only_db
947 $drops = array_diff(
948 array_keys($databases), (array) $GLOBALS['pma']->databases
950 if (count($drops)) {
951 foreach ($drops as $drop) {
952 unset($databases[$drop]);
954 unset($drop);
956 unset($sql_where_schema, $sql, $drops);
957 } else {
958 foreach ($GLOBALS['pma']->databases as $database_name) {
959 // MySQL forward compatibility
960 // so pma could use this array as if every server is of version >5.0
961 // todo : remove and check the rest of the code for usage,
962 // MySQL 5.0 or higher is required for current PMA version
963 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
965 if ($force_stats) {
966 include_once './libraries/mysql_charsets.lib.php';
968 $databases[$database_name]['DEFAULT_COLLATION_NAME']
969 = PMA_getDbCollation($database_name);
971 // get additional info about tables
972 $databases[$database_name]['SCHEMA_TABLES'] = 0;
973 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
974 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
975 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
976 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
977 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
978 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
980 $res = PMA_DBI_query(
981 'SHOW TABLE STATUS FROM '
982 . PMA_Util::backquote($database_name) . ';'
985 while ($row = PMA_DBI_fetch_assoc($res)) {
986 $databases[$database_name]['SCHEMA_TABLES']++;
987 $databases[$database_name]['SCHEMA_TABLE_ROWS']
988 += $row['Rows'];
989 $databases[$database_name]['SCHEMA_DATA_LENGTH']
990 += $row['Data_length'];
991 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
992 += $row['Max_data_length'];
993 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
994 += $row['Index_length'];
996 // for InnoDB, this does not contain the number of
997 // overhead bytes but the total free space
998 if ('InnoDB' != $row['Engine']) {
999 $databases[$database_name]['SCHEMA_DATA_FREE']
1000 += $row['Data_free'];
1002 $databases[$database_name]['SCHEMA_LENGTH']
1003 += $row['Data_length'] + $row['Index_length'];
1005 PMA_DBI_free_result($res);
1006 unset($res);
1013 * apply limit and order manually now
1014 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
1016 if ($apply_limit_and_order_manual) {
1017 $GLOBALS['callback_sort_order'] = $sort_order;
1018 $GLOBALS['callback_sort_by'] = $sort_by;
1019 usort($databases, 'PMA_usort_comparison_callback');
1020 unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
1023 * now apply limit
1025 if ($limit_count) {
1026 $databases = array_slice($databases, $limit_offset, $limit_count);
1030 return $databases;
1034 * returns detailed array with all columns for given table in database,
1035 * or all tables/databases
1037 * @param string $database name of database
1038 * @param string $table name of table to retrieve columns from
1039 * @param string $column name of specific column
1040 * @param mixed $link mysql link resource
1042 * @return array
1044 function PMA_DBI_get_columns_full($database = null, $table = null,
1045 $column = null, $link = null
1047 $columns = array();
1049 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1050 $sql_wheres = array();
1051 $array_keys = array();
1053 // get columns information from information_schema
1054 if (null !== $database) {
1055 $sql_wheres[] = '`TABLE_SCHEMA` = \''
1056 . PMA_Util::sqlAddSlashes($database) . '\' ';
1057 } else {
1058 $array_keys[] = 'TABLE_SCHEMA';
1060 if (null !== $table) {
1061 $sql_wheres[] = '`TABLE_NAME` = \''
1062 . PMA_Util::sqlAddSlashes($table) . '\' ';
1063 } else {
1064 $array_keys[] = 'TABLE_NAME';
1066 if (null !== $column) {
1067 $sql_wheres[] = '`COLUMN_NAME` = \''
1068 . PMA_Util::sqlAddSlashes($column) . '\' ';
1069 } else {
1070 $array_keys[] = 'COLUMN_NAME';
1073 // for PMA bc:
1074 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
1075 if (PMA_DRIZZLE) {
1076 $sql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME,
1077 column_name AS `Field`,
1078 (CASE
1079 WHEN character_maximum_length > 0
1080 THEN concat(lower(data_type), '(', character_maximum_length, ')')
1081 WHEN numeric_precision > 0 OR numeric_scale > 0
1082 THEN concat(lower(data_type), '(', numeric_precision,
1083 ',', numeric_scale, ')')
1084 WHEN enum_values IS NOT NULL
1085 THEN concat(lower(data_type), '(', enum_values, ')')
1086 ELSE lower(data_type) END)
1087 AS `Type`,
1088 collation_name AS `Collation`,
1089 (CASE is_nullable
1090 WHEN 1 THEN 'YES'
1091 ELSE 'NO' END) AS `Null`,
1092 (CASE
1093 WHEN is_used_in_primary THEN 'PRI'
1094 ELSE '' END) AS `Key`,
1095 column_default AS `Default`,
1096 (CASE
1097 WHEN is_auto_increment THEN 'auto_increment'
1098 WHEN column_default_update
1099 THEN 'on update ' || column_default_update
1100 ELSE '' END) AS `Extra`,
1101 NULL AS `Privileges`,
1102 column_comment AS `Comment`
1103 FROM data_dictionary.columns";
1104 } else {
1105 $sql = '
1106 SELECT *,
1107 `COLUMN_NAME` AS `Field`,
1108 `COLUMN_TYPE` AS `Type`,
1109 `COLLATION_NAME` AS `Collation`,
1110 `IS_NULLABLE` AS `Null`,
1111 `COLUMN_KEY` AS `Key`,
1112 `COLUMN_DEFAULT` AS `Default`,
1113 `EXTRA` AS `Extra`,
1114 `PRIVILEGES` AS `Privileges`,
1115 `COLUMN_COMMENT` AS `Comment`
1116 FROM `information_schema`.`COLUMNS`';
1118 if (count($sql_wheres)) {
1119 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
1122 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
1123 unset($sql_wheres, $sql);
1124 } else {
1125 if (null === $database) {
1126 foreach ($GLOBALS['pma']->databases as $database) {
1127 $columns[$database] = PMA_DBI_get_columns_full(
1128 $database, null, null, $link
1131 return $columns;
1132 } elseif (null === $table) {
1133 $tables = PMA_DBI_get_tables($database);
1134 foreach ($tables as $table) {
1135 $columns[$table] = PMA_DBI_get_columns_full(
1136 $database, $table, null, $link
1139 return $columns;
1142 $sql = 'SHOW FULL COLUMNS FROM '
1143 . PMA_Util::backquote($database) . '.' . PMA_Util::backquote($table);
1144 if (null !== $column) {
1145 $sql .= " LIKE '" . PMA_Util::sqlAddSlashes($column, true) . "'";
1148 $columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
1150 $ordinal_position = 1;
1151 foreach ($columns as $column_name => $each_column) {
1153 // MySQL forward compatibility
1154 // so pma could use this array as if every server is of version >5.0
1155 // todo : remove and check the rest of the code for usage,
1156 // MySQL 5.0 or higher is required for current PMA version
1157 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
1158 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
1159 $columns[$column_name]['COLLATION_NAME']
1160 =& $columns[$column_name]['Collation'];
1161 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
1162 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
1163 $columns[$column_name]['COLUMN_DEFAULT']
1164 =& $columns[$column_name]['Default'];
1165 $columns[$column_name]['EXTRA']
1166 =& $columns[$column_name]['Extra'];
1167 $columns[$column_name]['PRIVILEGES']
1168 =& $columns[$column_name]['Privileges'];
1169 $columns[$column_name]['COLUMN_COMMENT']
1170 =& $columns[$column_name]['Comment'];
1172 $columns[$column_name]['TABLE_CATALOG'] = null;
1173 $columns[$column_name]['TABLE_SCHEMA'] = $database;
1174 $columns[$column_name]['TABLE_NAME'] = $table;
1175 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
1176 $columns[$column_name]['DATA_TYPE']
1177 = substr(
1178 $columns[$column_name]['COLUMN_TYPE'],
1180 strpos($columns[$column_name]['COLUMN_TYPE'], '(')
1183 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
1185 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
1187 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
1189 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
1190 $columns[$column_name]['NUMERIC_PRECISION'] = null;
1191 $columns[$column_name]['NUMERIC_SCALE'] = null;
1192 $columns[$column_name]['CHARACTER_SET_NAME']
1193 = substr(
1194 $columns[$column_name]['COLLATION_NAME'],
1196 strpos($columns[$column_name]['COLLATION_NAME'], '_')
1199 $ordinal_position++;
1202 if (null !== $column) {
1203 reset($columns);
1204 $columns = current($columns);
1207 return $columns;
1211 * Returns SQL query for fetching columns for a table
1213 * The 'Key' column is not calculated properly, use PMA_DBI_get_columns() to get
1214 * correct values.
1216 * @param string $database name of database
1217 * @param string $table name of table to retrieve columns from
1218 * @param string $column name of column, null to show all columns
1219 * @param boolean $full whether to return full info or only column names
1221 * @see PMA_DBI_get_columns()
1223 * @return string
1225 function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
1227 if (PMA_DRIZZLE) {
1228 // `Key` column:
1229 // * used in primary key => PRI
1230 // * unique one-column => UNI
1231 // * indexed, one-column or first in multi-column => MUL
1232 // Promotion of UNI to PRI in case no promary index exists
1233 // is done after query is executed
1234 $sql = "SELECT
1235 column_name AS `Field`,
1236 (CASE
1237 WHEN character_maximum_length > 0
1238 THEN concat(lower(data_type), '(', character_maximum_length, ')')
1239 WHEN numeric_precision > 0 OR numeric_scale > 0
1240 THEN concat(lower(data_type), '(', numeric_precision,
1241 ',', numeric_scale, ')')
1242 WHEN enum_values IS NOT NULL
1243 THEN concat(lower(data_type), '(', enum_values, ')')
1244 ELSE lower(data_type) END)
1245 AS `Type`,
1246 " . ($full ? "
1247 collation_name AS `Collation`," : '') . "
1248 (CASE is_nullable
1249 WHEN 1 THEN 'YES'
1250 ELSE 'NO' END) AS `Null`,
1251 (CASE
1252 WHEN is_used_in_primary THEN 'PRI'
1253 WHEN is_unique AND NOT is_multi THEN 'UNI'
1254 WHEN is_indexed
1255 AND (NOT is_multi OR is_first_in_multi) THEN 'MUL'
1256 ELSE '' END) AS `Key`,
1257 column_default AS `Default`,
1258 (CASE
1259 WHEN is_auto_increment THEN 'auto_increment'
1260 WHEN column_default_update <> ''
1261 THEN 'on update ' || column_default_update
1262 ELSE '' END) AS `Extra`
1263 " . ($full ? " ,
1264 NULL AS `Privileges`,
1265 column_comment AS `Comment`" : '') . "
1266 FROM data_dictionary.columns
1267 WHERE table_schema = '" . PMA_Util::sqlAddSlashes($database) . "'
1268 AND table_name = '" . PMA_Util::sqlAddSlashes($table) . "'
1269 " . (($column != null) ? "
1270 AND column_name = '" . PMA_Util::sqlAddSlashes($column) . "'" : '');
1271 // ORDER BY ordinal_position
1272 } else {
1273 $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS FROM '
1274 . PMA_Util::backquote($database) . '.' . PMA_Util::backquote($table)
1275 . (($column != null) ? "LIKE '"
1276 . PMA_Util::sqlAddSlashes($column, true) . "'" : '');
1278 return $sql;
1282 * Returns descriptions of columns in given table (all or given by $column)
1284 * @param string $database name of database
1285 * @param string $table name of table to retrieve columns from
1286 * @param string $column name of column, null to show all columns
1287 * @param boolean $full whether to return full info or only column names
1288 * @param mixed $link mysql link resource
1290 * @return false|array array indexed by column names or,
1291 * if $column is given, flat array description
1293 function PMA_DBI_get_columns($database, $table, $column = null, $full = false,
1294 $link = null
1296 $sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
1297 $fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
1298 if (! is_array($fields) || count($fields) == 0) {
1299 return null;
1301 if (PMA_DRIZZLE) {
1302 // fix Key column, it's much simpler in PHP than in SQL
1303 $has_pk = false;
1304 $has_pk_candidates = false;
1305 foreach ($fields as $f) {
1306 if ($f['Key'] == 'PRI') {
1307 $has_pk = true;
1308 break;
1309 } else if ($f['Null'] == 'NO'
1310 && ($f['Key'] == 'MUL'
1311 || $f['Key'] == 'UNI')
1313 $has_pk_candidates = true;
1316 if (!$has_pk && $has_pk_candidates) {
1317 // check whether we can promote some unique index to PRI
1318 $sql = "
1319 SELECT i.index_name, p.column_name
1320 FROM data_dictionary.indexes i
1321 JOIN data_dictionary.index_parts p
1322 USING (table_schema, table_name)
1323 WHERE i.table_schema = '" . PMA_Util::sqlAddSlashes($database) . "'
1324 AND i.table_name = '" . PMA_Util::sqlAddSlashes($table) . "'
1325 AND i.is_unique
1326 AND NOT i.is_nullable";
1327 $fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
1328 $fs = $fs ? array_shift($fs) : array();
1329 foreach ($fs as $f) {
1330 $fields[$f]['Key'] = 'PRI';
1335 return ($column != null) ? array_shift($fields) : $fields;
1339 * Returns all column names in given table
1341 * @param string $database name of database
1342 * @param string $table name of table to retrieve columns from
1343 * @param mixed $link mysql link resource
1345 * @return null|array
1347 function PMA_DBI_get_column_names($database, $table, $link = null)
1349 $sql = PMA_DBI_get_columns_sql($database, $table);
1350 // We only need the 'Field' column which contains the table's column names
1351 $fields = array_keys(PMA_DBI_fetch_result($sql, 'Field', null, $link));
1353 if ( ! is_array($fields) || count($fields) == 0 ) {
1354 return null;
1356 return $fields;
1360 * Returns SQL for fetching information on table indexes (SHOW INDEXES)
1362 * @param string $database name of database
1363 * @param string $table name of the table whose indexes are to be retreived
1364 * @param string $where additional conditions for WHERE
1366 * @return array $indexes
1368 function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
1370 if (PMA_DRIZZLE) {
1371 $sql = "SELECT
1372 ip.table_name AS `Table`,
1373 (NOT ip.is_unique) AS Non_unique,
1374 ip.index_name AS Key_name,
1375 ip.sequence_in_index+1 AS Seq_in_index,
1376 ip.column_name AS Column_name,
1377 (CASE
1378 WHEN i.index_type = 'BTREE' THEN 'A'
1379 ELSE NULL END) AS Collation,
1380 NULL AS Cardinality,
1381 compare_length AS Sub_part,
1382 NULL AS Packed,
1383 ip.is_nullable AS `Null`,
1384 i.index_type AS Index_type,
1385 NULL AS Comment,
1386 i.index_comment AS Index_comment
1387 FROM data_dictionary.index_parts ip
1388 LEFT JOIN data_dictionary.indexes i
1389 USING (table_schema, table_name, index_name)
1390 WHERE table_schema = '" . PMA_Util::sqlAddSlashes($database) . "'
1391 AND table_name = '" . PMA_Util::sqlAddSlashes($table) . "'
1393 } else {
1394 $sql = 'SHOW INDEXES FROM ' . PMA_Util::backquote($database) . '.'
1395 . PMA_Util::backquote($table);
1397 if ($where) {
1398 $sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
1400 return $sql;
1404 * Returns indexes of a table
1406 * @param string $database name of database
1407 * @param string $table name of the table whose indexes are to be retrieved
1408 * @param mixed $link mysql link resource
1410 * @return array $indexes
1412 function PMA_DBI_get_table_indexes($database, $table, $link = null)
1414 $sql = PMA_DBI_get_table_indexes_sql($database, $table);
1415 $indexes = PMA_DBI_fetch_result($sql, null, null, $link);
1417 if (! is_array($indexes) || count($indexes) < 1) {
1418 return array();
1420 return $indexes;
1424 * returns value of given mysql server variable
1426 * @param string $var mysql server variable name
1427 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
1428 * @param mixed $link mysql link resource|object
1430 * @return mixed value for mysql server variable
1432 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
1434 if ($link === null) {
1435 if (isset($GLOBALS['userlink'])) {
1436 $link = $GLOBALS['userlink'];
1437 } else {
1438 return false;
1442 switch ($type) {
1443 case PMA_DBI_GETVAR_SESSION:
1444 $modifier = ' SESSION';
1445 break;
1446 case PMA_DBI_GETVAR_GLOBAL:
1447 $modifier = ' GLOBAL';
1448 break;
1449 default:
1450 $modifier = '';
1452 return PMA_DBI_fetch_value(
1453 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link
1458 * Function called just after a connection to the MySQL database server has
1459 * been established. It sets the connection collation, and determins the
1460 * version of MySQL which is running.
1462 * @param mixed $link mysql link resource|object
1463 * @param boolean $is_controluser whether link is for control user
1465 * @return void
1467 function PMA_DBI_postConnect($link, $is_controluser = false)
1469 if (! defined('PMA_MYSQL_INT_VERSION')) {
1470 if (PMA_Util::cacheExists('PMA_MYSQL_INT_VERSION', true)) {
1471 define(
1472 'PMA_MYSQL_INT_VERSION',
1473 PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
1475 define(
1476 'PMA_MYSQL_MAJOR_VERSION',
1477 PMA_Util::cacheGet('PMA_MYSQL_MAJOR_VERSION', true)
1479 define(
1480 'PMA_MYSQL_STR_VERSION',
1481 PMA_Util::cacheGet('PMA_MYSQL_STR_VERSION', true)
1483 define(
1484 'PMA_MYSQL_VERSION_COMMENT',
1485 PMA_Util::cacheGet('PMA_MYSQL_VERSION_COMMENT', true)
1487 } else {
1488 $version = PMA_DBI_fetch_single_row(
1489 'SELECT @@version, @@version_comment',
1490 'ASSOC',
1491 $link
1494 if ($version) {
1495 $match = explode('.', $version['@@version']);
1496 define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
1497 define(
1498 'PMA_MYSQL_INT_VERSION',
1499 (int) sprintf(
1500 '%d%02d%02d', $match[0], $match[1], intval($match[2])
1503 define('PMA_MYSQL_STR_VERSION', $version['@@version']);
1504 define('PMA_MYSQL_VERSION_COMMENT', $version['@@version_comment']);
1505 } else {
1506 define('PMA_MYSQL_INT_VERSION', 50015);
1507 define('PMA_MYSQL_MAJOR_VERSION', 5);
1508 define('PMA_MYSQL_STR_VERSION', '5.00.15');
1509 define('PMA_MYSQL_VERSION_COMMENT', '');
1511 PMA_Util::cacheSet(
1512 'PMA_MYSQL_INT_VERSION',
1513 PMA_MYSQL_INT_VERSION,
1514 true
1516 PMA_Util::cacheSet(
1517 'PMA_MYSQL_MAJOR_VERSION',
1518 PMA_MYSQL_MAJOR_VERSION,
1519 true
1521 PMA_Util::cacheSet(
1522 'PMA_MYSQL_STR_VERSION',
1523 PMA_MYSQL_STR_VERSION,
1524 true
1526 PMA_Util::cacheSet(
1527 'PMA_MYSQL_VERSION_COMMENT',
1528 PMA_MYSQL_VERSION_COMMENT,
1529 true
1532 // detect Drizzle by version number:
1533 // <year>.<month>.<build number>(.<patch rev)
1534 define('PMA_DRIZZLE', PMA_MYSQL_MAJOR_VERSION >= 2009);
1537 // Skip charsets for Drizzle
1538 if (!PMA_DRIZZLE) {
1539 if (! empty($GLOBALS['collation_connection'])) {
1540 PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
1541 $set_collation_con_query = "SET collation_connection = '"
1542 . PMA_Util::sqlAddSlashes($GLOBALS['collation_connection']) . "';";
1543 PMA_DBI_query(
1544 $set_collation_con_query,
1545 $link,
1546 PMA_DBI_QUERY_STORE
1548 } else {
1549 PMA_DBI_query(
1550 "SET NAMES 'utf8' COLLATE 'utf8_general_ci';",
1551 $link,
1552 PMA_DBI_QUERY_STORE
1557 // Cache plugin list for Drizzle
1558 if (PMA_DRIZZLE && !PMA_Util::cacheExists('drizzle_engines', true)) {
1559 $sql = "SELECT p.plugin_name, m.module_library
1560 FROM data_dictionary.plugins p
1561 JOIN data_dictionary.modules m USING (module_name)
1562 WHERE p.plugin_type = 'StorageEngine'
1563 AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
1564 AND p.is_active = 'YES'";
1565 $engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
1566 PMA_Util::cacheSet('drizzle_engines', $engines, true);
1571 * returns a single value from the given result or query,
1572 * if the query or the result has more than one row or field
1573 * the first field of the first row is returned
1575 * <code>
1576 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
1577 * $user_name = PMA_DBI_fetch_value($sql);
1578 * // produces
1579 * // $user_name = 'John Doe'
1580 * </code>
1582 * @param string|mysql_result $result query or mysql result
1583 * @param integer $row_number row to fetch the value from,
1584 * starting at 0, with 0 being default
1585 * @param integer|string $field field to fetch the value from,
1586 * starting at 0, with 0 being default
1587 * @param resource $link mysql link
1589 * @return mixed value of first field in first row from result
1590 * or false if not found
1592 function PMA_DBI_fetch_value($result, $row_number = 0, $field = 0, $link = null)
1594 $value = false;
1596 if (is_string($result)) {
1597 $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
1600 // return false if result is empty or false
1601 // or requested row is larger than rows in result
1602 if (PMA_DBI_num_rows($result) < ($row_number + 1)) {
1603 return $value;
1606 // if $field is an integer use non associative mysql fetch function
1607 if (is_int($field)) {
1608 $fetch_function = 'PMA_DBI_fetch_row';
1609 } else {
1610 $fetch_function = 'PMA_DBI_fetch_assoc';
1613 // get requested row
1614 for ($i = 0; $i <= $row_number; $i++) {
1615 $row = $fetch_function($result);
1617 PMA_DBI_free_result($result);
1619 // return requested field
1620 if (isset($row[$field])) {
1621 $value = $row[$field];
1623 unset($row);
1625 return $value;
1629 * returns only the first row from the result
1631 * <code>
1632 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
1633 * $user = PMA_DBI_fetch_single_row($sql);
1634 * // produces
1635 * // $user = array('id' => 123, 'name' => 'John Doe')
1636 * </code>
1638 * @param string|mysql_result $result query or mysql result
1639 * @param string $type NUM|ASSOC|BOTH
1640 * returned array should either numeric
1641 * associativ or booth
1642 * @param resource $link mysql link
1644 * @return array|boolean first row from result
1645 * or false if result is empty
1647 function PMA_DBI_fetch_single_row($result, $type = 'ASSOC', $link = null)
1649 if (is_string($result)) {
1650 $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
1653 // return null if result is empty or false
1654 if (! PMA_DBI_num_rows($result)) {
1655 return false;
1658 switch ($type) {
1659 case 'NUM' :
1660 $fetch_function = 'PMA_DBI_fetch_row';
1661 break;
1662 case 'ASSOC' :
1663 $fetch_function = 'PMA_DBI_fetch_assoc';
1664 break;
1665 case 'BOTH' :
1666 default :
1667 $fetch_function = 'PMA_DBI_fetch_array';
1668 break;
1671 $row = $fetch_function($result);
1672 PMA_DBI_free_result($result);
1673 return $row;
1677 * returns all rows in the resultset in one array
1679 * <code>
1680 * $sql = 'SELECT * FROM `user`';
1681 * $users = PMA_DBI_fetch_result($sql);
1682 * // produces
1683 * // $users[] = array('id' => 123, 'name' => 'John Doe')
1685 * $sql = 'SELECT `id`, `name` FROM `user`';
1686 * $users = PMA_DBI_fetch_result($sql, 'id');
1687 * // produces
1688 * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
1690 * $sql = 'SELECT `id`, `name` FROM `user`';
1691 * $users = PMA_DBI_fetch_result($sql, 0);
1692 * // produces
1693 * // $users['123'] = array(0 => 123, 1 => 'John Doe')
1695 * $sql = 'SELECT `id`, `name` FROM `user`';
1696 * $users = PMA_DBI_fetch_result($sql, 'id', 'name');
1697 * // or
1698 * $users = PMA_DBI_fetch_result($sql, 0, 1);
1699 * // produces
1700 * // $users['123'] = 'John Doe'
1702 * $sql = 'SELECT `name` FROM `user`';
1703 * $users = PMA_DBI_fetch_result($sql);
1704 * // produces
1705 * // $users[] = 'John Doe'
1707 * $sql = 'SELECT `group`, `name` FROM `user`'
1708 * $users = PMA_DBI_fetch_result($sql, array('group', null), 'name');
1709 * // produces
1710 * // $users['admin'][] = 'John Doe'
1712 * $sql = 'SELECT `group`, `name` FROM `user`'
1713 * $users = PMA_DBI_fetch_result($sql, array('group', 'name'), 'id');
1714 * // produces
1715 * // $users['admin']['John Doe'] = '123'
1716 * </code>
1718 * @param string|mysql_result $result query or mysql result
1719 * @param string|integer $key field-name or offset
1720 * used as key for array
1721 * @param string|integer $value value-name or offset
1722 * used as value for array
1723 * @param resource $link mysql link
1724 * @param mixed $options query options
1726 * @return array resultrows or values indexed by $key
1728 function PMA_DBI_fetch_result($result, $key = null, $value = null,
1729 $link = null, $options = 0
1731 $resultrows = array();
1733 if (is_string($result)) {
1734 $result = PMA_DBI_try_query($result, $link, $options, false);
1737 // return empty array if result is empty or false
1738 if (! $result) {
1739 return $resultrows;
1742 $fetch_function = 'PMA_DBI_fetch_assoc';
1744 // no nested array if only one field is in result
1745 if (null === $key && 1 === PMA_DBI_num_fields($result)) {
1746 $value = 0;
1747 $fetch_function = 'PMA_DBI_fetch_row';
1750 // if $key is an integer use non associative mysql fetch function
1751 if (is_int($key)) {
1752 $fetch_function = 'PMA_DBI_fetch_row';
1755 if (null === $key && null === $value) {
1756 while ($row = $fetch_function($result)) {
1757 $resultrows[] = $row;
1759 } elseif (null === $key) {
1760 while ($row = $fetch_function($result)) {
1761 $resultrows[] = $row[$value];
1763 } elseif (null === $value) {
1764 if (is_array($key)) {
1765 while ($row = $fetch_function($result)) {
1766 $result_target =& $resultrows;
1767 foreach ($key as $key_index) {
1768 if (null === $key_index) {
1769 $result_target =& $result_target[];
1770 continue;
1773 if (! isset($result_target[$row[$key_index]])) {
1774 $result_target[$row[$key_index]] = array();
1776 $result_target =& $result_target[$row[$key_index]];
1778 $result_target = $row;
1780 } else {
1781 while ($row = $fetch_function($result)) {
1782 $resultrows[$row[$key]] = $row;
1785 } else {
1786 if (is_array($key)) {
1787 while ($row = $fetch_function($result)) {
1788 $result_target =& $resultrows;
1789 foreach ($key as $key_index) {
1790 if (null === $key_index) {
1791 $result_target =& $result_target[];
1792 continue;
1795 if (! isset($result_target[$row[$key_index]])) {
1796 $result_target[$row[$key_index]] = array();
1798 $result_target =& $result_target[$row[$key_index]];
1800 $result_target = $row[$value];
1802 } else {
1803 while ($row = $fetch_function($result)) {
1804 $resultrows[$row[$key]] = $row[$value];
1809 PMA_DBI_free_result($result);
1810 return $resultrows;
1814 * Get supported SQL compatibility modes
1816 * @return array supported SQL compatibility modes
1818 function PMA_DBI_getCompatibilities()
1820 // Drizzle doesn't support compatibility modes
1821 if (PMA_DRIZZLE) {
1822 return array();
1825 $compats = array('NONE');
1826 $compats[] = 'ANSI';
1827 $compats[] = 'DB2';
1828 $compats[] = 'MAXDB';
1829 $compats[] = 'MYSQL323';
1830 $compats[] = 'MYSQL40';
1831 $compats[] = 'MSSQL';
1832 $compats[] = 'ORACLE';
1833 // removed; in MySQL 5.0.33, this produces exports that
1834 // can't be read by POSTGRESQL (see our bug #1596328)
1835 //$compats[] = 'POSTGRESQL';
1836 $compats[] = 'TRADITIONAL';
1838 return $compats;
1842 * returns warnings for last query
1844 * @param resource $link mysql link resource
1846 * @return array warnings
1848 function PMA_DBI_get_warnings($link = null)
1850 if (empty($link)) {
1851 if (isset($GLOBALS['userlink'])) {
1852 $link = $GLOBALS['userlink'];
1853 } else {
1854 return array();
1858 return PMA_DBI_fetch_result('SHOW WARNINGS', null, null, $link);
1862 * returns true (int > 0) if current user is superuser
1863 * otherwise 0
1865 * @return bool Whether use is a superuser
1867 function PMA_isSuperuser()
1869 if (PMA_Util::cacheExists('is_superuser', true)) {
1870 return PMA_Util::cacheGet('is_superuser', true);
1873 // when connection failed we don't have a $userlink
1874 if (isset($GLOBALS['userlink'])) {
1875 if (PMA_DRIZZLE) {
1876 // Drizzle has no authorization by default, so when no plugin is
1877 // enabled everyone is a superuser
1878 // Known authorization libraries: regex_policy, simple_user_policy
1879 // Plugins limit object visibility (dbs, tables, processes), we can
1880 // safely assume we always deal with superuser
1881 $result = true;
1882 } else {
1883 // check access to mysql.user table
1884 $result = (bool) PMA_DBI_try_query(
1885 'SELECT COUNT(*) FROM mysql.user',
1886 $GLOBALS['userlink'],
1887 PMA_DBI_QUERY_STORE
1890 PMA_Util::cacheSet('is_superuser', $result, true);
1891 } else {
1892 PMA_Util::cacheSet('is_superuser', false, true);
1895 return PMA_Util::cacheGet('is_superuser', true);
1899 * returns an array of PROCEDURE or FUNCTION names for a db
1901 * @param string $db db name
1902 * @param string $which PROCEDURE | FUNCTION
1903 * @param resource $link mysql link
1905 * @return array the procedure names or function names
1907 function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
1909 if (PMA_DRIZZLE) {
1910 // Drizzle doesn't support functions and procedures
1911 return array();
1913 $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
1914 $result = array();
1915 foreach ($shows as $one_show) {
1916 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1917 $result[] = $one_show['Name'];
1920 return($result);
1924 * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
1926 * @param string $db db name
1927 * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
1928 * @param string $name the procedure|function|event|view name
1929 * @param resource $link mysql link
1931 * @return string the definition
1933 function PMA_DBI_get_definition($db, $which, $name, $link = null)
1935 $returned_field = array(
1936 'PROCEDURE' => 'Create Procedure',
1937 'FUNCTION' => 'Create Function',
1938 'EVENT' => 'Create Event',
1939 'VIEW' => 'Create View'
1941 $query = 'SHOW CREATE ' . $which . ' '
1942 . PMA_Util::backquote($db) . '.'
1943 . PMA_Util::backquote($name);
1944 return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
1948 * returns details about the TRIGGERs for a specific table or database
1950 * @param string $db db name
1951 * @param string $table table name
1952 * @param string $delimiter the delimiter to use (may be empty)
1954 * @return array information about triggers (may be empty)
1956 function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
1958 if (PMA_DRIZZLE) {
1959 // Drizzle doesn't support triggers
1960 return array();
1963 $result = array();
1964 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1965 // Note: in http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html
1966 // their example uses WHERE TRIGGER_SCHEMA='dbname' so let's use this
1967 // instead of WHERE EVENT_OBJECT_SCHEMA='dbname'
1968 $query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
1969 . ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
1970 . ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
1971 . ' FROM information_schema.TRIGGERS'
1972 . ' WHERE TRIGGER_SCHEMA= \'' . PMA_Util::sqlAddSlashes($db) . '\'';
1974 if (! empty($table)) {
1975 $query .= " AND EVENT_OBJECT_TABLE = '"
1976 . PMA_Util::sqlAddSlashes($table) . "';";
1978 } else {
1979 $query = "SHOW TRIGGERS FROM " . PMA_Util::backquote($db);
1980 if (! empty($table)) {
1981 $query .= " LIKE '" . PMA_Util::sqlAddSlashes($table, true) . "';";
1985 if ($triggers = PMA_DBI_fetch_result($query)) {
1986 foreach ($triggers as $trigger) {
1987 if ($GLOBALS['cfg']['Server']['DisableIS']) {
1988 $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
1989 $trigger['ACTION_TIMING'] = $trigger['Timing'];
1990 $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
1991 $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
1992 $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
1993 $trigger['DEFINER'] = $trigger['Definer'];
1995 $one_result = array();
1996 $one_result['name'] = $trigger['TRIGGER_NAME'];
1997 $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
1998 $one_result['action_timing'] = $trigger['ACTION_TIMING'];
1999 $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
2000 $one_result['definition'] = $trigger['ACTION_STATEMENT'];
2001 $one_result['definer'] = $trigger['DEFINER'];
2003 // do not prepend the schema name; this way, importing the
2004 // definition into another schema will work
2005 $one_result['full_trigger_name'] = PMA_Util::backquote(
2006 $trigger['TRIGGER_NAME']
2008 $one_result['drop'] = 'DROP TRIGGER IF EXISTS '
2009 . $one_result['full_trigger_name'];
2010 $one_result['create'] = 'CREATE TRIGGER '
2011 . $one_result['full_trigger_name'] . ' '
2012 . $trigger['ACTION_TIMING']. ' '
2013 . $trigger['EVENT_MANIPULATION']
2014 . ' ON ' . PMA_Util::backquote($trigger['EVENT_OBJECT_TABLE'])
2015 . "\n" . ' FOR EACH ROW '
2016 . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
2018 $result[] = $one_result;
2022 // Sort results by name
2023 $name = array();
2024 foreach ($result as $value) {
2025 $name[] = $value['name'];
2027 array_multisort($name, SORT_ASC, $result);
2029 return($result);
2033 * Formats database error message in a friendly way.
2034 * This is needed because some errors messages cannot
2035 * be obtained by mysql_error().
2037 * @param int $error_number Error code
2038 * @param string $error_message Error message as returned by server
2040 * @return string HML text with error details
2042 function PMA_DBI_formatError($error_number, $error_message)
2044 if (! empty($error_message)) {
2045 $error_message = PMA_DBI_convert_message($error_message);
2048 $error_message = htmlspecialchars($error_message);
2050 $error = '#' . ((string) $error_number);
2052 if ($error_number == 2002) {
2053 $error .= ' - ' . $error_message;
2054 $error .= '<br />';
2055 $error .= __(
2056 'The server is not responding (or the local server\'s socket'
2057 . ' is not correctly configured).'
2059 } elseif ($error_number == 2003) {
2060 $error .= ' - ' . $error_message;
2061 $error .= '<br />' . __('The server is not responding.');
2062 } elseif ($error_number == 1005) {
2063 if (strpos($error_message, 'errno: 13') !== false) {
2064 $error .= ' - ' . $error_message;
2065 $error .= '<br />'
2066 . __('Please check privileges of directory containing database.');
2067 } else {
2068 /* InnoDB contraints, see
2069 * http://dev.mysql.com/doc/refman/5.0/en/
2070 * innodb-foreign-key-constraints.html
2072 $error .= ' - ' . $error_message .
2073 ' (<a href="server_engines.php' .
2074 PMA_generate_common_url(
2075 array('engine' => 'InnoDB', 'page' => 'Status')
2076 ) . '">' . __('Details…') . '</a>)';
2078 } else {
2079 $error .= ' - ' . $error_message;
2082 return $error;
2086 * Checks whether given schema is a system schema: information_schema
2087 * (MySQL and Drizzle) or data_dictionary (Drizzle)
2089 * @param string $schema_name Name of schema (database) to test
2090 * @param bool $test_for_mysql_schema Whether 'mysql' schema should
2091 * be treated the same as IS and DD
2093 * @return bool
2095 function PMA_is_system_schema($schema_name, $test_for_mysql_schema = false)
2097 return strtolower($schema_name) == 'information_schema'
2098 || (!PMA_DRIZZLE && strtolower($schema_name) == 'performance_schema')
2099 || (PMA_DRIZZLE && strtolower($schema_name) == 'data_dictionary')
2100 || ($test_for_mysql_schema && !PMA_DRIZZLE && $schema_name == 'mysql');
2104 * Get regular expression which occur first inside the given sql query.
2106 * @param Array $regex_array Comparing regular expressions.
2107 * @param String $query SQL query to be checked.
2109 * @return String Matching regular expression.
2111 function PMA_getFirstOccurringRegularExpression($regex_array, $query)
2114 $minimum_first_occurence_index = null;
2115 $regex = null;
2117 for ($i = 0; $i < count($regex_array); $i++) {
2118 if (preg_match($regex_array[$i], $query, $matches, PREG_OFFSET_CAPTURE)) {
2120 if (is_null($minimum_first_occurence_index)
2121 || ($matches[0][1] < $minimum_first_occurence_index)
2123 $regex = $regex_array[$i];
2124 $minimum_first_occurence_index = $matches[0][1];
2130 return $regex;