Translated using Weblate.
[phpmyadmin.git] / libraries / database_interface.lib.php
blob8d8f37e0950ca2da974aff26757d8049c369fe2e
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Common Option Constants For DBI Functions
6 * @package PhpMyAdmin
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 /**
48 * check for requested extension
50 if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
52 // if it fails try alternative extension ...
53 // and display an error ...
55 /**
56 * @todo add different messages for alternative extension
57 * and complete fail (no alternative extension too)
59 PMA_warnMissingExtension(
60 $GLOBALS['cfg']['Server']['extension'],
61 false,
62 PMA_showDocu('faqmysql')
65 if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
66 $alternativ_extension = 'mysqli';
67 } else {
68 $alternativ_extension = 'mysql';
71 if (! PMA_DBI_checkDbExtension($alternativ_extension)) {
72 // if alternative fails too ...
73 PMA_warnMissingExtension(
74 $GLOBALS['cfg']['Server']['extension'],
75 true,
76 PMA_showDocu('faqmysql')
80 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
81 unset($alternativ_extension);
84 /**
85 * Including The DBI Plugin
87 require_once './libraries/dbi/'
88 . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php';
90 /**
91 * runs a query
93 * @param string $query SQL query to execte
94 * @param mixed $link optional database link to use
95 * @param int $options optional query options
96 * @param bool $cache_affected_rows whether to cache affected rows
98 * @return mixed
100 function PMA_DBI_query($query, $link = null, $options = 0, $cache_affected_rows = true)
102 $res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
103 or PMA_mysqlDie(PMA_DBI_getError($link), $query);
104 return $res;
108 * runs a query and returns the result
110 * @param string $query query to run
111 * @param resource $link mysql link resource
112 * @param integer $options query options
113 * @param bool $cache_affected_rows whether to cache affected row
115 * @return mixed
117 function PMA_DBI_try_query($query, $link = null, $options = 0, $cache_affected_rows = true)
119 if (empty($link)) {
120 if (isset($GLOBALS['userlink'])) {
121 $link = $GLOBALS['userlink'];
122 } else {
123 return false;
127 if ($GLOBALS['cfg']['DBG']['sql']) {
128 $time = microtime(true);
131 $r = PMA_DBI_real_query($query, $link, $options);
133 if ($cache_affected_rows) {
134 $GLOBALS['cached_affected_rows'] = PMA_DBI_affected_rows($link, $get_from_cache = false);
137 if ($GLOBALS['cfg']['DBG']['sql']) {
138 $time = microtime(true) - $time;
140 $hash = md5($query);
142 if (isset($_SESSION['debug']['queries'][$hash])) {
143 $_SESSION['debug']['queries'][$hash]['count']++;
144 } else {
145 $_SESSION['debug']['queries'][$hash] = array();
146 if ($r == false) {
147 $_SESSION['debug']['queries'][$hash]['error'] = '<b style="color:red">'.mysqli_error($link).'</b>';
149 $_SESSION['debug']['queries'][$hash]['count'] = 1;
150 $_SESSION['debug']['queries'][$hash]['query'] = $query;
151 $_SESSION['debug']['queries'][$hash]['time'] = $time;
154 $trace = array();
155 foreach (debug_backtrace() as $trace_step) {
156 $trace[] = PMA_Error::relPath($trace_step['file']) . '#'
157 . $trace_step['line'] . ': '
158 . (isset($trace_step['class']) ? $trace_step['class'] : '')
159 //. (isset($trace_step['object']) ? get_class($trace_step['object']) : '')
160 . (isset($trace_step['type']) ? $trace_step['type'] : '')
161 . (isset($trace_step['function']) ? $trace_step['function'] : '')
162 . '('
163 . (isset($trace_step['params']) ? implode(', ', $trace_step['params']) : '')
164 . ')'
167 $_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
169 if ($r != false && PMA_Tracker::isActive() == true ) {
170 PMA_Tracker::handleQuery($query);
173 return $r;
177 * converts charset of a mysql message, usually coming from mysql_error(),
178 * into PMA charset, usally UTF-8
179 * uses language to charset mapping from mysql/share/errmsg.txt
180 * and charset names to ISO charset from information_schema.CHARACTER_SETS
182 * @param string $message the message
184 * @return string $message
186 function PMA_DBI_convert_message($message)
188 // latin always last!
189 $encodings = array(
190 'japanese' => 'EUC-JP', //'ujis',
191 'japanese-sjis' => 'Shift-JIS', //'sjis',
192 'korean' => 'EUC-KR', //'euckr',
193 'russian' => 'KOI8-R', //'koi8r',
194 'ukrainian' => 'KOI8-U', //'koi8u',
195 'greek' => 'ISO-8859-7', //'greek',
196 'serbian' => 'CP1250', //'cp1250',
197 'estonian' => 'ISO-8859-13', //'latin7',
198 'slovak' => 'ISO-8859-2', //'latin2',
199 'czech' => 'ISO-8859-2', //'latin2',
200 'hungarian' => 'ISO-8859-2', //'latin2',
201 'polish' => 'ISO-8859-2', //'latin2',
202 'romanian' => 'ISO-8859-2', //'latin2',
203 'spanish' => 'CP1252', //'latin1',
204 'swedish' => 'CP1252', //'latin1',
205 'italian' => 'CP1252', //'latin1',
206 'norwegian-ny' => 'CP1252', //'latin1',
207 'norwegian' => 'CP1252', //'latin1',
208 'portuguese' => 'CP1252', //'latin1',
209 'danish' => 'CP1252', //'latin1',
210 'dutch' => 'CP1252', //'latin1',
211 'english' => 'CP1252', //'latin1',
212 'french' => 'CP1252', //'latin1',
213 'german' => 'CP1252', //'latin1',
216 if ($server_language = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'language\';', 0, 1)) {
217 $found = array();
218 if (preg_match('&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i', $server_language, $found)) {
219 $server_language = $found[1];
223 if (! empty($server_language) && isset($encodings[$server_language])) {
224 if (function_exists('iconv')) {
225 if ((@stristr(PHP_OS, 'AIX'))
226 && (@strcasecmp(ICONV_IMPL, 'unknown') == 0)
227 && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)
229 include_once './libraries/iconv_wrapper.lib.php';
230 $message = PMA_aix_iconv_wrapper(
231 $encodings[$server_language],
232 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
233 $message
235 } else {
236 $message = iconv(
237 $encodings[$server_language],
238 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
239 $message
242 } elseif (function_exists('recode_string')) {
243 $message = recode_string(
244 $encodings[$server_language] . '..' . 'utf-8',
245 $message
247 } elseif (function_exists('libiconv')) {
248 $message = libiconv($encodings[$server_language], 'utf-8', $message);
249 } elseif (function_exists('mb_convert_encoding')) {
250 // do not try unsupported charsets
251 if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
252 $message = mb_convert_encoding(
253 $message,
254 'utf-8',
255 $encodings[$server_language]
259 } else {
261 * @todo lang not found, try all, what TODO ?
265 return $message;
269 * returns array with table names for given db
271 * @param string $database name of database
272 * @param mixed $link mysql link resource|object
274 * @return array tables names
276 function PMA_DBI_get_tables($database, $link = null)
278 return PMA_DBI_fetch_result(
279 'SHOW TABLES FROM ' . PMA_backquote($database) . ';',
280 null,
282 $link,
283 PMA_DBI_QUERY_STORE
288 * usort comparison callback
290 * @param string $a first argument to sort
291 * @param string $b second argument to sort
293 * @return integer a value representing whether $a should be before $b in the
294 * sorted array or not
296 * @access private
298 function PMA_usort_comparison_callback($a, $b)
300 if ($GLOBALS['cfg']['NaturalOrder']) {
301 $sorter = 'strnatcasecmp';
302 } else {
303 $sorter = 'strcasecmp';
305 /* No sorting when key is not present */
306 if (! isset($a[$GLOBALS['callback_sort_by']]) || ! isset($b[$GLOBALS['callback_sort_by']])) {
307 return 0;
309 // produces f.e.:
310 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
311 return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter($a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]);
312 } // end of the 'PMA_usort_comparison_callback()' function
315 * returns array of all tables in given db or dbs
316 * this function expects unquoted names:
317 * RIGHT: my_database
318 * WRONG: `my_database`
319 * WRONG: my\_database
320 * if $tbl_is_group is true, $table is used as filter for table names
321 * if $tbl_is_group is 'comment, $table is used as filter for table comments
323 * <code>
324 * PMA_DBI_get_tables_full('my_database');
325 * PMA_DBI_get_tables_full('my_database', 'my_table'));
326 * PMA_DBI_get_tables_full('my_database', 'my_tables_', true));
327 * PMA_DBI_get_tables_full('my_database', 'my_tables_', 'comment'));
328 * </code>
330 * @param string $database database
331 * @param string|bool $table table or false
332 * @param boolean|string $tbl_is_group $table is a table group
333 * @param mixed $link mysql link
334 * @param integer $limit_offset zero-based offset for the count
335 * @param boolean|integer $limit_count number of tables to return
336 * @param string $sort_by table attribute to sort by
337 * @param string $sort_order direction to sort (ASC or DESC)
339 * @todo move into PMA_Table
341 * @return array list of tables in given db(s)
343 function PMA_DBI_get_tables_full($database, $table = false, $tbl_is_group = false, $link = null,
344 $limit_offset = 0, $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC')
346 if (true === $limit_count) {
347 $limit_count = $GLOBALS['cfg']['MaxTableList'];
349 // prepare and check parameters
350 if (! is_array($database)) {
351 $databases = array($database);
352 } else {
353 $databases = $database;
356 $tables = array();
358 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
359 // get table information from information_schema
360 if ($table) {
361 if (true === $tbl_is_group) {
362 $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
363 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
364 } elseif ('comment' === $tbl_is_group) {
365 $sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
366 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
367 } else {
368 $sql_where_table = 'AND t.`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\'';
370 } else {
371 $sql_where_table = '';
374 // for PMA bc:
375 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
377 // on non-Windows servers,
378 // added BINARY in the WHERE clause to force a case sensitive
379 // comparison (if we are looking for the db Aa we don't want
380 // to find the db aa)
381 $this_databases = array_map('PMA_sqlAddSlashes', $databases);
383 if (PMA_DRIZZLE) {
384 $engine_info = PMA_cacheGet('drizzle_engines', true);
385 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
386 if (isset($engine_info['InnoDB'])
387 && $engine_info['InnoDB']['module_library'] == 'innobase'
389 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
392 // data_dictionary.table_cache may not contain any data for some tables, it's just a table cache
393 // auto_increment == 0 is cast to NULL because currently (2011.03.13 GA) Drizzle doesn't provide correct value
394 $sql = "
395 SELECT t.*,
396 t.TABLE_SCHEMA AS `Db`,
397 t.TABLE_NAME AS `Name`,
398 t.TABLE_TYPE AS `TABLE_TYPE`,
399 t.ENGINE AS `Engine`,
400 t.ENGINE AS `Type`,
401 t.TABLE_VERSION AS `Version`,-- VERSION
402 t.ROW_FORMAT AS `Row_format`,
403 coalesce(tc.ROWS, stat.NUM_ROWS)
404 AS `Rows`,-- TABLE_ROWS,
405 coalesce(tc.ROWS, stat.NUM_ROWS)
406 AS `TABLE_ROWS`,
407 tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
408 tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
409 NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
410 NULL AS `Index_length`, -- INDEX_LENGTH
411 NULL AS `Data_free`, -- DATA_FREE
412 nullif(t.AUTO_INCREMENT, 0)
413 AS `Auto_increment`,
414 t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
415 t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
416 NULL AS `Check_time`, -- CHECK_TIME
417 t.TABLE_COLLATION AS `Collation`,
418 NULL AS `Checksum`, -- CHECKSUM
419 NULL AS `Create_options`, -- CREATE_OPTIONS
420 t.TABLE_COMMENT AS `Comment`
421 FROM data_dictionary.TABLES t
422 LEFT JOIN data_dictionary.TABLE_CACHE tc ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME = t.TABLE_NAME
423 $stats_join
424 WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
425 " . $sql_where_table;
426 } else {
427 $sql = '
428 SELECT *,
429 `TABLE_SCHEMA` AS `Db`,
430 `TABLE_NAME` AS `Name`,
431 `TABLE_TYPE` AS `TABLE_TYPE`,
432 `ENGINE` AS `Engine`,
433 `ENGINE` AS `Type`,
434 `VERSION` AS `Version`,
435 `ROW_FORMAT` AS `Row_format`,
436 `TABLE_ROWS` AS `Rows`,
437 `AVG_ROW_LENGTH` AS `Avg_row_length`,
438 `DATA_LENGTH` AS `Data_length`,
439 `MAX_DATA_LENGTH` AS `Max_data_length`,
440 `INDEX_LENGTH` AS `Index_length`,
441 `DATA_FREE` AS `Data_free`,
442 `AUTO_INCREMENT` AS `Auto_increment`,
443 `CREATE_TIME` AS `Create_time`,
444 `UPDATE_TIME` AS `Update_time`,
445 `CHECK_TIME` AS `Check_time`,
446 `TABLE_COLLATION` AS `Collation`,
447 `CHECKSUM` AS `Checksum`,
448 `CREATE_OPTIONS` AS `Create_options`,
449 `TABLE_COMMENT` AS `Comment`
450 FROM `information_schema`.`TABLES` t
451 WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA` IN (\'' . implode("', '", $this_databases) . '\')
452 ' . $sql_where_table;
455 // Sort the tables
456 $sql .= " ORDER BY $sort_by $sort_order";
458 if ($limit_count) {
459 $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
462 $tables = PMA_DBI_fetch_result(
463 $sql, array('TABLE_SCHEMA', 'TABLE_NAME'), null, $link
465 unset($sql_where_table, $sql);
467 if (PMA_DRIZZLE) {
468 // correct I_S and D_D names returned by D_D.TABLES - Drizzle generally uses lower case for them,
469 // but TABLES returns uppercase
470 foreach ((array)$database as $db) {
471 $db_upper = strtoupper($db);
472 if (!isset($tables[$db]) && isset($tables[$db_upper])) {
473 $tables[$db] = $tables[$db_upper];
474 unset($tables[$db_upper]);
479 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
480 // here, the array's first key is by schema name
481 foreach ($tables as $one_database_name => $one_database_tables) {
482 uksort($one_database_tables, 'strnatcasecmp');
484 if ($sort_order == 'DESC') {
485 $one_database_tables = array_reverse($one_database_tables);
487 $tables[$one_database_name] = $one_database_tables;
490 } // end (get information from table schema)
492 // If permissions are wrong on even one database directory,
493 // information_schema does not return any table info for any database
494 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
495 if (empty($tables) && !PMA_DRIZZLE) {
496 foreach ($databases as $each_database) {
497 if ($table || (true === $tbl_is_group)) {
498 $sql = 'SHOW TABLE STATUS FROM '
499 . PMA_backquote($each_database)
500 .' LIKE \'' . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table, true)) . '%\'';
501 } else {
502 $sql = 'SHOW TABLE STATUS FROM '
503 . PMA_backquote($each_database);
506 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
508 // Sort naturally if the config allows it and we're sorting
509 // the Name column.
510 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
511 uksort($each_tables, 'strnatcasecmp');
513 if ($sort_order == 'DESC') {
514 $each_tables = array_reverse($each_tables);
516 } else {
517 // Prepare to sort by creating array of the selected sort
518 // value to pass to array_multisort
520 // Size = Data_length + Index_length
521 if ($sort_by == 'Data_length') {
522 foreach ($each_tables as $table_name => $table_data) {
523 ${$sort_by}[$table_name] = strtolower($table_data['Data_length'] + $table_data['Index_length']);
525 } else {
526 foreach ($each_tables as $table_name => $table_data) {
527 ${$sort_by}[$table_name] = strtolower($table_data[$sort_by]);
531 if ($sort_order == 'DESC') {
532 array_multisort($$sort_by, SORT_DESC, $each_tables);
533 } else {
534 array_multisort($$sort_by, SORT_ASC, $each_tables);
537 // cleanup the temporary sort array
538 unset($$sort_by);
541 if ($limit_count) {
542 $each_tables = array_slice($each_tables, $limit_offset, $limit_count);
545 foreach ($each_tables as $table_name => $each_table) {
546 if ('comment' === $tbl_is_group
547 && 0 === strpos($each_table['Comment'], $table)
549 // remove table from list
550 unset($each_tables[$table_name]);
551 continue;
554 if (! isset($each_tables[$table_name]['Type'])
555 && isset($each_tables[$table_name]['Engine'])
557 // pma BC, same parts of PMA still uses 'Type'
558 $each_tables[$table_name]['Type']
559 =& $each_tables[$table_name]['Engine'];
560 } elseif (! isset($each_tables[$table_name]['Engine'])
561 && isset($each_tables[$table_name]['Type'])) {
562 // old MySQL reports Type, newer MySQL reports Engine
563 $each_tables[$table_name]['Engine']
564 =& $each_tables[$table_name]['Type'];
567 // MySQL forward compatibility
568 // so pma could use this array as if every server is of version >5.0
569 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
570 $each_tables[$table_name]['TABLE_NAME'] =& $each_tables[$table_name]['Name'];
571 $each_tables[$table_name]['ENGINE'] =& $each_tables[$table_name]['Engine'];
572 $each_tables[$table_name]['VERSION'] =& $each_tables[$table_name]['Version'];
573 $each_tables[$table_name]['ROW_FORMAT'] =& $each_tables[$table_name]['Row_format'];
574 $each_tables[$table_name]['TABLE_ROWS'] =& $each_tables[$table_name]['Rows'];
575 $each_tables[$table_name]['AVG_ROW_LENGTH'] =& $each_tables[$table_name]['Avg_row_length'];
576 $each_tables[$table_name]['DATA_LENGTH'] =& $each_tables[$table_name]['Data_length'];
577 $each_tables[$table_name]['MAX_DATA_LENGTH'] =& $each_tables[$table_name]['Max_data_length'];
578 $each_tables[$table_name]['INDEX_LENGTH'] =& $each_tables[$table_name]['Index_length'];
579 $each_tables[$table_name]['DATA_FREE'] =& $each_tables[$table_name]['Data_free'];
580 $each_tables[$table_name]['AUTO_INCREMENT'] =& $each_tables[$table_name]['Auto_increment'];
581 $each_tables[$table_name]['CREATE_TIME'] =& $each_tables[$table_name]['Create_time'];
582 $each_tables[$table_name]['UPDATE_TIME'] =& $each_tables[$table_name]['Update_time'];
583 $each_tables[$table_name]['CHECK_TIME'] =& $each_tables[$table_name]['Check_time'];
584 $each_tables[$table_name]['TABLE_COLLATION'] =& $each_tables[$table_name]['Collation'];
585 $each_tables[$table_name]['CHECKSUM'] =& $each_tables[$table_name]['Checksum'];
586 $each_tables[$table_name]['CREATE_OPTIONS'] =& $each_tables[$table_name]['Create_options'];
587 $each_tables[$table_name]['TABLE_COMMENT'] =& $each_tables[$table_name]['Comment'];
589 if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
590 && $each_tables[$table_name]['Engine'] == null
592 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
593 } else {
595 * @todo difference between 'TEMPORARY' and 'BASE TABLE' but how to detect?
597 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
601 $tables[$each_database] = $each_tables;
605 // cache table data
606 // so PMA_Table does not require to issue SHOW TABLE STATUS again
607 // Note: I don't see why we would need array_merge_recursive() here,
608 // as it creates double entries for the same table (for example a double
609 // entry for Comment when changing the storage engine in Operations)
610 // Note 2: Instead of array_merge(), simply use the + operator because
611 // array_merge() renumbers numeric keys starting with 0, therefore
612 // we would lose a db name thats consists only of numbers
613 foreach ($tables as $one_database => $its_tables) {
614 if (isset(PMA_Table::$cache[$one_database])) {
615 PMA_Table::$cache[$one_database] = PMA_Table::$cache[$one_database] + $tables[$one_database];
616 } else {
617 PMA_Table::$cache[$one_database] = $tables[$one_database];
620 unset($one_database, $its_tables);
622 if (! is_array($database)) {
623 if (isset($tables[$database])) {
624 return $tables[$database];
625 } elseif (isset($tables[strtolower($database)])) {
626 // on windows with lower_case_table_names = 1
627 // MySQL returns
628 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
629 // but information_schema.TABLES gives `test`
630 // bug #1436171
631 // http://sf.net/support/tracker.php?aid=1436171
632 return $tables[strtolower($database)];
633 } else {
634 // one database but inexact letter case match
635 // as Drizzle is always case insensitive, we can safely return the only result
636 if (PMA_DRIZZLE && count($tables) == 1) {
637 $keys = array_keys($tables);
638 if (strlen(array_pop($keys)) == strlen($database)) {
639 return array_pop($tables);
642 return $tables;
644 } else {
645 return $tables;
650 * returns array with databases containing extended infos about them
652 * @param string $database database
653 * @param boolean $force_stats retrieve stats also for MySQL < 5
654 * @param resource $link mysql link
655 * @param string $sort_by column to order by
656 * @param string $sort_order ASC or DESC
657 * @param integer $limit_offset starting offset for LIMIT
658 * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
660 * @todo move into PMA_List_Database?
662 * @return array $databases
664 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
665 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
666 $limit_offset = 0, $limit_count = false)
668 $sort_order = strtoupper($sort_order);
670 if (true === $limit_count) {
671 $limit_count = $GLOBALS['cfg']['MaxDbList'];
674 // initialize to avoid errors when there are no databases
675 $databases = array();
677 $apply_limit_and_order_manual = true;
679 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
681 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
682 * cause MySQL does not support natural ordering, we have to do it afterward
684 $limit = '';
685 if (!$GLOBALS['cfg']['NaturalOrder']) {
686 if ($limit_count) {
687 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
690 $apply_limit_and_order_manual = false;
693 // get table information from information_schema
694 if ($database) {
695 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
696 . PMA_sqlAddSlashes($database) . '\'';
697 } else {
698 $sql_where_schema = '';
701 if (PMA_DRIZZLE) {
702 // data_dictionary.table_cache may not contain any data for some
703 // tables, it's just a table cache
704 $sql = 'SELECT
705 s.SCHEMA_NAME,
706 s.DEFAULT_COLLATION_NAME';
707 if ($force_stats) {
708 // no TABLE_CACHE data, stable results are better than
709 // constantly changing
710 $sql .= ',
711 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
712 SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
714 $sql .= '
715 FROM data_dictionary.SCHEMAS s';
716 if ($force_stats) {
717 $engine_info = PMA_cacheGet('drizzle_engines', true);
718 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
719 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
720 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
723 $sql .= "
724 LEFT JOIN data_dictionary.TABLES t
725 ON t.TABLE_SCHEMA = s.SCHEMA_NAME
726 $stats_join";
728 $sql .= $sql_where_schema . '
729 GROUP BY s.SCHEMA_NAME
730 ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
731 . $limit;
732 } else {
733 $sql = 'SELECT
734 s.SCHEMA_NAME,
735 s.DEFAULT_COLLATION_NAME';
736 if ($force_stats) {
737 $sql .= ',
738 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
739 SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
740 SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
741 SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
742 SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
743 SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
744 AS SCHEMA_LENGTH,
745 SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
747 $sql .= '
748 FROM `information_schema`.SCHEMATA s';
749 if ($force_stats) {
750 $sql .= '
751 LEFT JOIN `information_schema`.TABLES t
752 ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
754 $sql .= $sql_where_schema . '
755 GROUP BY BINARY s.SCHEMA_NAME
756 ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order
757 . $limit;
760 $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
762 $mysql_error = PMA_DBI_getError($link);
763 if (! count($databases) && $GLOBALS['errno']) {
764 PMA_mysqlDie($mysql_error, $sql);
767 // display only databases also in official database list
768 // f.e. to apply hide_db and only_db
769 $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases);
770 if (count($drops)) {
771 foreach ($drops as $drop) {
772 unset($databases[$drop]);
774 unset($drop);
776 unset($sql_where_schema, $sql, $drops);
777 } else {
778 foreach ($GLOBALS['pma']->databases as $database_name) {
779 // MySQL forward compatibility
780 // so pma could use this array as if every server is of version >5.0
781 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
783 if ($force_stats) {
784 include_once './libraries/mysql_charsets.lib.php';
786 $databases[$database_name]['DEFAULT_COLLATION_NAME']
787 = PMA_getDbCollation($database_name);
789 // get additional info about tables
790 $databases[$database_name]['SCHEMA_TABLES'] = 0;
791 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
792 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
793 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
794 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
795 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
796 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
798 $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($database_name) . ';');
799 while ($row = PMA_DBI_fetch_assoc($res)) {
800 $databases[$database_name]['SCHEMA_TABLES']++;
801 $databases[$database_name]['SCHEMA_TABLE_ROWS']
802 += $row['Rows'];
803 $databases[$database_name]['SCHEMA_DATA_LENGTH']
804 += $row['Data_length'];
805 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
806 += $row['Max_data_length'];
807 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
808 += $row['Index_length'];
810 // for InnoDB, this does not contain the number of
811 // overhead bytes but the total free space
812 if ('InnoDB' != $row['Engine']) {
813 $databases[$database_name]['SCHEMA_DATA_FREE']
814 += $row['Data_free'];
816 $databases[$database_name]['SCHEMA_LENGTH']
817 += $row['Data_length'] + $row['Index_length'];
819 PMA_DBI_free_result($res);
820 unset($res);
827 * apply limit and order manually now
828 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
830 if ($apply_limit_and_order_manual) {
831 $GLOBALS['callback_sort_order'] = $sort_order;
832 $GLOBALS['callback_sort_by'] = $sort_by;
833 usort($databases, 'PMA_usort_comparison_callback');
834 unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
837 * now apply limit
839 if ($limit_count) {
840 $databases = array_slice($databases, $limit_offset, $limit_count);
844 return $databases;
848 * returns detailed array with all columns for given table in database,
849 * or all tables/databases
851 * @param string $database name of database
852 * @param string $table name of table to retrieve columns from
853 * @param string $column name of specific column
854 * @param mixed $link mysql link resource
856 * @return array
858 function PMA_DBI_get_columns_full($database = null, $table = null,
859 $column = null, $link = null)
861 $columns = array();
863 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
864 $sql_wheres = array();
865 $array_keys = array();
867 // get columns information from information_schema
868 if (null !== $database) {
869 $sql_wheres[] = '`TABLE_SCHEMA` = \'' . PMA_sqlAddSlashes($database) . '\' ';
870 } else {
871 $array_keys[] = 'TABLE_SCHEMA';
873 if (null !== $table) {
874 $sql_wheres[] = '`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\' ';
875 } else {
876 $array_keys[] = 'TABLE_NAME';
878 if (null !== $column) {
879 $sql_wheres[] = '`COLUMN_NAME` = \'' . PMA_sqlAddSlashes($column) . '\' ';
880 } else {
881 $array_keys[] = 'COLUMN_NAME';
884 // for PMA bc:
885 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
886 if (PMA_DRIZZLE) {
887 $sql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME,
888 column_name AS `Field`,
889 (CASE
890 WHEN character_maximum_length > 0
891 THEN concat(lower(data_type), '(', character_maximum_length, ')')
892 WHEN numeric_precision > 0 OR numeric_scale > 0
893 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
894 WHEN enum_values IS NOT NULL
895 THEN concat(lower(data_type), '(', enum_values, ')')
896 ELSE lower(data_type) END)
897 AS `Type`,
898 collation_name AS `Collation`,
899 (CASE is_nullable
900 WHEN 1 THEN 'YES'
901 ELSE 'NO' END) AS `Null`,
902 (CASE
903 WHEN is_used_in_primary THEN 'PRI'
904 ELSE '' END) AS `Key`,
905 column_default AS `Default`,
906 (CASE
907 WHEN is_auto_increment THEN 'auto_increment'
908 WHEN column_default_update THEN 'on update ' || column_default_update
909 ELSE '' END) AS `Extra`,
910 NULL AS `Privileges`,
911 column_comment AS `Comment`
912 FROM data_dictionary.columns";
913 } else {
914 $sql = '
915 SELECT *,
916 `COLUMN_NAME` AS `Field`,
917 `COLUMN_TYPE` AS `Type`,
918 `COLLATION_NAME` AS `Collation`,
919 `IS_NULLABLE` AS `Null`,
920 `COLUMN_KEY` AS `Key`,
921 `COLUMN_DEFAULT` AS `Default`,
922 `EXTRA` AS `Extra`,
923 `PRIVILEGES` AS `Privileges`,
924 `COLUMN_COMMENT` AS `Comment`
925 FROM `information_schema`.`COLUMNS`';
927 if (count($sql_wheres)) {
928 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
931 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
932 unset($sql_wheres, $sql);
933 } else {
934 if (null === $database) {
935 foreach ($GLOBALS['pma']->databases as $database) {
936 $columns[$database] = PMA_DBI_get_columns_full(
937 $database, null, null, $link
940 return $columns;
941 } elseif (null === $table) {
942 $tables = PMA_DBI_get_tables($database);
943 foreach ($tables as $table) {
944 $columns[$table] = PMA_DBI_get_columns_full(
945 $database, $table, null, $link
948 return $columns;
951 $sql = 'SHOW FULL COLUMNS FROM '
952 . PMA_backquote($database) . '.' . PMA_backquote($table);
953 if (null !== $column) {
954 $sql .= " LIKE '" . PMA_sqlAddSlashes($column, true) . "'";
957 $columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
959 $ordinal_position = 1;
960 foreach ($columns as $column_name => $each_column) {
962 // MySQL forward compatibility
963 // so pma could use this array as if every server is of version >5.0
964 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
965 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
966 $columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
967 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
968 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
969 $columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
970 $columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
971 $columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
972 $columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
974 $columns[$column_name]['TABLE_CATALOG'] = null;
975 $columns[$column_name]['TABLE_SCHEMA'] = $database;
976 $columns[$column_name]['TABLE_NAME'] = $table;
977 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
978 $columns[$column_name]['DATA_TYPE']
979 = substr(
980 $columns[$column_name]['COLUMN_TYPE'],
982 strpos($columns[$column_name]['COLUMN_TYPE'], '(')
985 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
987 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
989 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
991 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
992 $columns[$column_name]['NUMERIC_PRECISION'] = null;
993 $columns[$column_name]['NUMERIC_SCALE'] = null;
994 $columns[$column_name]['CHARACTER_SET_NAME']
995 = substr(
996 $columns[$column_name]['COLLATION_NAME'],
998 strpos($columns[$column_name]['COLLATION_NAME'], '_')
1001 $ordinal_position++;
1004 if (null !== $column) {
1005 reset($columns);
1006 $columns = current($columns);
1009 return $columns;
1013 * Returns SQL query for fetching columns for a table
1015 * The 'Key' column is not calculated properly, use PMA_DBI_get_columns() to get
1016 * correct values.
1018 * @param string $database name of database
1019 * @param string $table name of table to retrieve columns from
1020 * @param string $column name of column, null to show all columns
1021 * @param boolean $full whether to return full info or only column names
1023 * @see PMA_DBI_get_columns()
1025 * @return string
1027 function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
1029 if (PMA_DRIZZLE) {
1030 // `Key` column:
1031 // * used in primary key => PRI
1032 // * unique one-column => UNI
1033 // * indexed, one-column or first in multi-column => MUL
1034 // Promotion of UNI to PRI in case no promary index exists is done after query is executed
1035 $sql = "SELECT
1036 column_name AS `Field`,
1037 (CASE
1038 WHEN character_maximum_length > 0
1039 THEN concat(lower(data_type), '(', character_maximum_length, ')')
1040 WHEN numeric_precision > 0 OR numeric_scale > 0
1041 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
1042 WHEN enum_values IS NOT NULL
1043 THEN concat(lower(data_type), '(', enum_values, ')')
1044 ELSE lower(data_type) END)
1045 AS `Type`,
1046 " . ($full ? "
1047 collation_name AS `Collation`," : '') . "
1048 (CASE is_nullable
1049 WHEN 1 THEN 'YES'
1050 ELSE 'NO' END) AS `Null`,
1051 (CASE
1052 WHEN is_used_in_primary THEN 'PRI'
1053 WHEN is_unique AND NOT is_multi THEN 'UNI'
1054 WHEN is_indexed AND (NOT is_multi OR is_first_in_multi) THEN 'MUL'
1055 ELSE '' END) AS `Key`,
1056 column_default AS `Default`,
1057 (CASE
1058 WHEN is_auto_increment THEN 'auto_increment'
1059 WHEN column_default_update <> '' THEN 'on update ' || column_default_update
1060 ELSE '' END) AS `Extra`
1061 " . ($full ? " ,
1062 NULL AS `Privileges`,
1063 column_comment AS `Comment`" : '') . "
1064 FROM data_dictionary.columns
1065 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1066 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1067 " . (($column != null) ? "
1068 AND column_name = '" . PMA_sqlAddSlashes($column) . "'" : '');
1069 // ORDER BY ordinal_position
1070 } else {
1071 $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
1072 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table)
1073 . (($column != null) ? "LIKE '" . PMA_sqlAddSlashes($column, true) . "'" : '');
1075 return $sql;
1079 * Returns descriptions of columns in given table (all or given by $column)
1081 * @param string $database name of database
1082 * @param string $table name of table to retrieve columns from
1083 * @param string $column name of column, null to show all columns
1084 * @param boolean $full whether to return full info or only column names
1085 * @param mixed $link mysql link resource
1087 * @return false|array array indexed by column names or,
1088 * if $column is given, flat array description
1090 function PMA_DBI_get_columns($database, $table, $column = null, $full = false, $link = null)
1092 $sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
1093 $fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
1094 if (! is_array($fields) || count($fields) == 0) {
1095 return null;
1097 if (PMA_DRIZZLE) {
1098 // fix Key column, it's much simpler in PHP than in SQL
1099 $has_pk = false;
1100 $has_pk_candidates = false;
1101 foreach ($fields as $f) {
1102 if ($f['Key'] == 'PRI') {
1103 $has_pk = true;
1104 break;
1105 } else if ($f['Null'] == 'NO' && ($f['Key'] == 'MUL' || $f['Key'] == 'UNI')) {
1106 $has_pk_candidates = true;
1109 if (!$has_pk && $has_pk_candidates) {
1110 // check whether we can promote some unique index to PRI
1111 $sql = "
1112 SELECT i.index_name, p.column_name
1113 FROM data_dictionary.indexes i
1114 JOIN data_dictionary.index_parts p USING (table_schema, table_name)
1115 WHERE i.table_schema = '" . PMA_sqlAddSlashes($database) . "'
1116 AND i.table_name = '" . PMA_sqlAddSlashes($table) . "'
1117 AND i.is_unique
1118 AND NOT i.is_nullable";
1119 $fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
1120 $fs = $fs ? array_shift($fs) : array();
1121 foreach ($fs as $f) {
1122 $fields[$f]['Key'] = 'PRI';
1127 return ($column != null) ? array_shift($fields) : $fields;
1131 * Returns SQL for fetching information on table indexes (SHOW INDEXES)
1133 * @param string $database name of database
1134 * @param string $table name of the table whose indexes are to be retreived
1135 * @param string $where additional conditions for WHERE
1137 * @return array $indexes
1139 function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
1141 if (PMA_DRIZZLE) {
1142 $sql = "SELECT
1143 ip.table_name AS `Table`,
1144 (NOT ip.is_unique) AS Non_unique,
1145 ip.index_name AS Key_name,
1146 ip.sequence_in_index+1 AS Seq_in_index,
1147 ip.column_name AS Column_name,
1148 (CASE
1149 WHEN i.index_type = 'BTREE' THEN 'A'
1150 ELSE NULL END) AS Collation,
1151 NULL AS Cardinality,
1152 compare_length AS Sub_part,
1153 NULL AS Packed,
1154 ip.is_nullable AS `Null`,
1155 i.index_type AS Index_type,
1156 NULL AS Comment,
1157 i.index_comment AS Index_comment
1158 FROM data_dictionary.index_parts ip
1159 LEFT JOIN data_dictionary.indexes i USING (table_schema, table_name, index_name)
1160 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1161 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1163 } else {
1164 $sql = 'SHOW INDEXES FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table);
1166 if ($where) {
1167 $sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
1169 return $sql;
1173 * Returns indexes of a table
1175 * @param string $database name of database
1176 * @param string $table name of the table whose indexes are to be retrieved
1177 * @param mixed $link mysql link resource
1179 * @return array $indexes
1181 function PMA_DBI_get_table_indexes($database, $table, $link = null)
1183 $sql = PMA_DBI_get_table_indexes_sql($database, $table);
1184 $indexes = PMA_DBI_fetch_result($sql, null, null, $link);
1186 if (! is_array($indexes) || count($indexes) < 1) {
1187 return array();
1189 return $indexes;
1193 * returns value of given mysql server variable
1195 * @param string $var mysql server variable name
1196 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
1197 * @param mixed $link mysql link resource|object
1199 * @return mixed value for mysql server variable
1201 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
1203 if ($link === null) {
1204 if (isset($GLOBALS['userlink'])) {
1205 $link = $GLOBALS['userlink'];
1206 } else {
1207 return false;
1211 switch ($type) {
1212 case PMA_DBI_GETVAR_SESSION:
1213 $modifier = ' SESSION';
1214 break;
1215 case PMA_DBI_GETVAR_GLOBAL:
1216 $modifier = ' GLOBAL';
1217 break;
1218 default:
1219 $modifier = '';
1221 return PMA_DBI_fetch_value(
1222 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link
1227 * Function called just after a connection to the MySQL database server has
1228 * been established. It sets the connection collation, and determins the
1229 * version of MySQL which is running.
1231 * @param mixed $link mysql link resource|object
1232 * @param boolean $is_controluser whether link is for control user
1234 function PMA_DBI_postConnect($link, $is_controluser = false)
1236 if (! defined('PMA_MYSQL_INT_VERSION')) {
1237 if (PMA_cacheExists('PMA_MYSQL_INT_VERSION', true)) {
1238 define(
1239 'PMA_MYSQL_INT_VERSION',
1240 PMA_cacheGet('PMA_MYSQL_INT_VERSION', true)
1242 define(
1243 'PMA_MYSQL_MAJOR_VERSION',
1244 PMA_cacheGet('PMA_MYSQL_MAJOR_VERSION', true)
1246 define(
1247 'PMA_MYSQL_STR_VERSION',
1248 PMA_cacheGet('PMA_MYSQL_STR_VERSION', true)
1250 define(
1251 'PMA_MYSQL_VERSION_COMMENT',
1252 PMA_cacheGet('PMA_MYSQL_VERSION_COMMENT', true)
1254 } else {
1255 $version = PMA_DBI_fetch_single_row(
1256 'SELECT @@version, @@version_comment',
1257 'ASSOC',
1258 $link
1261 if ($version) {
1262 $match = explode('.', $version['@@version']);
1263 define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
1264 define(
1265 'PMA_MYSQL_INT_VERSION',
1266 (int) sprintf('%d%02d%02d', $match[0], $match[1], intval($match[2]))
1268 define('PMA_MYSQL_STR_VERSION', $version['@@version']);
1269 define('PMA_MYSQL_VERSION_COMMENT', $version['@@version_comment']);
1270 } else {
1271 define('PMA_MYSQL_INT_VERSION', 50015);
1272 define('PMA_MYSQL_MAJOR_VERSION', 5);
1273 define('PMA_MYSQL_STR_VERSION', '5.00.15');
1274 define('PMA_MYSQL_VERSION_COMMENT', '');
1276 PMA_cacheSet(
1277 'PMA_MYSQL_INT_VERSION',
1278 PMA_MYSQL_INT_VERSION,
1279 true
1281 PMA_cacheSet(
1282 'PMA_MYSQL_MAJOR_VERSION',
1283 PMA_MYSQL_MAJOR_VERSION,
1284 true
1286 PMA_cacheSet(
1287 'PMA_MYSQL_STR_VERSION',
1288 PMA_MYSQL_STR_VERSION,
1289 true
1291 PMA_cacheSet(
1292 'PMA_MYSQL_VERSION_COMMENT',
1293 PMA_MYSQL_VERSION_COMMENT,
1294 true
1297 // detect Drizzle by version number:
1298 // <year>.<month>.<build number>(.<patch rev)
1299 define('PMA_DRIZZLE', PMA_MYSQL_MAJOR_VERSION >= 2009);
1302 // Skip charsets for Drizzle
1303 if (!PMA_DRIZZLE) {
1304 if (! empty($GLOBALS['collation_connection'])) {
1305 PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
1306 PMA_DBI_query(
1307 "SET collation_connection = '" . PMA_sqlAddSlashes($GLOBALS['collation_connection']) . "';",
1308 $link,
1309 PMA_DBI_QUERY_STORE
1311 } else {
1312 PMA_DBI_query(
1313 "SET NAMES 'utf8' COLLATE 'utf8_general_ci';",
1314 $link,
1315 PMA_DBI_QUERY_STORE
1320 // Cache plugin list for Drizzle
1321 if (PMA_DRIZZLE && !PMA_cacheExists('drizzle_engines', true)) {
1322 $sql = "SELECT p.plugin_name, m.module_library
1323 FROM data_dictionary.plugins p
1324 JOIN data_dictionary.modules m USING (module_name)
1325 WHERE p.plugin_type = 'StorageEngine'
1326 AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
1327 AND p.is_active = 'YES'";
1328 $engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
1329 PMA_cacheSet('drizzle_engines', $engines, true);
1334 * returns a single value from the given result or query,
1335 * if the query or the result has more than one row or field
1336 * the first field of the first row is returned
1338 * <code>
1339 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
1340 * $user_name = PMA_DBI_fetch_value($sql);
1341 * // produces
1342 * // $user_name = 'John Doe'
1343 * </code>
1345 * @param string|mysql_result $result query or mysql result
1346 * @param integer $row_number row to fetch the value from,
1347 * starting at 0, with 0 beeing default
1348 * @param integer|string $field field to fetch the value from,
1349 * starting at 0, with 0 beeing default
1350 * @param resource $link mysql link
1352 * @return mixed value of first field in first row from result
1353 * or false if not found
1355 function PMA_DBI_fetch_value($result, $row_number = 0, $field = 0, $link = null)
1357 $value = false;
1359 if (is_string($result)) {
1360 $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
1363 // return false if result is empty or false
1364 // or requested row is larger than rows in result
1365 if (PMA_DBI_num_rows($result) < ($row_number + 1)) {
1366 return $value;
1369 // if $field is an integer use non associative mysql fetch function
1370 if (is_int($field)) {
1371 $fetch_function = 'PMA_DBI_fetch_row';
1372 } else {
1373 $fetch_function = 'PMA_DBI_fetch_assoc';
1376 // get requested row
1377 for ($i = 0; $i <= $row_number; $i++) {
1378 $row = $fetch_function($result);
1380 PMA_DBI_free_result($result);
1382 // return requested field
1383 if (isset($row[$field])) {
1384 $value = $row[$field];
1386 unset($row);
1388 return $value;
1392 * returns only the first row from the result
1394 * <code>
1395 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
1396 * $user = PMA_DBI_fetch_single_row($sql);
1397 * // produces
1398 * // $user = array('id' => 123, 'name' => 'John Doe')
1399 * </code>
1401 * @param string|mysql_result $result query or mysql result
1402 * @param string $type NUM|ASSOC|BOTH
1403 * returned array should either numeric
1404 * associativ or booth
1405 * @param resource $link mysql link
1407 * @return array|boolean first row from result
1408 * or false if result is empty
1410 function PMA_DBI_fetch_single_row($result, $type = 'ASSOC', $link = null)
1412 if (is_string($result)) {
1413 $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
1416 // return null if result is empty or false
1417 if (! PMA_DBI_num_rows($result)) {
1418 return false;
1421 switch ($type) {
1422 case 'NUM' :
1423 $fetch_function = 'PMA_DBI_fetch_row';
1424 break;
1425 case 'ASSOC' :
1426 $fetch_function = 'PMA_DBI_fetch_assoc';
1427 break;
1428 case 'BOTH' :
1429 default :
1430 $fetch_function = 'PMA_DBI_fetch_array';
1431 break;
1434 $row = $fetch_function($result);
1435 PMA_DBI_free_result($result);
1436 return $row;
1440 * returns all rows in the resultset in one array
1442 * <code>
1443 * $sql = 'SELECT * FROM `user`';
1444 * $users = PMA_DBI_fetch_result($sql);
1445 * // produces
1446 * // $users[] = array('id' => 123, 'name' => 'John Doe')
1448 * $sql = 'SELECT `id`, `name` FROM `user`';
1449 * $users = PMA_DBI_fetch_result($sql, 'id');
1450 * // produces
1451 * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
1453 * $sql = 'SELECT `id`, `name` FROM `user`';
1454 * $users = PMA_DBI_fetch_result($sql, 0);
1455 * // produces
1456 * // $users['123'] = array(0 => 123, 1 => 'John Doe')
1458 * $sql = 'SELECT `id`, `name` FROM `user`';
1459 * $users = PMA_DBI_fetch_result($sql, 'id', 'name');
1460 * // or
1461 * $users = PMA_DBI_fetch_result($sql, 0, 1);
1462 * // produces
1463 * // $users['123'] = 'John Doe'
1465 * $sql = 'SELECT `name` FROM `user`';
1466 * $users = PMA_DBI_fetch_result($sql);
1467 * // produces
1468 * // $users[] = 'John Doe'
1470 * $sql = 'SELECT `group`, `name` FROM `user`'
1471 * $users = PMA_DBI_fetch_result($sql, array('group', null), 'name');
1472 * // produces
1473 * // $users['admin'][] = 'John Doe'
1475 * $sql = 'SELECT `group`, `name` FROM `user`'
1476 * $users = PMA_DBI_fetch_result($sql, array('group', 'name'), 'id');
1477 * // produces
1478 * // $users['admin']['John Doe'] = '123'
1479 * </code>
1481 * @param string|mysql_result $result query or mysql result
1482 * @param string|integer $key field-name or offset
1483 * used as key for array
1484 * @param string|integer $value value-name or offset
1485 * used as value for array
1486 * @param resource $link mysql link
1487 * @param mixed $options
1489 * @return array resultrows or values indexed by $key
1491 function PMA_DBI_fetch_result($result, $key = null, $value = null,
1492 $link = null, $options = 0)
1494 $resultrows = array();
1496 if (is_string($result)) {
1497 $result = PMA_DBI_try_query($result, $link, $options, false);
1500 // return empty array if result is empty or false
1501 if (! $result) {
1502 return $resultrows;
1505 $fetch_function = 'PMA_DBI_fetch_assoc';
1507 // no nested array if only one field is in result
1508 if (null === $key && 1 === PMA_DBI_num_fields($result)) {
1509 $value = 0;
1510 $fetch_function = 'PMA_DBI_fetch_row';
1513 // if $key is an integer use non associative mysql fetch function
1514 if (is_int($key)) {
1515 $fetch_function = 'PMA_DBI_fetch_row';
1518 if (null === $key && null === $value) {
1519 while ($row = $fetch_function($result)) {
1520 $resultrows[] = $row;
1522 } elseif (null === $key) {
1523 while ($row = $fetch_function($result)) {
1524 $resultrows[] = $row[$value];
1526 } elseif (null === $value) {
1527 if (is_array($key)) {
1528 while ($row = $fetch_function($result)) {
1529 $result_target =& $resultrows;
1530 foreach ($key as $key_index) {
1531 if (null === $key_index) {
1532 $result_target =& $result_target[];
1533 continue;
1536 if (! isset($result_target[$row[$key_index]])) {
1537 $result_target[$row[$key_index]] = array();
1539 $result_target =& $result_target[$row[$key_index]];
1541 $result_target = $row;
1543 } else {
1544 while ($row = $fetch_function($result)) {
1545 $resultrows[$row[$key]] = $row;
1548 } else {
1549 if (is_array($key)) {
1550 while ($row = $fetch_function($result)) {
1551 $result_target =& $resultrows;
1552 foreach ($key as $key_index) {
1553 if (null === $key_index) {
1554 $result_target =& $result_target[];
1555 continue;
1558 if (! isset($result_target[$row[$key_index]])) {
1559 $result_target[$row[$key_index]] = array();
1561 $result_target =& $result_target[$row[$key_index]];
1563 $result_target = $row[$value];
1565 } else {
1566 while ($row = $fetch_function($result)) {
1567 $resultrows[$row[$key]] = $row[$value];
1572 PMA_DBI_free_result($result);
1573 return $resultrows;
1577 * Get supported SQL compatibility modes
1579 * @return array supported SQL compatibility modes
1581 function PMA_DBI_getCompatibilities()
1583 // Drizzle doesn't support compatibility modes
1584 if (PMA_DRIZZLE) {
1585 return array();
1588 $compats = array('NONE');
1589 $compats[] = 'ANSI';
1590 $compats[] = 'DB2';
1591 $compats[] = 'MAXDB';
1592 $compats[] = 'MYSQL323';
1593 $compats[] = 'MYSQL40';
1594 $compats[] = 'MSSQL';
1595 $compats[] = 'ORACLE';
1596 // removed; in MySQL 5.0.33, this produces exports that
1597 // can't be read by POSTGRESQL (see our bug #1596328)
1598 //$compats[] = 'POSTGRESQL';
1599 $compats[] = 'TRADITIONAL';
1601 return $compats;
1605 * returns warnings for last query
1607 * @param resource $link mysql link resource
1609 * @return array warnings
1611 function PMA_DBI_get_warnings($link = null)
1613 if (empty($link)) {
1614 if (isset($GLOBALS['userlink'])) {
1615 $link = $GLOBALS['userlink'];
1616 } else {
1617 return array();
1621 return PMA_DBI_fetch_result('SHOW WARNINGS', null, null, $link);
1625 * returns true (int > 0) if current user is superuser
1626 * otherwise 0
1628 * @return bool Whether use is a superuser
1630 function PMA_isSuperuser()
1632 if (PMA_cacheExists('is_superuser', true)) {
1633 return PMA_cacheGet('is_superuser', true);
1636 // when connection failed we don't have a $userlink
1637 if (isset($GLOBALS['userlink'])) {
1638 if (PMA_DRIZZLE) {
1639 // Drizzle has no authorization by default, so when no plugin is
1640 // enabled everyone is a superuser
1641 // Known authorization libraries: regex_policy, simple_user_policy
1642 // Plugins limit object visibility (dbs, tables, processes), we can
1643 // safely assume we always deal with superuser
1644 $r = true;
1645 } else {
1646 // check access to mysql.user table
1647 $r = (bool) PMA_DBI_try_query(
1648 'SELECT COUNT(*) FROM mysql.user',
1649 $GLOBALS['userlink'],
1650 PMA_DBI_QUERY_STORE
1653 PMA_cacheSet('is_superuser', $r, true);
1654 } else {
1655 PMA_cacheSet('is_superuser', false, true);
1658 return PMA_cacheGet('is_superuser', true);
1662 * returns an array of PROCEDURE or FUNCTION names for a db
1664 * @param string $db db name
1665 * @param string $which PROCEDURE | FUNCTION
1666 * @param resource $link mysql link
1668 * @returnarray the procedure names or function names
1670 function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
1672 if (PMA_DRIZZLE) {
1673 // Drizzle doesn't support functions and procedures
1674 return array();
1676 $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
1677 $result = array();
1678 foreach ($shows as $one_show) {
1679 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1680 $result[] = $one_show['Name'];
1683 return($result);
1687 * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
1689 * @param string $db db name
1690 * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
1691 * @param string $name the procedure|function|event|view name
1692 * @param resource $link mysql link
1694 * @return string the definition
1696 function PMA_DBI_get_definition($db, $which, $name, $link = null)
1698 $returned_field = array(
1699 'PROCEDURE' => 'Create Procedure',
1700 'FUNCTION' => 'Create Function',
1701 'EVENT' => 'Create Event',
1702 'VIEW' => 'Create View'
1704 $query = 'SHOW CREATE ' . $which . ' '
1705 . PMA_backquote($db) . '.' . PMA_backquote($name);
1706 return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
1710 * returns details about the TRIGGERs for a specific table or database
1712 * @param string $db db name
1713 * @param string $table table name
1714 * @param string $delimiter the delimiter to use (may be empty)
1716 * @return array information about triggers (may be empty)
1718 function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
1720 if (PMA_DRIZZLE) {
1721 // Drizzle doesn't support triggers
1722 return array();
1725 $result = array();
1726 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1727 // Note: in http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html
1728 // their example uses WHERE TRIGGER_SCHEMA='dbname' so let's use this
1729 // instead of WHERE EVENT_OBJECT_SCHEMA='dbname'
1730 $query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
1731 . ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
1732 . ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
1733 . ' FROM information_schema.TRIGGERS'
1734 . ' WHERE TRIGGER_SCHEMA= \'' . PMA_sqlAddSlashes($db) . '\'';
1736 if (! empty($table)) {
1737 $query .= " AND EVENT_OBJECT_TABLE = '" . PMA_sqlAddSlashes($table) . "';";
1739 } else {
1740 $query = "SHOW TRIGGERS FROM " . PMA_backquote($db);
1741 if (! empty($table)) {
1742 $query .= " LIKE '" . PMA_sqlAddSlashes($table, true) . "';";
1746 if ($triggers = PMA_DBI_fetch_result($query)) {
1747 foreach ($triggers as $trigger) {
1748 if ($GLOBALS['cfg']['Server']['DisableIS']) {
1749 $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
1750 $trigger['ACTION_TIMING'] = $trigger['Timing'];
1751 $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
1752 $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
1753 $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
1754 $trigger['DEFINER'] = $trigger['Definer'];
1756 $one_result = array();
1757 $one_result['name'] = $trigger['TRIGGER_NAME'];
1758 $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
1759 $one_result['action_timing'] = $trigger['ACTION_TIMING'];
1760 $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
1761 $one_result['definition'] = $trigger['ACTION_STATEMENT'];
1762 $one_result['definer'] = $trigger['DEFINER'];
1764 // do not prepend the schema name; this way, importing the
1765 // definition into another schema will work
1766 $one_result['full_trigger_name'] = PMA_backquote($trigger['TRIGGER_NAME']);
1767 $one_result['drop'] = 'DROP TRIGGER IF EXISTS '
1768 . $one_result['full_trigger_name'];
1769 $one_result['create'] = 'CREATE TRIGGER '
1770 . $one_result['full_trigger_name'] . ' '
1771 . $trigger['ACTION_TIMING']. ' '
1772 . $trigger['EVENT_MANIPULATION']
1773 . ' ON ' . PMA_backquote($trigger['EVENT_OBJECT_TABLE'])
1774 . "\n" . ' FOR EACH ROW '
1775 . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
1777 $result[] = $one_result;
1781 // Sort results by name
1782 $name = array();
1783 foreach ($result as $key => $value) {
1784 $name[] = $value['name'];
1786 array_multisort($name, SORT_ASC, $result);
1788 return($result);
1792 * Formats database error message in a friendly way.
1793 * This is needed because some errors messages cannot
1794 * be obtained by mysql_error().
1796 * @param int $error_number Error code
1797 * @param string $error_message Error message as returned by server
1799 * @return string HML text with error details
1801 function PMA_DBI_formatError($error_number, $error_message)
1803 if (! empty($error_message)) {
1804 $error_message = PMA_DBI_convert_message($error_message);
1807 $error_message = htmlspecialchars($error_message);
1809 $error = '#' . ((string) $error_number);
1811 if ($error_number == 2002) {
1812 $error .= ' - ' . $error_message;
1813 $error .= '<br />' . __('The server is not responding (or the local server\'s socket is not correctly configured).');
1814 } elseif ($error_number == 2003) {
1815 $error .= ' - ' . $error_message;
1816 $error .= '<br />' . __('The server is not responding.');
1817 } elseif ($error_number == 1005) {
1818 if (strpos($error_message, 'errno: 13') !== false) {
1819 $error .= ' - ' . $error_message;
1820 $error .= '<br />' . __('Please check privileges of directory containing database.');
1821 } else {
1822 /* InnoDB contraints, see
1823 * http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
1825 $error .= ' - ' . $error_message .
1826 ' (<a href="server_engines.php' .
1827 PMA_generate_common_url(array('engine' => 'InnoDB', 'page' => 'Status')) .
1828 '">' . __('Details...') . '</a>)';
1830 } else {
1831 $error .= ' - ' . $error_message;
1834 return $error;
1838 * Checks whether given schema is a system schema: information_schema
1839 * (MySQL and Drizzle) or data_dictionary (Drizzle)
1841 * @param string $schema_name Name of schema (database) to test
1842 * @param bool $test_for_mysql_schema Whether 'mysql' schema should
1843 * be treated the same as IS and DD
1845 * @return bool
1847 function PMA_is_system_schema($schema_name, $test_for_mysql_schema = false)
1849 return strtolower($schema_name) == 'information_schema'
1850 || (!PMA_DRIZZLE && strtolower($schema_name) == 'performance_schema')
1851 || (PMA_DRIZZLE && strtolower($schema_name) == 'data_dictionary')
1852 || ($test_for_mysql_schema && !PMA_DRIZZLE && $schema_name == 'mysql');