Print server_comment after server software version
[phpmyadmin/crack.git] / libraries / database_interface.lib.php
blob507cd4b08a34a5233031347aefa3ad1884219bc3
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 /**
15 // PMA_DBI_try_query()
16 define('PMA_DBI_QUERY_STORE', 1); // Force STORE_RESULT method, ignored by classic MySQL.
17 define('PMA_DBI_QUERY_UNBUFFERED', 2); // Do not read whole query
18 // PMA_DBI_get_variable()
19 define('PMA_DBI_GETVAR_SESSION', 1);
20 define('PMA_DBI_GETVAR_GLOBAL', 2);
22 /**
23 * Checks whether database extension is loaded
25 * @param string $extension mysql extension to check
26 * @return bool
28 function PMA_DBI_checkDbExtension($extension = 'mysql')
30 if ($extension == 'drizzle' && function_exists('drizzle_create')) {
31 return true;
32 } else if (function_exists($extension . '_connect')) {
33 return true;
36 return false;
39 /**
40 * check for requested extension
42 if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
44 // if it fails try alternative extension ...
45 // and display an error ...
47 /**
48 * @todo add different messages for alternative extension
49 * and complete fail (no alternative extension too)
51 PMA_warnMissingExtension($GLOBALS['cfg']['Server']['extension'], false, PMA_showDocu('faqmysql'));
53 if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
54 $alternativ_extension = 'mysqli';
55 } else {
56 $alternativ_extension = 'mysql';
59 if (! PMA_DBI_checkDbExtension($alternativ_extension)) {
60 // if alternative fails too ...
61 PMA_warnMissingExtension($GLOBALS['cfg']['Server']['extension'], true, PMA_showDocu('faqmysql'));
64 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
65 unset($alternativ_extension);
68 /**
69 * Including The DBI Plugin
71 require_once './libraries/dbi/' . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php';
73 /**
74 * runs a query
76 * @param string $query SQL query to execte
77 * @param mixed $link optional database link to use
78 * @param int $options optional query options
79 * @param bool $cache_affected_rows whether to cache affected rows
80 * @return mixed
82 function PMA_DBI_query($query, $link = null, $options = 0, $cache_affected_rows = true)
84 $res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
85 or PMA_mysqlDie(PMA_DBI_getError($link), $query);
86 return $res;
89 /**
90 * runs a query and returns the result
92 * @param string $query query to run
93 * @param resource $link mysql link resource
94 * @param integer $options
95 * @param bool $cache_affected_rows
96 * @return mixed
98 function PMA_DBI_try_query($query, $link = null, $options = 0, $cache_affected_rows = true)
100 if (empty($link)) {
101 if (isset($GLOBALS['userlink'])) {
102 $link = $GLOBALS['userlink'];
103 } else {
104 return false;
108 if ($GLOBALS['cfg']['DBG']['sql']) {
109 $time = microtime(true);
112 $r = PMA_DBI_real_query($query, $link, $options);
114 if ($cache_affected_rows) {
115 $GLOBALS['cached_affected_rows'] = PMA_DBI_affected_rows($link, $get_from_cache = false);
118 if ($GLOBALS['cfg']['DBG']['sql']) {
119 $time = microtime(true) - $time;
121 $hash = md5($query);
123 if (isset($_SESSION['debug']['queries'][$hash])) {
124 $_SESSION['debug']['queries'][$hash]['count']++;
125 } else {
126 $_SESSION['debug']['queries'][$hash] = array();
127 if ($r == false) {
128 $_SESSION['debug']['queries'][$hash]['error'] = '<b style="color:red">'.mysqli_error($link).'</b>';
130 $_SESSION['debug']['queries'][$hash]['count'] = 1;
131 $_SESSION['debug']['queries'][$hash]['query'] = $query;
132 $_SESSION['debug']['queries'][$hash]['time'] = $time;
135 $trace = array();
136 foreach (debug_backtrace() as $trace_step) {
137 $trace[] = PMA_Error::relPath($trace_step['file']) . '#'
138 . $trace_step['line'] . ': '
139 . (isset($trace_step['class']) ? $trace_step['class'] : '')
140 //. (isset($trace_step['object']) ? get_class($trace_step['object']) : '')
141 . (isset($trace_step['type']) ? $trace_step['type'] : '')
142 . (isset($trace_step['function']) ? $trace_step['function'] : '')
143 . '('
144 . (isset($trace_step['params']) ? implode(', ', $trace_step['params']) : '')
145 . ')'
148 $_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
150 if ($r != false && PMA_Tracker::isActive() == true ) {
151 PMA_Tracker::handleQuery($query);
154 return $r;
158 * converts charset of a mysql message, usually coming from mysql_error(),
159 * into PMA charset, usally UTF-8
160 * uses language to charset mapping from mysql/share/errmsg.txt
161 * and charset names to ISO charset from information_schema.CHARACTER_SETS
163 * @param string $message
164 * @return string $message
166 function PMA_DBI_convert_message($message)
168 // latin always last!
169 $encodings = array(
170 'japanese' => 'EUC-JP', //'ujis',
171 'japanese-sjis' => 'Shift-JIS', //'sjis',
172 'korean' => 'EUC-KR', //'euckr',
173 'russian' => 'KOI8-R', //'koi8r',
174 'ukrainian' => 'KOI8-U', //'koi8u',
175 'greek' => 'ISO-8859-7', //'greek',
176 'serbian' => 'CP1250', //'cp1250',
177 'estonian' => 'ISO-8859-13', //'latin7',
178 'slovak' => 'ISO-8859-2', //'latin2',
179 'czech' => 'ISO-8859-2', //'latin2',
180 'hungarian' => 'ISO-8859-2', //'latin2',
181 'polish' => 'ISO-8859-2', //'latin2',
182 'romanian' => 'ISO-8859-2', //'latin2',
183 'spanish' => 'CP1252', //'latin1',
184 'swedish' => 'CP1252', //'latin1',
185 'italian' => 'CP1252', //'latin1',
186 'norwegian-ny' => 'CP1252', //'latin1',
187 'norwegian' => 'CP1252', //'latin1',
188 'portuguese' => 'CP1252', //'latin1',
189 'danish' => 'CP1252', //'latin1',
190 'dutch' => 'CP1252', //'latin1',
191 'english' => 'CP1252', //'latin1',
192 'french' => 'CP1252', //'latin1',
193 'german' => 'CP1252', //'latin1',
196 if ($server_language = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'language\';', 0, 1)) {
197 $found = array();
198 if (preg_match('&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i', $server_language, $found)) {
199 $server_language = $found[1];
203 if (! empty($server_language) && isset($encodings[$server_language])) {
204 if (function_exists('iconv')) {
205 if ((@stristr(PHP_OS, 'AIX')) && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
206 require_once './libraries/iconv_wrapper.lib.php';
207 $message = PMA_aix_iconv_wrapper($encodings[$server_language],
208 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'], $message);
209 } else {
210 $message = iconv($encodings[$server_language],
211 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'], $message);
213 } elseif (function_exists('recode_string')) {
214 $message = recode_string($encodings[$server_language] . '..' . 'utf-8',
215 $message);
216 } elseif (function_exists('libiconv')) {
217 $message = libiconv($encodings[$server_language], 'utf-8', $message);
218 } elseif (function_exists('mb_convert_encoding')) {
219 // do not try unsupported charsets
220 if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
221 $message = mb_convert_encoding($message, 'utf-8',
222 $encodings[$server_language]);
225 } else {
227 * @todo lang not found, try all, what TODO ?
231 return $message;
235 * returns array with table names for given db
237 * @param string $database name of database
238 * @param mixed $link mysql link resource|object
239 * @return array tables names
241 function PMA_DBI_get_tables($database, $link = null)
243 return PMA_DBI_fetch_result('SHOW TABLES FROM ' . PMA_backquote($database) . ';',
244 null, 0, $link, PMA_DBI_QUERY_STORE);
248 * usort comparison callback
250 * @param string $a first argument to sort
251 * @param string $b second argument to sort
253 * @return integer a value representing whether $a should be before $b in the
254 * sorted array or not
256 * @access private
258 function PMA_usort_comparison_callback($a, $b)
260 if ($GLOBALS['cfg']['NaturalOrder']) {
261 $sorter = 'strnatcasecmp';
262 } else {
263 $sorter = 'strcasecmp';
265 /* No sorting when key is not present */
266 if (! isset($a[$GLOBALS['callback_sort_by']]) || ! isset($b[$GLOBALS['callback_sort_by']])) {
267 return 0;
269 // produces f.e.:
270 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
271 return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter($a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]);
272 } // end of the 'PMA_usort_comparison_callback()' function
275 * returns array of all tables in given db or dbs
276 * this function expects unquoted names:
277 * RIGHT: my_database
278 * WRONG: `my_database`
279 * WRONG: my\_database
280 * if $tbl_is_group is true, $table is used as filter for table names
281 * if $tbl_is_group is 'comment, $table is used as filter for table comments
283 * <code>
284 * PMA_DBI_get_tables_full('my_database');
285 * PMA_DBI_get_tables_full('my_database', 'my_table'));
286 * PMA_DBI_get_tables_full('my_database', 'my_tables_', true));
287 * PMA_DBI_get_tables_full('my_database', 'my_tables_', 'comment'));
288 * </code>
290 * @todo move into PMA_Table
291 * @param string $database database
292 * @param string|bool $table table or false
293 * @param boolean|string $tbl_is_group $table is a table group
294 * @param mixed $link mysql link
295 * @param integer $limit_offset zero-based offset for the count
296 * @param boolean|integer $limit_count number of tables to return
297 * @param string $sort_by table attribute to sort by
298 * @param string $sort_order direction to sort (ASC or DESC)
299 * @return array list of tables in given db(s)
301 function PMA_DBI_get_tables_full($database, $table = false, $tbl_is_group = false, $link = null,
302 $limit_offset = 0, $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC')
304 if (true === $limit_count) {
305 $limit_count = $GLOBALS['cfg']['MaxTableList'];
307 // prepare and check parameters
308 if (! is_array($database)) {
309 $databases = array($database);
310 } else {
311 $databases = $database;
314 $tables = array();
316 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
317 // get table information from information_schema
318 if ($table) {
319 if (true === $tbl_is_group) {
320 $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
321 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
322 } elseif ('comment' === $tbl_is_group) {
323 $sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
324 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
325 } else {
326 $sql_where_table = 'AND t.`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\'';
328 } else {
329 $sql_where_table = '';
332 // for PMA bc:
333 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
335 // on non-Windows servers,
336 // added BINARY in the WHERE clause to force a case sensitive
337 // comparison (if we are looking for the db Aa we don't want
338 // to find the db aa)
339 $this_databases = array_map('PMA_sqlAddSlashes', $databases);
341 if (PMA_DRIZZLE) {
342 $engine_info = PMA_cacheGet('drizzle_engines', true);
343 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
344 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
345 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
348 // data_dictionary.table_cache may not contain any data for some tables, it's just a table cache
349 // auto_increment == 0 is cast to NULL because currently (2011.03.13 GA) Drizzle doesn't provide correct value
350 $sql = "
351 SELECT t.*,
352 t.TABLE_SCHEMA AS `Db`,
353 t.TABLE_NAME AS `Name`,
354 t.TABLE_TYPE AS `TABLE_TYPE`,
355 t.ENGINE AS `Engine`,
356 t.ENGINE AS `Type`,
357 t.TABLE_VERSION AS `Version`,-- VERSION
358 t.ROW_FORMAT AS `Row_format`,
359 coalesce(tc.ROWS, stat.NUM_ROWS)
360 AS `Rows`,-- TABLE_ROWS,
361 coalesce(tc.ROWS, stat.NUM_ROWS)
362 AS `TABLE_ROWS`,
363 tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
364 tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
365 NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
366 NULL AS `Index_length`, -- INDEX_LENGTH
367 NULL AS `Data_free`, -- DATA_FREE
368 nullif(t.AUTO_INCREMENT, 0)
369 AS `Auto_increment`,
370 t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
371 t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
372 NULL AS `Check_time`, -- CHECK_TIME
373 t.TABLE_COLLATION AS `Collation`,
374 NULL AS `Checksum`, -- CHECKSUM
375 NULL AS `Create_options`, -- CREATE_OPTIONS
376 t.TABLE_COMMENT AS `Comment`
377 FROM data_dictionary.TABLES t
378 LEFT JOIN data_dictionary.TABLE_CACHE tc ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME = t.TABLE_NAME
379 $stats_join
380 WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
381 " . $sql_where_table;
382 } else {
383 $sql = '
384 SELECT *,
385 `TABLE_SCHEMA` AS `Db`,
386 `TABLE_NAME` AS `Name`,
387 `TABLE_TYPE` AS `TABLE_TYPE`,
388 `ENGINE` AS `Engine`,
389 `ENGINE` AS `Type`,
390 `VERSION` AS `Version`,
391 `ROW_FORMAT` AS `Row_format`,
392 `TABLE_ROWS` AS `Rows`,
393 `AVG_ROW_LENGTH` AS `Avg_row_length`,
394 `DATA_LENGTH` AS `Data_length`,
395 `MAX_DATA_LENGTH` AS `Max_data_length`,
396 `INDEX_LENGTH` AS `Index_length`,
397 `DATA_FREE` AS `Data_free`,
398 `AUTO_INCREMENT` AS `Auto_increment`,
399 `CREATE_TIME` AS `Create_time`,
400 `UPDATE_TIME` AS `Update_time`,
401 `CHECK_TIME` AS `Check_time`,
402 `TABLE_COLLATION` AS `Collation`,
403 `CHECKSUM` AS `Checksum`,
404 `CREATE_OPTIONS` AS `Create_options`,
405 `TABLE_COMMENT` AS `Comment`
406 FROM `information_schema`.`TABLES` t
407 WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA` IN (\'' . implode("', '", $this_databases) . '\')
408 ' . $sql_where_table;
411 // Sort the tables
412 $sql .= " ORDER BY $sort_by $sort_order";
414 if ($limit_count) {
415 $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
418 $tables = PMA_DBI_fetch_result($sql, array('TABLE_SCHEMA', 'TABLE_NAME'),
419 null, $link);
420 unset($sql_where_table, $sql);
422 if (PMA_DRIZZLE) {
423 // correct I_S and D_D names returned by D_D.TABLES - Drizzle generally uses lower case for them,
424 // but TABLES returns uppercase
425 foreach ((array)$database as $db) {
426 $db_upper = strtoupper($db);
427 if (!isset($tables[$db]) && isset($tables[$db_upper])) {
428 $tables[$db] = $tables[$db_upper];
429 unset($tables[$db_upper]);
434 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
435 // here, the array's first key is by schema name
436 foreach ($tables as $one_database_name => $one_database_tables) {
437 uksort($one_database_tables, 'strnatcasecmp');
439 if ($sort_order == 'DESC') {
440 $one_database_tables = array_reverse($one_database_tables);
442 $tables[$one_database_name] = $one_database_tables;
445 } // end (get information from table schema)
447 // If permissions are wrong on even one database directory,
448 // information_schema does not return any table info for any database
449 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
450 if (empty($tables) && !PMA_DRIZZLE) {
451 foreach ($databases as $each_database) {
452 if ($table || (true === $tbl_is_group)) {
453 $sql = 'SHOW TABLE STATUS FROM '
454 . PMA_backquote($each_database)
455 .' LIKE \'' . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table, true)) . '%\'';
456 } else {
457 $sql = 'SHOW TABLE STATUS FROM '
458 . PMA_backquote($each_database);
461 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
463 // Sort naturally if the config allows it and we're sorting
464 // the Name column.
465 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
466 uksort($each_tables, 'strnatcasecmp');
468 if ($sort_order == 'DESC') {
469 $each_tables = array_reverse($each_tables);
471 } else {
472 // Prepare to sort by creating array of the selected sort
473 // value to pass to array_multisort
475 // Size = Data_length + Index_length
476 if ($sort_by == 'Data_length') {
477 foreach ($each_tables as $table_name => $table_data) {
478 ${$sort_by}[$table_name] = strtolower($table_data['Data_length'] + $table_data['Index_length']);
480 } else {
481 foreach ($each_tables as $table_name => $table_data) {
482 ${$sort_by}[$table_name] = strtolower($table_data[$sort_by]);
486 if ($sort_order == 'DESC') {
487 array_multisort($$sort_by, SORT_DESC, $each_tables);
488 } else {
489 array_multisort($$sort_by, SORT_ASC, $each_tables);
492 // cleanup the temporary sort array
493 unset($$sort_by);
496 if ($limit_count) {
497 $each_tables = array_slice($each_tables, $limit_offset, $limit_count);
500 foreach ($each_tables as $table_name => $each_table) {
501 if ('comment' === $tbl_is_group
502 && 0 === strpos($each_table['Comment'], $table))
504 // remove table from list
505 unset($each_tables[$table_name]);
506 continue;
509 if (! isset($each_tables[$table_name]['Type'])
510 && isset($each_tables[$table_name]['Engine'])) {
511 // pma BC, same parts of PMA still uses 'Type'
512 $each_tables[$table_name]['Type']
513 =& $each_tables[$table_name]['Engine'];
514 } elseif (! isset($each_tables[$table_name]['Engine'])
515 && isset($each_tables[$table_name]['Type'])) {
516 // old MySQL reports Type, newer MySQL reports Engine
517 $each_tables[$table_name]['Engine']
518 =& $each_tables[$table_name]['Type'];
521 // MySQL forward compatibility
522 // so pma could use this array as if every server is of version >5.0
523 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
524 $each_tables[$table_name]['TABLE_NAME'] =& $each_tables[$table_name]['Name'];
525 $each_tables[$table_name]['ENGINE'] =& $each_tables[$table_name]['Engine'];
526 $each_tables[$table_name]['VERSION'] =& $each_tables[$table_name]['Version'];
527 $each_tables[$table_name]['ROW_FORMAT'] =& $each_tables[$table_name]['Row_format'];
528 $each_tables[$table_name]['TABLE_ROWS'] =& $each_tables[$table_name]['Rows'];
529 $each_tables[$table_name]['AVG_ROW_LENGTH'] =& $each_tables[$table_name]['Avg_row_length'];
530 $each_tables[$table_name]['DATA_LENGTH'] =& $each_tables[$table_name]['Data_length'];
531 $each_tables[$table_name]['MAX_DATA_LENGTH'] =& $each_tables[$table_name]['Max_data_length'];
532 $each_tables[$table_name]['INDEX_LENGTH'] =& $each_tables[$table_name]['Index_length'];
533 $each_tables[$table_name]['DATA_FREE'] =& $each_tables[$table_name]['Data_free'];
534 $each_tables[$table_name]['AUTO_INCREMENT'] =& $each_tables[$table_name]['Auto_increment'];
535 $each_tables[$table_name]['CREATE_TIME'] =& $each_tables[$table_name]['Create_time'];
536 $each_tables[$table_name]['UPDATE_TIME'] =& $each_tables[$table_name]['Update_time'];
537 $each_tables[$table_name]['CHECK_TIME'] =& $each_tables[$table_name]['Check_time'];
538 $each_tables[$table_name]['TABLE_COLLATION'] =& $each_tables[$table_name]['Collation'];
539 $each_tables[$table_name]['CHECKSUM'] =& $each_tables[$table_name]['Checksum'];
540 $each_tables[$table_name]['CREATE_OPTIONS'] =& $each_tables[$table_name]['Create_options'];
541 $each_tables[$table_name]['TABLE_COMMENT'] =& $each_tables[$table_name]['Comment'];
543 if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
544 && $each_tables[$table_name]['Engine'] == null) {
545 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
546 } else {
548 * @todo difference between 'TEMPORARY' and 'BASE TABLE' but how to detect?
550 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
554 $tables[$each_database] = $each_tables;
558 // cache table data
559 // so PMA_Table does not require to issue SHOW TABLE STATUS again
560 // Note: I don't see why we would need array_merge_recursive() here,
561 // as it creates double entries for the same table (for example a double
562 // entry for Comment when changing the storage engine in Operations)
563 // Note 2: Instead of array_merge(), simply use the + operator because
564 // array_merge() renumbers numeric keys starting with 0, therefore
565 // we would lose a db name thats consists only of numbers
566 foreach ($tables as $one_database => $its_tables) {
567 if (isset(PMA_Table::$cache[$one_database])) {
568 PMA_Table::$cache[$one_database] = PMA_Table::$cache[$one_database] + $tables[$one_database];
569 } else {
570 PMA_Table::$cache[$one_database] = $tables[$one_database];
573 unset($one_database, $its_tables);
575 if (! is_array($database)) {
576 if (isset($tables[$database])) {
577 return $tables[$database];
578 } elseif (isset($tables[strtolower($database)])) {
579 // on windows with lower_case_table_names = 1
580 // MySQL returns
581 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
582 // but information_schema.TABLES gives `test`
583 // bug #1436171
584 // http://sf.net/support/tracker.php?aid=1436171
585 return $tables[strtolower($database)];
586 } else {
587 // one database but inexact letter case match
588 // as Drizzle is always case insensitive, we can safely return the only result
589 if (PMA_DRIZZLE && count($tables) == 1) {
590 $keys = array_keys($tables);
591 if (strlen(array_pop($keys)) == strlen($database)) {
592 return array_pop($tables);
595 return $tables;
597 } else {
598 return $tables;
603 * returns array with databases containing extended infos about them
605 * @todo move into PMA_List_Database?
606 * @param string $database database
607 * @param boolean $force_stats retrieve stats also for MySQL < 5
608 * @param resource $link mysql link
609 * @param string $sort_by column to order by
610 * @param string $sort_order ASC or DESC
611 * @param integer $limit_offset starting offset for LIMIT
612 * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
613 * @return array $databases
615 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
616 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
617 $limit_offset = 0, $limit_count = false)
619 $sort_order = strtoupper($sort_order);
621 if (true === $limit_count) {
622 $limit_count = $GLOBALS['cfg']['MaxDbList'];
625 // initialize to avoid errors when there are no databases
626 $databases = array();
628 $apply_limit_and_order_manual = true;
630 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
632 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
633 * cause MySQL does not support natural ordering, we have to do it afterward
635 $limit = '';
636 if (!$GLOBALS['cfg']['NaturalOrder']) {
637 if ($limit_count) {
638 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
641 $apply_limit_and_order_manual = false;
644 // get table information from information_schema
645 if ($database) {
646 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
647 . PMA_sqlAddSlashes($database) . '\'';
648 } else {
649 $sql_where_schema = '';
652 if (PMA_DRIZZLE) {
653 // data_dictionary.table_cache may not contain any data for some tables, it's just a table cache
654 $sql = 'SELECT
655 s.SCHEMA_NAME,
656 s.DEFAULT_COLLATION_NAME';
657 if ($force_stats) {
658 // no TABLE_CACHE data, stable results are better than constantly changing
659 $sql .= ',
660 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
661 SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
663 $sql .= '
664 FROM data_dictionary.SCHEMAS s';
665 if ($force_stats) {
666 $engine_info = PMA_cacheGet('drizzle_engines', true);
667 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
668 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
669 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
672 $sql .= "
673 LEFT JOIN data_dictionary.TABLES t
674 ON t.TABLE_SCHEMA = s.SCHEMA_NAME
675 $stats_join";
677 $sql .= $sql_where_schema . '
678 GROUP BY s.SCHEMA_NAME
679 ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
680 . $limit;
681 } else {
682 $sql = 'SELECT
683 s.SCHEMA_NAME,
684 s.DEFAULT_COLLATION_NAME';
685 if ($force_stats) {
686 $sql .= ',
687 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
688 SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
689 SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
690 SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
691 SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
692 SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
693 AS SCHEMA_LENGTH,
694 SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
696 $sql .= '
697 FROM `information_schema`.SCHEMATA s';
698 if ($force_stats) {
699 $sql .= '
700 LEFT JOIN `information_schema`.TABLES t
701 ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
703 $sql .= $sql_where_schema . '
704 GROUP BY BINARY s.SCHEMA_NAME
705 ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order
706 . $limit;
709 $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
711 $mysql_error = PMA_DBI_getError($link);
712 if (! count($databases) && $GLOBALS['errno']) {
713 PMA_mysqlDie($mysql_error, $sql);
716 // display only databases also in official database list
717 // f.e. to apply hide_db and only_db
718 $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases);
719 if (count($drops)) {
720 foreach ($drops as $drop) {
721 unset($databases[$drop]);
723 unset($drop);
725 unset($sql_where_schema, $sql, $drops);
726 } else {
727 foreach ($GLOBALS['pma']->databases as $database_name) {
728 // MySQL forward compatibility
729 // so pma could use this array as if every server is of version >5.0
730 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
732 if ($force_stats) {
733 require_once './libraries/mysql_charsets.lib.php';
735 $databases[$database_name]['DEFAULT_COLLATION_NAME']
736 = PMA_getDbCollation($database_name);
738 // get additional info about tables
739 $databases[$database_name]['SCHEMA_TABLES'] = 0;
740 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
741 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
742 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
743 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
744 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
745 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
747 $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($database_name) . ';');
748 while ($row = PMA_DBI_fetch_assoc($res)) {
749 $databases[$database_name]['SCHEMA_TABLES']++;
750 $databases[$database_name]['SCHEMA_TABLE_ROWS']
751 += $row['Rows'];
752 $databases[$database_name]['SCHEMA_DATA_LENGTH']
753 += $row['Data_length'];
754 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
755 += $row['Max_data_length'];
756 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
757 += $row['Index_length'];
759 // for InnoDB, this does not contain the number of
760 // overhead bytes but the total free space
761 if ('InnoDB' != $row['Engine']) {
762 $databases[$database_name]['SCHEMA_DATA_FREE']
763 += $row['Data_free'];
765 $databases[$database_name]['SCHEMA_LENGTH']
766 += $row['Data_length'] + $row['Index_length'];
768 PMA_DBI_free_result($res);
769 unset($res);
776 * apply limit and order manually now
777 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
779 if ($apply_limit_and_order_manual) {
780 $GLOBALS['callback_sort_order'] = $sort_order;
781 $GLOBALS['callback_sort_by'] = $sort_by;
782 usort($databases, 'PMA_usort_comparison_callback');
783 unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
786 * now apply limit
788 if ($limit_count) {
789 $databases = array_slice($databases, $limit_offset, $limit_count);
793 return $databases;
797 * returns detailed array with all columns for given table in database,
798 * or all tables/databases
800 * @param string $database name of database
801 * @param string $table name of table to retrieve columns from
802 * @param string $column name of specific column
803 * @param mixed $link mysql link resource
804 * @return array
806 function PMA_DBI_get_columns_full($database = null, $table = null,
807 $column = null, $link = null)
809 $columns = array();
811 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
812 $sql_wheres = array();
813 $array_keys = array();
815 // get columns information from information_schema
816 if (null !== $database) {
817 $sql_wheres[] = '`TABLE_SCHEMA` = \'' . PMA_sqlAddSlashes($database) . '\' ';
818 } else {
819 $array_keys[] = 'TABLE_SCHEMA';
821 if (null !== $table) {
822 $sql_wheres[] = '`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\' ';
823 } else {
824 $array_keys[] = 'TABLE_NAME';
826 if (null !== $column) {
827 $sql_wheres[] = '`COLUMN_NAME` = \'' . PMA_sqlAddSlashes($column) . '\' ';
828 } else {
829 $array_keys[] = 'COLUMN_NAME';
832 // for PMA bc:
833 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
834 if (PMA_DRIZZLE) {
835 $sql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME,
836 column_name AS `Field`,
837 (CASE
838 WHEN character_maximum_length > 0
839 THEN concat(lower(data_type), '(', character_maximum_length, ')')
840 WHEN numeric_precision > 0 OR numeric_scale > 0
841 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
842 WHEN enum_values IS NOT NULL
843 THEN concat(lower(data_type), '(', enum_values, ')')
844 ELSE lower(data_type) END)
845 AS `Type`,
846 collation_name AS `Collation`,
847 (CASE is_nullable
848 WHEN 1 THEN 'YES'
849 ELSE 'NO' END) AS `Null`,
850 (CASE
851 WHEN is_used_in_primary THEN 'PRI'
852 ELSE '' END) AS `Key`,
853 column_default AS `Default`,
854 (CASE
855 WHEN is_auto_increment THEN 'auto_increment'
856 WHEN column_default_update THEN 'on update ' || column_default_update
857 ELSE '' END) AS `Extra`,
858 NULL AS `Privileges`,
859 column_comment AS `Comment`
860 FROM data_dictionary.columns";
861 } else {
862 $sql = '
863 SELECT *,
864 `COLUMN_NAME` AS `Field`,
865 `COLUMN_TYPE` AS `Type`,
866 `COLLATION_NAME` AS `Collation`,
867 `IS_NULLABLE` AS `Null`,
868 `COLUMN_KEY` AS `Key`,
869 `COLUMN_DEFAULT` AS `Default`,
870 `EXTRA` AS `Extra`,
871 `PRIVILEGES` AS `Privileges`,
872 `COLUMN_COMMENT` AS `Comment`
873 FROM `information_schema`.`COLUMNS`';
875 if (count($sql_wheres)) {
876 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
879 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
880 unset($sql_wheres, $sql);
881 } else {
882 if (null === $database) {
883 foreach ($GLOBALS['pma']->databases as $database) {
884 $columns[$database] = PMA_DBI_get_columns_full($database, null,
885 null, $link);
887 return $columns;
888 } elseif (null === $table) {
889 $tables = PMA_DBI_get_tables($database);
890 foreach ($tables as $table) {
891 $columns[$table] = PMA_DBI_get_columns_full(
892 $database, $table, null, $link);
894 return $columns;
897 $sql = 'SHOW FULL COLUMNS FROM '
898 . PMA_backquote($database) . '.' . PMA_backquote($table);
899 if (null !== $column) {
900 $sql .= " LIKE '" . PMA_sqlAddSlashes($column, true) . "'";
903 $columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
905 $ordinal_position = 1;
906 foreach ($columns as $column_name => $each_column) {
908 // MySQL forward compatibility
909 // so pma could use this array as if every server is of version >5.0
910 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
911 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
912 $columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
913 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
914 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
915 $columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
916 $columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
917 $columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
918 $columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
920 $columns[$column_name]['TABLE_CATALOG'] = null;
921 $columns[$column_name]['TABLE_SCHEMA'] = $database;
922 $columns[$column_name]['TABLE_NAME'] = $table;
923 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
924 $columns[$column_name]['DATA_TYPE'] =
925 substr($columns[$column_name]['COLUMN_TYPE'], 0,
926 strpos($columns[$column_name]['COLUMN_TYPE'], '('));
928 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
930 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
932 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
934 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
935 $columns[$column_name]['NUMERIC_PRECISION'] = null;
936 $columns[$column_name]['NUMERIC_SCALE'] = null;
937 $columns[$column_name]['CHARACTER_SET_NAME'] =
938 substr($columns[$column_name]['COLLATION_NAME'], 0,
939 strpos($columns[$column_name]['COLLATION_NAME'], '_'));
941 $ordinal_position++;
944 if (null !== $column) {
945 reset($columns);
946 $columns = current($columns);
949 return $columns;
953 * Returns SQL query for fetching columns for a table
955 * The 'Key' column is not calculated properly, use PMA_DBI_get_columns() to get correct values.
957 * @see PMA_DBI_get_columns()
958 * @param string $database name of database
959 * @param string $table name of table to retrieve columns from
960 * @param string $column name of column, null to show all columns
961 * @param boolean $full whether to return full info or only column names
962 * @return string
964 function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
966 if (PMA_DRIZZLE) {
967 // `Key` column:
968 // * used in primary key => PRI
969 // * unique one-column => UNI
970 // * indexed, one-column or first in multi-column => MUL
971 // Promotion of UNI to PRI in case no promary index exists is done after query is executed
972 $sql = "SELECT
973 column_name AS `Field`,
974 (CASE
975 WHEN character_maximum_length > 0
976 THEN concat(lower(data_type), '(', character_maximum_length, ')')
977 WHEN numeric_precision > 0 OR numeric_scale > 0
978 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
979 WHEN enum_values IS NOT NULL
980 THEN concat(lower(data_type), '(', enum_values, ')')
981 ELSE lower(data_type) END)
982 AS `Type`,
983 " . ($full ? "
984 collation_name AS `Collation`," : '') . "
985 (CASE is_nullable
986 WHEN 1 THEN 'YES'
987 ELSE 'NO' END) AS `Null`,
988 (CASE
989 WHEN is_used_in_primary THEN 'PRI'
990 WHEN is_unique AND NOT is_multi THEN 'UNI'
991 WHEN is_indexed AND (NOT is_multi OR is_first_in_multi) THEN 'MUL'
992 ELSE '' END) AS `Key`,
993 column_default AS `Default`,
994 (CASE
995 WHEN is_auto_increment THEN 'auto_increment'
996 WHEN column_default_update <> '' THEN 'on update ' || column_default_update
997 ELSE '' END) AS `Extra`
998 " . ($full ? " ,
999 NULL AS `Privileges`,
1000 column_comment AS `Comment`" : '') . "
1001 FROM data_dictionary.columns
1002 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1003 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1004 " . ($column ? "
1005 AND column_name = '" . PMA_sqlAddSlashes($column) . "'" : '');
1006 // ORDER BY ordinal_position
1007 } else {
1008 $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
1009 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table)
1010 . ($column ? "LIKE '" . PMA_sqlAddSlashes($column, true) . "'" : '');
1012 return $sql;
1016 * Returns descriptions of columns in given table (all or given by $column)
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
1022 * @param mixed $link mysql link resource
1023 * @return false|array array indexed by column names or, if $column is given, flat array description
1025 function PMA_DBI_get_columns($database, $table, $column = null, $full = false, $link = null)
1027 $sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
1028 $fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
1029 if (! is_array($fields) || count($fields) == 0) {
1030 return null;
1032 if (PMA_DRIZZLE) {
1033 // fix Key column, it's much simpler in PHP than in SQL
1034 $has_pk = false;
1035 $has_pk_candidates = false;
1036 foreach ($fields as $f) {
1037 if ($f['Key'] == 'PRI') {
1038 $has_pk = true;
1039 break;
1040 } else if ($f['Null'] == 'NO' && ($f['Key'] == 'MUL' || $f['Key'] == 'UNI')) {
1041 $has_pk_candidates = true;
1044 if (!$has_pk && $has_pk_candidates) {
1045 // check whether we can promote some unique index to PRI
1046 $sql = "
1047 SELECT i.index_name, p.column_name
1048 FROM data_dictionary.indexes i
1049 JOIN data_dictionary.index_parts p USING (table_schema, table_name)
1050 WHERE i.table_schema = '" . PMA_sqlAddSlashes($database) . "'
1051 AND i.table_name = '" . PMA_sqlAddSlashes($table) . "'
1052 AND i.is_unique
1053 AND NOT i.is_nullable";
1054 $fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
1055 $fs = $fs ? array_shift($fs) : array();
1056 foreach ($fs as $f) {
1057 $fields[$f]['Key'] = 'PRI';
1062 return $column ? array_shift($fields) : $fields;
1066 * Returns SQL for fetching informatin on table indexes (SHOW INDEXES)
1068 * @param string $database name of database
1069 * @param string $table name of the table whose indexes are to be retreived
1070 * @param string $where additional conditions for WHERE
1071 * @return array $indexes
1073 function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
1075 if (PMA_DRIZZLE) {
1076 $sql = "SELECT
1077 ip.table_name AS `Table`,
1078 (NOT ip.is_unique) AS Non_unique,
1079 ip.index_name AS Key_name,
1080 ip.sequence_in_index+1 AS Seq_in_index,
1081 ip.column_name AS Column_name,
1082 (CASE
1083 WHEN i.index_type = 'BTREE' THEN 'A'
1084 ELSE NULL END) AS Collation,
1085 NULL AS Cardinality,
1086 compare_length AS Sub_part,
1087 NULL AS Packed,
1088 ip.is_nullable AS `Null`,
1089 i.index_type AS Index_type,
1090 NULL AS Comment,
1091 i.index_comment AS Index_comment
1092 FROM data_dictionary.index_parts ip
1093 LEFT JOIN data_dictionary.indexes i USING (table_schema, table_name, index_name)
1094 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1095 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1097 } else {
1098 $sql = 'SHOW INDEXES FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table);
1100 if ($where) {
1101 $sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
1103 return $sql;
1107 * Returns indexes od a table
1109 * @param string $database name of database
1110 * @param string $table name of the table whose indexes are to be retreived
1111 * @param mixed $link mysql link resource
1112 * @return array $indexes
1114 function PMA_DBI_get_table_indexes($database, $table, $link = null)
1116 $sql = PMA_DBI_get_table_indexes_sql($database, $table);
1117 $indexes = PMA_DBI_fetch_result($sql, null, null, $link);
1119 if (! is_array($indexes) || count($indexes) < 1) {
1120 return array();
1122 return $indexes;
1126 * returns value of given mysql server variable
1128 * @param string $var mysql server variable name
1129 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
1130 * @param mixed $link mysql link resource|object
1131 * @return mixed value for mysql server variable
1133 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
1135 if ($link === null) {
1136 if (isset($GLOBALS['userlink'])) {
1137 $link = $GLOBALS['userlink'];
1138 } else {
1139 return false;
1143 switch ($type) {
1144 case PMA_DBI_GETVAR_SESSION:
1145 $modifier = ' SESSION';
1146 break;
1147 case PMA_DBI_GETVAR_GLOBAL:
1148 $modifier = ' GLOBAL';
1149 break;
1150 default:
1151 $modifier = '';
1153 return PMA_DBI_fetch_value(
1154 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link);
1158 * Function called just after a connection to the MySQL database server has been established
1159 * It sets the connection collation, and determins the version of MySQL which is running.
1161 * @param mixed $link mysql link resource|object
1162 * @param boolean $is_controluser
1164 function PMA_DBI_postConnect($link, $is_controluser = false)
1166 if (! defined('PMA_MYSQL_INT_VERSION')) {
1167 if (PMA_cacheExists('PMA_MYSQL_INT_VERSION', true)) {
1168 define('PMA_MYSQL_INT_VERSION', PMA_cacheGet('PMA_MYSQL_INT_VERSION', true));
1169 define('PMA_MYSQL_MAJOR_VERSION', PMA_cacheGet('PMA_MYSQL_MAJOR_VERSION', true));
1170 define('PMA_MYSQL_STR_VERSION', PMA_cacheGet('PMA_MYSQL_STR_VERSION', true));
1171 define('PMA_MYSQL_VERSION_COMMENT', PMA_cacheGet('PMA_MYSQL_VERSION_COMMENT', true));
1172 } else {
1173 $version = PMA_DBI_fetch_single_row('SELECT @@version, @@version_comment', 'ASSOC', $link);
1174 if ($version) {
1175 $match = explode('.', $version['@@version']);
1176 define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
1177 define('PMA_MYSQL_INT_VERSION',
1178 (int) sprintf('%d%02d%02d', $match[0], $match[1],
1179 intval($match[2])));
1180 define('PMA_MYSQL_STR_VERSION', $version['@@version']);
1181 define('PMA_MYSQL_VERSION_COMMENT', $version['@@version_comment']);
1182 } else {
1183 define('PMA_MYSQL_INT_VERSION', 50015);
1184 define('PMA_MYSQL_MAJOR_VERSION', 5);
1185 define('PMA_MYSQL_STR_VERSION', '5.00.15');
1186 define('PMA_MYSQL_VERSION_COMMENT', '');
1188 PMA_cacheSet('PMA_MYSQL_INT_VERSION', PMA_MYSQL_INT_VERSION, true);
1189 PMA_cacheSet('PMA_MYSQL_MAJOR_VERSION', PMA_MYSQL_MAJOR_VERSION, true);
1190 PMA_cacheSet('PMA_MYSQL_STR_VERSION', PMA_MYSQL_STR_VERSION, true);
1191 PMA_cacheSet('PMA_MYSQL_VERSION_COMMENT', PMA_MYSQL_VERSION_COMMENT, true);
1193 // detect Drizzle by version number - <year>.<month>.<build number>(.<patch rev)
1194 define('PMA_DRIZZLE', PMA_MYSQL_MAJOR_VERSION >= 2009);
1197 // Skip charsets for Drizzle
1198 if (!PMA_DRIZZLE) {
1199 if (! empty($GLOBALS['collation_connection'])) {
1200 PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
1201 PMA_DBI_query("SET collation_connection = '" . PMA_sqlAddSlashes($GLOBALS['collation_connection']) . "';", $link, PMA_DBI_QUERY_STORE);
1202 } else {
1203 PMA_DBI_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci';", $link, PMA_DBI_QUERY_STORE);
1207 // Cache plugin list for Drizzle
1208 if (PMA_DRIZZLE && !PMA_cacheExists('drizzle_engines', true)) {
1209 $sql = "SELECT p.plugin_name, m.module_library
1210 FROM data_dictionary.plugins p
1211 JOIN data_dictionary.modules m USING (module_name)
1212 WHERE p.plugin_type = 'StorageEngine'
1213 AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
1214 AND p.is_active = 'YES'";
1215 $engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
1216 PMA_cacheSet('drizzle_engines', $engines, true);
1221 * returns a single value from the given result or query,
1222 * if the query or the result has more than one row or field
1223 * the first field of the first row is returned
1225 * <code>
1226 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
1227 * $user_name = PMA_DBI_fetch_value($sql);
1228 * // produces
1229 * // $user_name = 'John Doe'
1230 * </code>
1232 * @param string|mysql_result $result query or mysql result
1233 * @param integer $row_number row to fetch the value from,
1234 * starting at 0, with 0 beeing default
1235 * @param integer|string $field field to fetch the value from,
1236 * starting at 0, with 0 beeing default
1237 * @param resource $link mysql link
1238 * @param mixed $options
1239 * @return mixed value of first field in first row from result
1240 * or false if not found
1242 function PMA_DBI_fetch_value($result, $row_number = 0, $field = 0, $link = null, $options = 0)
1244 $value = false;
1246 if (is_string($result)) {
1247 $result = PMA_DBI_try_query($result, $link, $options | PMA_DBI_QUERY_STORE, false);
1250 // return false if result is empty or false
1251 // or requested row is larger than rows in result
1252 if (PMA_DBI_num_rows($result) < ($row_number + 1)) {
1253 return $value;
1256 // if $field is an integer use non associative mysql fetch function
1257 if (is_int($field)) {
1258 $fetch_function = 'PMA_DBI_fetch_row';
1259 } else {
1260 $fetch_function = 'PMA_DBI_fetch_assoc';
1263 // get requested row
1264 for ($i = 0; $i <= $row_number; $i++) {
1265 $row = $fetch_function($result);
1267 PMA_DBI_free_result($result);
1269 // return requested field
1270 if (isset($row[$field])) {
1271 $value = $row[$field];
1273 unset($row);
1275 return $value;
1279 * returns only the first row from the result
1281 * <code>
1282 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
1283 * $user = PMA_DBI_fetch_single_row($sql);
1284 * // produces
1285 * // $user = array('id' => 123, 'name' => 'John Doe')
1286 * </code>
1288 * @param string|mysql_result $result query or mysql result
1289 * @param string $type NUM|ASSOC|BOTH
1290 * returned array should either numeric
1291 * associativ or booth
1292 * @param resource $link mysql link
1293 * @param mixed $options
1294 * @return array|boolean first row from result
1295 * or false if result is empty
1297 function PMA_DBI_fetch_single_row($result, $type = 'ASSOC', $link = null, $options = 0)
1299 if (is_string($result)) {
1300 $result = PMA_DBI_try_query($result, $link, $options | PMA_DBI_QUERY_STORE, false);
1303 // return null if result is empty or false
1304 if (! PMA_DBI_num_rows($result)) {
1305 return false;
1308 switch ($type) {
1309 case 'NUM' :
1310 $fetch_function = 'PMA_DBI_fetch_row';
1311 break;
1312 case 'ASSOC' :
1313 $fetch_function = 'PMA_DBI_fetch_assoc';
1314 break;
1315 case 'BOTH' :
1316 default :
1317 $fetch_function = 'PMA_DBI_fetch_array';
1318 break;
1321 $row = $fetch_function($result);
1322 PMA_DBI_free_result($result);
1323 return $row;
1327 * returns all rows in the resultset in one array
1329 * <code>
1330 * $sql = 'SELECT * FROM `user`';
1331 * $users = PMA_DBI_fetch_result($sql);
1332 * // produces
1333 * // $users[] = array('id' => 123, 'name' => 'John Doe')
1335 * $sql = 'SELECT `id`, `name` FROM `user`';
1336 * $users = PMA_DBI_fetch_result($sql, 'id');
1337 * // produces
1338 * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
1340 * $sql = 'SELECT `id`, `name` FROM `user`';
1341 * $users = PMA_DBI_fetch_result($sql, 0);
1342 * // produces
1343 * // $users['123'] = array(0 => 123, 1 => 'John Doe')
1345 * $sql = 'SELECT `id`, `name` FROM `user`';
1346 * $users = PMA_DBI_fetch_result($sql, 'id', 'name');
1347 * // or
1348 * $users = PMA_DBI_fetch_result($sql, 0, 1);
1349 * // produces
1350 * // $users['123'] = 'John Doe'
1352 * $sql = 'SELECT `name` FROM `user`';
1353 * $users = PMA_DBI_fetch_result($sql);
1354 * // produces
1355 * // $users[] = 'John Doe'
1357 * $sql = 'SELECT `group`, `name` FROM `user`'
1358 * $users = PMA_DBI_fetch_result($sql, array('group', null), 'name');
1359 * // produces
1360 * // $users['admin'][] = 'John Doe'
1362 * $sql = 'SELECT `group`, `name` FROM `user`'
1363 * $users = PMA_DBI_fetch_result($sql, array('group', 'name'), 'id');
1364 * // produces
1365 * // $users['admin']['John Doe'] = '123'
1366 * </code>
1368 * @param string|mysql_result $result query or mysql result
1369 * @param string|integer $key field-name or offset
1370 * used as key for array
1371 * @param string|integer $value value-name or offset
1372 * used as value for array
1373 * @param resource $link mysql link
1374 * @param mixed $options
1375 * @return array resultrows or values indexed by $key
1377 function PMA_DBI_fetch_result($result, $key = null, $value = null,
1378 $link = null, $options = 0)
1380 $resultrows = array();
1382 if (is_string($result)) {
1383 $result = PMA_DBI_try_query($result, $link, $options, false);
1386 // return empty array if result is empty or false
1387 if (! $result) {
1388 return $resultrows;
1391 $fetch_function = 'PMA_DBI_fetch_assoc';
1393 // no nested array if only one field is in result
1394 if (null === $key && 1 === PMA_DBI_num_fields($result)) {
1395 $value = 0;
1396 $fetch_function = 'PMA_DBI_fetch_row';
1399 // if $key is an integer use non associative mysql fetch function
1400 if (is_int($key)) {
1401 $fetch_function = 'PMA_DBI_fetch_row';
1404 if (null === $key && null === $value) {
1405 while ($row = $fetch_function($result)) {
1406 $resultrows[] = $row;
1408 } elseif (null === $key) {
1409 while ($row = $fetch_function($result)) {
1410 $resultrows[] = $row[$value];
1412 } elseif (null === $value) {
1413 if (is_array($key)) {
1414 while ($row = $fetch_function($result)) {
1415 $result_target =& $resultrows;
1416 foreach ($key as $key_index) {
1417 if (null === $key_index) {
1418 $result_target =& $result_target[];
1419 continue;
1422 if (! isset($result_target[$row[$key_index]])) {
1423 $result_target[$row[$key_index]] = array();
1425 $result_target =& $result_target[$row[$key_index]];
1427 $result_target = $row;
1429 } else {
1430 while ($row = $fetch_function($result)) {
1431 $resultrows[$row[$key]] = $row;
1434 } else {
1435 if (is_array($key)) {
1436 while ($row = $fetch_function($result)) {
1437 $result_target =& $resultrows;
1438 foreach ($key as $key_index) {
1439 if (null === $key_index) {
1440 $result_target =& $result_target[];
1441 continue;
1444 if (! isset($result_target[$row[$key_index]])) {
1445 $result_target[$row[$key_index]] = array();
1447 $result_target =& $result_target[$row[$key_index]];
1449 $result_target = $row[$value];
1451 } else {
1452 while ($row = $fetch_function($result)) {
1453 $resultrows[$row[$key]] = $row[$value];
1458 PMA_DBI_free_result($result);
1459 return $resultrows;
1463 * return default table engine for given database
1465 * @return string default table engine
1467 function PMA_DBI_get_default_engine()
1469 return PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'storage_engine\';', 0, 1);
1473 * Get supported SQL compatibility modes
1475 * @return array supported SQL compatibility modes
1477 function PMA_DBI_getCompatibilities()
1479 // Drizzle doesn't support compatibility modes
1480 if (PMA_DRIZZLE) {
1481 return array();
1484 $compats = array('NONE');
1485 $compats[] = 'ANSI';
1486 $compats[] = 'DB2';
1487 $compats[] = 'MAXDB';
1488 $compats[] = 'MYSQL323';
1489 $compats[] = 'MYSQL40';
1490 $compats[] = 'MSSQL';
1491 $compats[] = 'ORACLE';
1492 // removed; in MySQL 5.0.33, this produces exports that
1493 // can't be read by POSTGRESQL (see our bug #1596328)
1494 //$compats[] = 'POSTGRESQL';
1495 $compats[] = 'TRADITIONAL';
1497 return $compats;
1501 * returns warnings for last query
1503 * @param resource $link mysql link resource
1504 * @return array warnings
1506 function PMA_DBI_get_warnings($link = null)
1508 if (empty($link)) {
1509 if (isset($GLOBALS['userlink'])) {
1510 $link = $GLOBALS['userlink'];
1511 } else {
1512 return array();
1516 return PMA_DBI_fetch_result('SHOW WARNINGS', null, null, $link);
1520 * returns true (int > 0) if current user is superuser
1521 * otherwise 0
1523 * @return integer $is_superuser
1525 function PMA_isSuperuser()
1527 if (PMA_cacheExists('is_superuser', true)) {
1528 return PMA_cacheGet('is_superuser', true);
1531 // when connection failed we don't have a $userlink
1532 if (isset($GLOBALS['userlink'])) {
1533 if (PMA_DRIZZLE) {
1534 // Drizzle has no authorization by default, so when no plugin is enabled everyone is a superuser
1535 // Known authorization libraries: regex_policy, simple_user_policy
1536 // Plugins limit object visibility (dbs, tables, processes), we can safely assume we always deal with superuser
1537 $r = true;
1538 } else {
1539 // check access to mysql.user table
1540 $r = (bool) PMA_DBI_try_query('SELECT COUNT(*) FROM mysql.user', $GLOBALS['userlink'], PMA_DBI_QUERY_STORE);
1542 PMA_cacheSet('is_superuser', $r, true);
1543 } else {
1544 PMA_cacheSet('is_superuser', false, true);
1547 return PMA_cacheGet('is_superuser', true);
1551 * returns an array of PROCEDURE or FUNCTION names for a db
1553 * @param string $db db name
1554 * @param string $which PROCEDURE | FUNCTION
1555 * @param resource $link mysql link
1557 * @return array the procedure names or function names
1559 function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
1561 if (PMA_DRIZZLE) {
1562 // Drizzle doesn't support functions and procedures
1563 return array();
1565 $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
1566 $result = array();
1567 foreach ($shows as $one_show) {
1568 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1569 $result[] = $one_show['Name'];
1572 return($result);
1576 * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
1578 * @param string $db db name
1579 * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
1580 * @param string $name the procedure|function|event|view name
1581 * @param resource $link mysql link
1583 * @return string the definition
1585 function PMA_DBI_get_definition($db, $which, $name, $link = null)
1587 $returned_field = array(
1588 'PROCEDURE' => 'Create Procedure',
1589 'FUNCTION' => 'Create Function',
1590 'EVENT' => 'Create Event',
1591 'VIEW' => 'Create View'
1593 $query = 'SHOW CREATE ' . $which . ' ' . PMA_backquote($db) . '.' . PMA_backquote($name);
1594 return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
1598 * returns details about the TRIGGERs for a specific table or database
1600 * @param string $db db name
1601 * @param string $table table name
1602 * @param string $delimiter the delimiter to use (may be empty)
1604 * @return array information about triggers (may be empty)
1606 function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
1608 if (PMA_DRIZZLE) {
1609 // Drizzle doesn't support triggers
1610 return array();
1613 $result = array();
1614 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1615 // Note: in http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html
1616 // their example uses WHERE TRIGGER_SCHEMA='dbname' so let's use this
1617 // instead of WHERE EVENT_OBJECT_SCHEMA='dbname'
1618 $query = "SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION, EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT, EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA= '" . PMA_sqlAddSlashes($db,true) . "';";
1619 if (! empty($table)) {
1620 $query .= " AND EVENT_OBJECT_TABLE = '" . PMA_sqlAddSlashes($table, true) . "';";
1622 } else {
1623 $query = "SHOW TRIGGERS FROM " . PMA_backquote(PMA_sqlAddSlashes($db,true));
1624 if (! empty($table)) {
1625 $query .= " LIKE '" . PMA_sqlAddSlashes($table, true) . "';";
1629 if ($triggers = PMA_DBI_fetch_result($query)) {
1630 foreach ($triggers as $trigger) {
1631 if ($GLOBALS['cfg']['Server']['DisableIS']) {
1632 $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
1633 $trigger['ACTION_TIMING'] = $trigger['Timing'];
1634 $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
1635 $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
1636 $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
1637 $trigger['DEFINER'] = $trigger['Definer'];
1639 $one_result = array();
1640 $one_result['name'] = $trigger['TRIGGER_NAME'];
1641 $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
1642 $one_result['action_timing'] = $trigger['ACTION_TIMING'];
1643 $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
1644 $one_result['definition'] = $trigger['ACTION_STATEMENT'];
1645 $one_result['definer'] = $trigger['DEFINER'];
1647 // do not prepend the schema name; this way, importing the
1648 // definition into another schema will work
1649 $one_result['full_trigger_name'] = PMA_backquote($trigger['TRIGGER_NAME']);
1650 $one_result['drop'] = 'DROP TRIGGER IF EXISTS ' . $one_result['full_trigger_name'];
1651 $one_result['create'] = 'CREATE TRIGGER ' . $one_result['full_trigger_name'] . ' ' . $trigger['ACTION_TIMING']. ' ' . $trigger['EVENT_MANIPULATION'] . ' ON ' . PMA_backquote($trigger['EVENT_OBJECT_TABLE']) . "\n" . ' FOR EACH ROW ' . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
1653 $result[] = $one_result;
1657 // Sort results by name
1658 $name = array();
1659 foreach ($result as $key => $value) {
1660 $name[] = $value['name'];
1662 array_multisort($name, SORT_ASC, $result);
1664 return($result);
1668 * Checks whether given schema is a system schema: information_schema (MySQL and Drizzle)
1669 * or data_dictionary (Drizzle)
1671 * @param string $schema_name
1672 * @param bool $test_for_mysql_schema Whether 'mysql' schema should be treated the same as IS and DD
1673 * @return bool
1675 function PMA_is_system_schema($schema_name, $test_for_mysql_schema = false)
1677 return strtolower($schema_name) == 'information_schema'
1678 || (PMA_DRIZZLE && strtolower($schema_name) == 'data_dictionary')
1679 || ($test_for_mysql_schema && !PMA_DRIZZLE && $schema_name == 'mysql');
1683 * Returns true if $db.$view_name is a view, false if not
1685 * @param string $db database name
1686 * @param string $view_name view/table name
1688 * @return bool true if $db.$view_name is a view, false if not
1690 function PMA_isView($db, $view_name)
1692 $result = PMA_DBI_fetch_result(
1693 "SELECT TABLE_NAME
1694 FROM information_schema.VIEWS
1695 WHERE TABLE_SCHEMA = '" . PMA_sqlAddSlashes($db) . "'
1696 AND TABLE_NAME = '" . PMA_sqlAddSlashes($view_name) . "'");
1698 if ($result) {
1699 return true;
1700 } else {
1701 return false;