Merge remote-tracking branch 'origin/master' into drizzle
[phpmyadmin.git] / libraries / database_interface.lib.php
blob2d0bce48050c066e3dba07193121bc9debac9a8f
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') {
29 if ($extension == 'drizzle' && function_exists('drizzle_create')) {
30 return true;
31 } else if (function_exists($extension . '_connect')) {
32 return true;
35 return false;
38 /**
39 * check for requested extension
41 if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
43 // if it fails try alternative extension ...
44 // and display an error ...
46 /**
47 * @todo add different messages for alternative extension
48 * and complete fail (no alternative extension too)
50 PMA_warnMissingExtension($GLOBALS['cfg']['Server']['extension'], false, PMA_showDocu('faqmysql'));
52 if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
53 $alternativ_extension = 'mysqli';
54 } else {
55 $alternativ_extension = 'mysql';
58 if (! PMA_DBI_checkDbExtension($alternativ_extension)) {
59 // if alternative fails too ...
60 PMA_warnMissingExtension($GLOBALS['cfg']['Server']['extension'], true, PMA_showDocu('faqmysql'));
63 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
64 unset($alternativ_extension);
67 /**
68 * Including The DBI Plugin
70 require_once './libraries/dbi/' . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php';
72 /**
73 * runs a query
75 * @param string $query
76 * @param mixed $link
77 * @param int $options
78 * @param bool $cache_affected_rows
79 * @return mixed
81 function PMA_DBI_query($query, $link = null, $options = 0, $cache_affected_rows = true) {
82 $res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
83 or PMA_mysqlDie(PMA_DBI_getError($link), $query);
84 return $res;
87 /**
88 * runs a query and returns the result
90 * @param string $query query to run
91 * @param resource $link mysql link resource
92 * @param integer $options
93 * @param bool $cache_affected_rows
94 * @return mixed
96 function PMA_DBI_try_query($query, $link = null, $options = 0, $cache_affected_rows = true)
98 if (empty($link)) {
99 if (isset($GLOBALS['userlink'])) {
100 $link = $GLOBALS['userlink'];
101 } else {
102 return false;
106 if ($GLOBALS['cfg']['DBG']['sql']) {
107 $time = microtime(true);
110 $r = PMA_DBI_real_query($query, $link, $options);
112 if ($cache_affected_rows) {
113 $GLOBALS['cached_affected_rows'] = PMA_DBI_affected_rows($link, $get_from_cache = false);
116 if ($GLOBALS['cfg']['DBG']['sql']) {
117 $time = microtime(true) - $time;
119 $hash = md5($query);
121 if (isset($_SESSION['debug']['queries'][$hash])) {
122 $_SESSION['debug']['queries'][$hash]['count']++;
123 } else {
124 $_SESSION['debug']['queries'][$hash] = array();
125 if ($r == false) {
126 $_SESSION['debug']['queries'][$hash]['error'] = '<b style="color:red">'.mysqli_error($link).'</b>';
128 $_SESSION['debug']['queries'][$hash]['count'] = 1;
129 $_SESSION['debug']['queries'][$hash]['query'] = $query;
130 $_SESSION['debug']['queries'][$hash]['time'] = $time;
133 $trace = array();
134 foreach (debug_backtrace() as $trace_step) {
135 $trace[] = PMA_Error::relPath($trace_step['file']) . '#'
136 . $trace_step['line'] . ': '
137 . (isset($trace_step['class']) ? $trace_step['class'] : '')
138 //. (isset($trace_step['object']) ? get_class($trace_step['object']) : '')
139 . (isset($trace_step['type']) ? $trace_step['type'] : '')
140 . (isset($trace_step['function']) ? $trace_step['function'] : '')
141 . '('
142 . (isset($trace_step['params']) ? implode(', ', $trace_step['params']) : '')
143 . ')'
146 $_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
148 if ($r != false && PMA_Tracker::isActive() == true ) {
149 PMA_Tracker::handleQuery($query);
152 return $r;
156 * converts charset of a mysql message, usually coming from mysql_error(),
157 * into PMA charset, usally UTF-8
158 * uses language to charset mapping from mysql/share/errmsg.txt
159 * and charset names to ISO charset from information_schema.CHARACTER_SETS
161 * @param string $message
162 * @return string $message
164 function PMA_DBI_convert_message($message) {
165 // latin always last!
166 $encodings = array(
167 'japanese' => 'EUC-JP', //'ujis',
168 'japanese-sjis' => 'Shift-JIS', //'sjis',
169 'korean' => 'EUC-KR', //'euckr',
170 'russian' => 'KOI8-R', //'koi8r',
171 'ukrainian' => 'KOI8-U', //'koi8u',
172 'greek' => 'ISO-8859-7', //'greek',
173 'serbian' => 'CP1250', //'cp1250',
174 'estonian' => 'ISO-8859-13', //'latin7',
175 'slovak' => 'ISO-8859-2', //'latin2',
176 'czech' => 'ISO-8859-2', //'latin2',
177 'hungarian' => 'ISO-8859-2', //'latin2',
178 'polish' => 'ISO-8859-2', //'latin2',
179 'romanian' => 'ISO-8859-2', //'latin2',
180 'spanish' => 'CP1252', //'latin1',
181 'swedish' => 'CP1252', //'latin1',
182 'italian' => 'CP1252', //'latin1',
183 'norwegian-ny' => 'CP1252', //'latin1',
184 'norwegian' => 'CP1252', //'latin1',
185 'portuguese' => 'CP1252', //'latin1',
186 'danish' => 'CP1252', //'latin1',
187 'dutch' => 'CP1252', //'latin1',
188 'english' => 'CP1252', //'latin1',
189 'french' => 'CP1252', //'latin1',
190 'german' => 'CP1252', //'latin1',
193 if ($server_language = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'language\';', 0, 1)) {
194 $found = array();
195 if (preg_match('&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i', $server_language, $found)) {
196 $server_language = $found[1];
200 if (! empty($server_language) && isset($encodings[$server_language])) {
201 if (function_exists('iconv')) {
202 if ((@stristr(PHP_OS, 'AIX')) && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
203 require_once './libraries/iconv_wrapper.lib.php';
204 $message = PMA_aix_iconv_wrapper($encodings[$server_language],
205 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'], $message);
206 } else {
207 $message = iconv($encodings[$server_language],
208 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'], $message);
210 } elseif (function_exists('recode_string')) {
211 $message = recode_string($encodings[$server_language] . '..' . 'utf-8',
212 $message);
213 } elseif (function_exists('libiconv')) {
214 $message = libiconv($encodings[$server_language], 'utf-8', $message);
215 } elseif (function_exists('mb_convert_encoding')) {
216 // do not try unsupported charsets
217 if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
218 $message = mb_convert_encoding($message, 'utf-8',
219 $encodings[$server_language]);
222 } else {
224 * @todo lang not found, try all, what TODO ?
228 return $message;
232 * returns array with table names for given db
234 * @param string $database name of database
235 * @param mixed $link mysql link resource|object
236 * @return array tables names
238 function PMA_DBI_get_tables($database, $link = null)
240 return PMA_DBI_fetch_result('SHOW TABLES FROM ' . PMA_backquote($database) . ';',
241 null, 0, $link, PMA_DBI_QUERY_STORE);
245 * usort comparison callback
247 * @param string $a first argument to sort
248 * @param string $b second argument to sort
250 * @return integer a value representing whether $a should be before $b in the
251 * sorted array or not
253 * @access private
255 function PMA_usort_comparison_callback($a, $b)
257 if ($GLOBALS['cfg']['NaturalOrder']) {
258 $sorter = 'strnatcasecmp';
259 } else {
260 $sorter = 'strcasecmp';
262 /* No sorting when key is not present */
263 if (! isset($a[$GLOBALS['callback_sort_by']]) || ! isset($b[$GLOBALS['callback_sort_by']])) {
264 return 0;
266 // produces f.e.:
267 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
268 return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter($a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]);
269 } // end of the 'PMA_usort_comparison_callback()' function
272 * returns array of all tables in given db or dbs
273 * this function expects unquoted names:
274 * RIGHT: my_database
275 * WRONG: `my_database`
276 * WRONG: my\_database
277 * if $tbl_is_group is true, $table is used as filter for table names
278 * if $tbl_is_group is 'comment, $table is used as filter for table comments
280 * <code>
281 * PMA_DBI_get_tables_full('my_database');
282 * PMA_DBI_get_tables_full('my_database', 'my_table'));
283 * PMA_DBI_get_tables_full('my_database', 'my_tables_', true));
284 * PMA_DBI_get_tables_full('my_database', 'my_tables_', 'comment'));
285 * </code>
287 * @todo move into PMA_Table
288 * @param string $database database
289 * @param string|bool $table table or false
290 * @param boolean|string $tbl_is_group $table is a table group
291 * @param mixed $link mysql link
292 * @param integer $limit_offset zero-based offset for the count
293 * @param boolean|integer $limit_count number of tables to return
294 * @param string $sort_by table attribute to sort by
295 * @param string $sort_order direction to sort (ASC or DESC)
296 * @return array list of tables in given db(s)
298 function PMA_DBI_get_tables_full($database, $table = false, $tbl_is_group = false, $link = null,
299 $limit_offset = 0, $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC')
301 if (true === $limit_count) {
302 $limit_count = $GLOBALS['cfg']['MaxTableList'];
304 // prepare and check parameters
305 if (! is_array($database)) {
306 $databases = array($database);
307 } else {
308 $databases = $database;
311 $tables = array();
313 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
314 // get table information from information_schema
315 if ($table) {
316 if (true === $tbl_is_group) {
317 $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
318 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
319 } elseif ('comment' === $tbl_is_group) {
320 $sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
321 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
322 } else {
323 $sql_where_table = 'AND t.`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\'';
325 } else {
326 $sql_where_table = '';
329 // for PMA bc:
330 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
332 // on non-Windows servers,
333 // added BINARY in the WHERE clause to force a case sensitive
334 // comparison (if we are looking for the db Aa we don't want
335 // to find the db aa)
336 $this_databases = array_map('PMA_sqlAddSlashes', $databases);
338 if (PMA_DRIZZLE) {
339 $engine_info = PMA_cacheGet('drizzle_engines', true);
340 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
341 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
342 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
345 // data_dictionary.table_cache may not contain any data for some tables, it's just a table cache
346 // auto_increment == 0 is cast to NULL because currently (2011.03.13 GA) Drizzle doesn't provide correct value
347 $sql = "
348 SELECT t.*,
349 t.TABLE_SCHEMA AS `Db`,
350 t.TABLE_NAME AS `Name`,
351 t.TABLE_TYPE AS `TABLE_TYPE`,
352 t.ENGINE AS `Engine`,
353 t.ENGINE AS `Type`,
354 t.TABLE_VERSION AS `Version`,-- VERSION
355 t.ROW_FORMAT AS `Row_format`,
356 coalesce(tc.ROWS, stat.NUM_ROWS)
357 AS `Rows`,-- TABLE_ROWS,
358 coalesce(tc.ROWS, stat.NUM_ROWS)
359 AS `TABLE_ROWS`,
360 tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
361 tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
362 NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
363 NULL AS `Index_length`, -- INDEX_LENGTH
364 NULL AS `Data_free`, -- DATA_FREE
365 nullif(t.AUTO_INCREMENT, 0)
366 AS `Auto_increment`,
367 t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
368 t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
369 NULL AS `Check_time`, -- CHECK_TIME
370 t.TABLE_COLLATION AS `Collation`,
371 NULL AS `Checksum`, -- CHECKSUM
372 NULL AS `Create_options`, -- CREATE_OPTIONS
373 t.TABLE_COMMENT AS `Comment`
374 FROM data_dictionary.TABLES t
375 LEFT JOIN data_dictionary.TABLE_CACHE tc ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME = t.TABLE_NAME
376 $stats_join
377 WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
378 " . $sql_where_table;
379 } else {
380 $sql = '
381 SELECT *,
382 `TABLE_SCHEMA` AS `Db`,
383 `TABLE_NAME` AS `Name`,
384 `TABLE_TYPE` AS `TABLE_TYPE`,
385 `ENGINE` AS `Engine`,
386 `ENGINE` AS `Type`,
387 `VERSION` AS `Version`,
388 `ROW_FORMAT` AS `Row_format`,
389 `TABLE_ROWS` AS `Rows`,
390 `AVG_ROW_LENGTH` AS `Avg_row_length`,
391 `DATA_LENGTH` AS `Data_length`,
392 `MAX_DATA_LENGTH` AS `Max_data_length`,
393 `INDEX_LENGTH` AS `Index_length`,
394 `DATA_FREE` AS `Data_free`,
395 `AUTO_INCREMENT` AS `Auto_increment`,
396 `CREATE_TIME` AS `Create_time`,
397 `UPDATE_TIME` AS `Update_time`,
398 `CHECK_TIME` AS `Check_time`,
399 `TABLE_COLLATION` AS `Collation`,
400 `CHECKSUM` AS `Checksum`,
401 `CREATE_OPTIONS` AS `Create_options`,
402 `TABLE_COMMENT` AS `Comment`
403 FROM `information_schema`.`TABLES` t
404 WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA` IN (\'' . implode("', '", $this_databases) . '\')
405 ' . $sql_where_table;
408 // Sort the tables
409 $sql .= " ORDER BY $sort_by $sort_order";
411 if ($limit_count) {
412 $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
415 $tables = PMA_DBI_fetch_result($sql, array('TABLE_SCHEMA', 'TABLE_NAME'),
416 null, $link);
417 unset($sql_where_table, $sql);
419 if (PMA_DRIZZLE) {
420 // correct I_S and D_D names returned by D_D.TABLES - Drizzle generally uses lower case for them,
421 // but TABLES returns uppercase
422 foreach ((array)$database as $db) {
423 $db_upper = strtoupper($db);
424 if (!isset($tables[$db]) && isset($tables[$db_upper])) {
425 $tables[$db] = $tables[$db_upper];
426 unset($tables[$db_upper]);
431 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
432 // here, the array's first key is by schema name
433 foreach ($tables as $one_database_name => $one_database_tables) {
434 uksort($one_database_tables, 'strnatcasecmp');
436 if ($sort_order == 'DESC') {
437 $one_database_tables = array_reverse($one_database_tables);
439 $tables[$one_database_name] = $one_database_tables;
442 } // end (get information from table schema)
444 // If permissions are wrong on even one database directory,
445 // information_schema does not return any table info for any database
446 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
447 if (empty($tables) && !PMA_DRIZZLE) {
448 foreach ($databases as $each_database) {
449 if ($table || (true === $tbl_is_group)) {
450 $sql = 'SHOW TABLE STATUS FROM '
451 . PMA_backquote($each_database)
452 .' LIKE \'' . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table, true)) . '%\'';
453 } else {
454 $sql = 'SHOW TABLE STATUS FROM '
455 . PMA_backquote($each_database);
458 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
460 // Sort naturally if the config allows it and we're sorting
461 // the Name column.
462 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
463 uksort($each_tables, 'strnatcasecmp');
465 if ($sort_order == 'DESC') {
466 $each_tables = array_reverse($each_tables);
468 } else {
469 // Prepare to sort by creating array of the selected sort
470 // value to pass to array_multisort
472 // Size = Data_length + Index_length
473 if ($sort_by == 'Data_length') {
474 foreach ($each_tables as $table_name => $table_data) {
475 ${$sort_by}[$table_name] = strtolower($table_data['Data_length'] + $table_data['Index_length']);
477 } else {
478 foreach ($each_tables as $table_name => $table_data) {
479 ${$sort_by}[$table_name] = strtolower($table_data[$sort_by]);
483 if ($sort_order == 'DESC') {
484 array_multisort($$sort_by, SORT_DESC, $each_tables);
485 } else {
486 array_multisort($$sort_by, SORT_ASC, $each_tables);
489 // cleanup the temporary sort array
490 unset($$sort_by);
493 if ($limit_count) {
494 $each_tables = array_slice($each_tables, $limit_offset, $limit_count);
497 foreach ($each_tables as $table_name => $each_table) {
498 if ('comment' === $tbl_is_group
499 && 0 === strpos($each_table['Comment'], $table))
501 // remove table from list
502 unset($each_tables[$table_name]);
503 continue;
506 if (! isset($each_tables[$table_name]['Type'])
507 && isset($each_tables[$table_name]['Engine'])) {
508 // pma BC, same parts of PMA still uses 'Type'
509 $each_tables[$table_name]['Type']
510 =& $each_tables[$table_name]['Engine'];
511 } elseif (! isset($each_tables[$table_name]['Engine'])
512 && isset($each_tables[$table_name]['Type'])) {
513 // old MySQL reports Type, newer MySQL reports Engine
514 $each_tables[$table_name]['Engine']
515 =& $each_tables[$table_name]['Type'];
518 // MySQL forward compatibility
519 // so pma could use this array as if every server is of version >5.0
520 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
521 $each_tables[$table_name]['TABLE_NAME'] =& $each_tables[$table_name]['Name'];
522 $each_tables[$table_name]['ENGINE'] =& $each_tables[$table_name]['Engine'];
523 $each_tables[$table_name]['VERSION'] =& $each_tables[$table_name]['Version'];
524 $each_tables[$table_name]['ROW_FORMAT'] =& $each_tables[$table_name]['Row_format'];
525 $each_tables[$table_name]['TABLE_ROWS'] =& $each_tables[$table_name]['Rows'];
526 $each_tables[$table_name]['AVG_ROW_LENGTH'] =& $each_tables[$table_name]['Avg_row_length'];
527 $each_tables[$table_name]['DATA_LENGTH'] =& $each_tables[$table_name]['Data_length'];
528 $each_tables[$table_name]['MAX_DATA_LENGTH'] =& $each_tables[$table_name]['Max_data_length'];
529 $each_tables[$table_name]['INDEX_LENGTH'] =& $each_tables[$table_name]['Index_length'];
530 $each_tables[$table_name]['DATA_FREE'] =& $each_tables[$table_name]['Data_free'];
531 $each_tables[$table_name]['AUTO_INCREMENT'] =& $each_tables[$table_name]['Auto_increment'];
532 $each_tables[$table_name]['CREATE_TIME'] =& $each_tables[$table_name]['Create_time'];
533 $each_tables[$table_name]['UPDATE_TIME'] =& $each_tables[$table_name]['Update_time'];
534 $each_tables[$table_name]['CHECK_TIME'] =& $each_tables[$table_name]['Check_time'];
535 $each_tables[$table_name]['TABLE_COLLATION'] =& $each_tables[$table_name]['Collation'];
536 $each_tables[$table_name]['CHECKSUM'] =& $each_tables[$table_name]['Checksum'];
537 $each_tables[$table_name]['CREATE_OPTIONS'] =& $each_tables[$table_name]['Create_options'];
538 $each_tables[$table_name]['TABLE_COMMENT'] =& $each_tables[$table_name]['Comment'];
540 if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
541 && $each_tables[$table_name]['Engine'] == null) {
542 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
543 } else {
545 * @todo difference between 'TEMPORARY' and 'BASE TABLE' but how to detect?
547 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
551 $tables[$each_database] = $each_tables;
555 // cache table data
556 // so PMA_Table does not require to issue SHOW TABLE STATUS again
557 // Note: I don't see why we would need array_merge_recursive() here,
558 // as it creates double entries for the same table (for example a double
559 // entry for Comment when changing the storage engine in Operations)
560 // Note 2: Instead of array_merge(), simply use the + operator because
561 // array_merge() renumbers numeric keys starting with 0, therefore
562 // we would lose a db name thats consists only of numbers
563 foreach ($tables as $one_database => $its_tables) {
564 if (isset(PMA_Table::$cache[$one_database])) {
565 PMA_Table::$cache[$one_database] = PMA_Table::$cache[$one_database] + $tables[$one_database];
566 } else {
567 PMA_Table::$cache[$one_database] = $tables[$one_database];
570 unset($one_database, $its_tables);
572 if (! is_array($database)) {
573 if (isset($tables[$database])) {
574 return $tables[$database];
575 } elseif (isset($tables[strtolower($database)])) {
576 // on windows with lower_case_table_names = 1
577 // MySQL returns
578 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
579 // but information_schema.TABLES gives `test`
580 // bug #1436171
581 // http://sf.net/support/tracker.php?aid=1436171
582 return $tables[strtolower($database)];
583 } else {
584 // one database but inexact letter case match
585 // as Drizzle is always case insensitive, we can safely return the only result
586 if (PMA_DRIZZLE && count($tables) == 1) {
587 $keys = array_keys($tables);
588 if (strlen(array_pop($keys)) == strlen($database)) {
589 return array_pop($tables);
592 return $tables;
594 } else {
595 return $tables;
600 * returns array with databases containing extended infos about them
602 * @todo move into PMA_List_Database?
603 * @param string $database database
604 * @param boolean $force_stats retrieve stats also for MySQL < 5
605 * @param resource $link mysql link
606 * @param string $sort_by column to order by
607 * @param string $sort_order ASC or DESC
608 * @param integer $limit_offset starting offset for LIMIT
609 * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
610 * @return array $databases
612 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
613 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
614 $limit_offset = 0, $limit_count = false)
616 $sort_order = strtoupper($sort_order);
618 if (true === $limit_count) {
619 $limit_count = $GLOBALS['cfg']['MaxDbList'];
622 // initialize to avoid errors when there are no databases
623 $databases = array();
625 $apply_limit_and_order_manual = true;
627 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
629 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
630 * cause MySQL does not support natural ordering, we have to do it afterward
632 $limit = '';
633 if (!$GLOBALS['cfg']['NaturalOrder']) {
634 if ($limit_count) {
635 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
638 $apply_limit_and_order_manual = false;
641 // get table information from information_schema
642 if ($database) {
643 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
644 . PMA_sqlAddSlashes($database) . '\'';
645 } else {
646 $sql_where_schema = '';
649 if (PMA_DRIZZLE) {
650 // data_dictionary.table_cache may not contain any data for some tables, it's just a table cache
651 $sql = 'SELECT
652 s.SCHEMA_NAME,
653 s.DEFAULT_COLLATION_NAME';
654 if ($force_stats) {
655 // no TABLE_CACHE data, stable results are better than constantly changing
656 $sql .= ',
657 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
658 SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
660 $sql .= '
661 FROM data_dictionary.SCHEMAS s';
662 if ($force_stats) {
663 $engine_info = PMA_cacheGet('drizzle_engines', true);
664 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
665 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
666 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
669 $sql .= "
670 LEFT JOIN data_dictionary.TABLES t
671 ON t.TABLE_SCHEMA = s.SCHEMA_NAME
672 $stats_join";
674 $sql .= $sql_where_schema . '
675 GROUP BY s.SCHEMA_NAME
676 ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
677 . $limit;
678 } else {
679 $sql = 'SELECT
680 s.SCHEMA_NAME,
681 s.DEFAULT_COLLATION_NAME';
682 if ($force_stats) {
683 $sql .= ',
684 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
685 SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
686 SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
687 SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
688 SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
689 SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
690 AS SCHEMA_LENGTH,
691 SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
693 $sql .= '
694 FROM `information_schema`.SCHEMATA s';
695 if ($force_stats) {
696 $sql .= '
697 LEFT JOIN `information_schema`.TABLES t
698 ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
700 $sql .= $sql_where_schema . '
701 GROUP BY BINARY s.SCHEMA_NAME
702 ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order
703 . $limit;
706 $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
708 $mysql_error = PMA_DBI_getError($link);
709 if (! count($databases) && $GLOBALS['errno']) {
710 PMA_mysqlDie($mysql_error, $sql);
713 // display only databases also in official database list
714 // f.e. to apply hide_db and only_db
715 $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases);
716 if (count($drops)) {
717 foreach ($drops as $drop) {
718 unset($databases[$drop]);
720 unset($drop);
722 unset($sql_where_schema, $sql, $drops);
723 } else {
724 foreach ($GLOBALS['pma']->databases as $database_name) {
725 // MySQL forward compatibility
726 // so pma could use this array as if every server is of version >5.0
727 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
729 if ($force_stats) {
730 require_once './libraries/mysql_charsets.lib.php';
732 $databases[$database_name]['DEFAULT_COLLATION_NAME']
733 = PMA_getDbCollation($database_name);
735 // get additional info about tables
736 $databases[$database_name]['SCHEMA_TABLES'] = 0;
737 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
738 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
739 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
740 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
741 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
742 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
744 $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($database_name) . ';');
745 while ($row = PMA_DBI_fetch_assoc($res)) {
746 $databases[$database_name]['SCHEMA_TABLES']++;
747 $databases[$database_name]['SCHEMA_TABLE_ROWS']
748 += $row['Rows'];
749 $databases[$database_name]['SCHEMA_DATA_LENGTH']
750 += $row['Data_length'];
751 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
752 += $row['Max_data_length'];
753 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
754 += $row['Index_length'];
756 // for InnoDB, this does not contain the number of
757 // overhead bytes but the total free space
758 if ('InnoDB' != $row['Engine']) {
759 $databases[$database_name]['SCHEMA_DATA_FREE']
760 += $row['Data_free'];
762 $databases[$database_name]['SCHEMA_LENGTH']
763 += $row['Data_length'] + $row['Index_length'];
765 PMA_DBI_free_result($res);
766 unset($res);
773 * apply limit and order manually now
774 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
776 if ($apply_limit_and_order_manual) {
777 $GLOBALS['callback_sort_order'] = $sort_order;
778 $GLOBALS['callback_sort_by'] = $sort_by;
779 usort($databases, 'PMA_usort_comparison_callback');
780 unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
783 * now apply limit
785 if ($limit_count) {
786 $databases = array_slice($databases, $limit_offset, $limit_count);
790 return $databases;
794 * returns detailed array with all columns for given table in database,
795 * or all tables/databases
797 * @param string $database name of database
798 * @param string $table name of table to retrieve columns from
799 * @param string $column name of specific column
800 * @param mixed $link mysql link resource
801 * @return array
803 function PMA_DBI_get_columns_full($database = null, $table = null,
804 $column = null, $link = null)
806 $columns = array();
808 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
809 $sql_wheres = array();
810 $array_keys = array();
812 // get columns information from information_schema
813 if (null !== $database) {
814 $sql_wheres[] = '`TABLE_SCHEMA` = \'' . PMA_sqlAddSlashes($database) . '\' ';
815 } else {
816 $array_keys[] = 'TABLE_SCHEMA';
818 if (null !== $table) {
819 $sql_wheres[] = '`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\' ';
820 } else {
821 $array_keys[] = 'TABLE_NAME';
823 if (null !== $column) {
824 $sql_wheres[] = '`COLUMN_NAME` = \'' . PMA_sqlAddSlashes($column) . '\' ';
825 } else {
826 $array_keys[] = 'COLUMN_NAME';
829 // for PMA bc:
830 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
831 if (PMA_DRIZZLE) {
832 $sql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME,
833 column_name AS `Field`,
834 (CASE
835 WHEN character_maximum_length > 0
836 THEN concat(lower(data_type), '(', character_maximum_length, ')')
837 WHEN numeric_precision > 0 OR numeric_scale > 0
838 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
839 WHEN enum_values IS NOT NULL
840 THEN concat(lower(data_type), '(', enum_values, ')')
841 ELSE lower(data_type) END)
842 AS `Type`,
843 collation_name AS `Collation`,
844 (CASE is_nullable
845 WHEN 1 THEN 'YES'
846 ELSE 'NO' END) AS `Null`,
847 (CASE
848 WHEN is_used_in_primary THEN 'PRI'
849 ELSE '' END) AS `Key`,
850 column_default AS `Default`,
851 (CASE
852 WHEN is_auto_increment THEN 'auto_increment'
853 WHEN column_default_update THEN 'on update ' || column_default_update
854 ELSE '' END) AS `Extra`,
855 NULL AS `Privileges`,
856 column_comment AS `Comment`
857 FROM data_dictionary.columns";
858 } else {
859 $sql = '
860 SELECT *,
861 `COLUMN_NAME` AS `Field`,
862 `COLUMN_TYPE` AS `Type`,
863 `COLLATION_NAME` AS `Collation`,
864 `IS_NULLABLE` AS `Null`,
865 `COLUMN_KEY` AS `Key`,
866 `COLUMN_DEFAULT` AS `Default`,
867 `EXTRA` AS `Extra`,
868 `PRIVILEGES` AS `Privileges`,
869 `COLUMN_COMMENT` AS `Comment`
870 FROM `information_schema`.`COLUMNS`';
872 if (count($sql_wheres)) {
873 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
876 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
877 unset($sql_wheres, $sql);
878 } else {
879 if (null === $database) {
880 foreach ($GLOBALS['pma']->databases as $database) {
881 $columns[$database] = PMA_DBI_get_columns_full($database, null,
882 null, $link);
884 return $columns;
885 } elseif (null === $table) {
886 $tables = PMA_DBI_get_tables($database);
887 foreach ($tables as $table) {
888 $columns[$table] = PMA_DBI_get_columns_full(
889 $database, $table, null, $link);
891 return $columns;
894 $sql = 'SHOW FULL COLUMNS FROM '
895 . PMA_backquote($database) . '.' . PMA_backquote($table);
896 if (null !== $column) {
897 $sql .= " LIKE '" . PMA_sqlAddSlashes($column, true) . "'";
900 $columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
902 $ordinal_position = 1;
903 foreach ($columns as $column_name => $each_column) {
905 // MySQL forward compatibility
906 // so pma could use this array as if every server is of version >5.0
907 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
908 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
909 $columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
910 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
911 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
912 $columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
913 $columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
914 $columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
915 $columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
917 $columns[$column_name]['TABLE_CATALOG'] = null;
918 $columns[$column_name]['TABLE_SCHEMA'] = $database;
919 $columns[$column_name]['TABLE_NAME'] = $table;
920 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
921 $columns[$column_name]['DATA_TYPE'] =
922 substr($columns[$column_name]['COLUMN_TYPE'], 0,
923 strpos($columns[$column_name]['COLUMN_TYPE'], '('));
925 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
927 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
929 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
931 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
932 $columns[$column_name]['NUMERIC_PRECISION'] = null;
933 $columns[$column_name]['NUMERIC_SCALE'] = null;
934 $columns[$column_name]['CHARACTER_SET_NAME'] =
935 substr($columns[$column_name]['COLLATION_NAME'], 0,
936 strpos($columns[$column_name]['COLLATION_NAME'], '_'));
938 $ordinal_position++;
941 if (null !== $column) {
942 reset($columns);
943 $columns = current($columns);
946 return $columns;
950 * Returns SQL query for fetching columns for a table
952 * The 'Key' column is not calculated properly, use PMA_DBI_get_columns() to get correct values.
954 * @see PMA_DBI_get_columns()
955 * @param string $database name of database
956 * @param string $table name of table to retrieve columns from
957 * @param string $column name of column, null to show all columns
958 * @param boolean $full whether to return full info or only column names
959 * @return string
961 function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
963 if (PMA_DRIZZLE) {
964 // `Key` column:
965 // * used in primary key => PRI
966 // * unique one-column => UNI
967 // * indexed, one-column or first in multi-column => MUL
968 // Promotion of UNI to PRI in case no promary index exists is done after query is executed
969 $sql = "SELECT
970 column_name AS `Field`,
971 (CASE
972 WHEN character_maximum_length > 0
973 THEN concat(lower(data_type), '(', character_maximum_length, ')')
974 WHEN numeric_precision > 0 OR numeric_scale > 0
975 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
976 WHEN enum_values IS NOT NULL
977 THEN concat(lower(data_type), '(', enum_values, ')')
978 ELSE lower(data_type) END)
979 AS `Type`,
980 " . ($full ? "
981 collation_name AS `Collation`," : '') . "
982 (CASE is_nullable
983 WHEN 1 THEN 'YES'
984 ELSE 'NO' END) AS `Null`,
985 (CASE
986 WHEN is_used_in_primary THEN 'PRI'
987 WHEN is_unique AND NOT is_multi THEN 'UNI'
988 WHEN is_indexed AND (NOT is_multi OR is_first_in_multi) THEN 'MUL'
989 ELSE '' END) AS `Key`,
990 column_default AS `Default`,
991 (CASE
992 WHEN is_auto_increment THEN 'auto_increment'
993 WHEN column_default_update <> '' THEN 'on update ' || column_default_update
994 ELSE '' END) AS `Extra`
995 " . ($full ? " ,
996 NULL AS `Privileges`,
997 column_comment AS `Comment`" : '') . "
998 FROM data_dictionary.columns
999 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1000 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1001 " . ($column ? "
1002 AND column_name = '" . PMA_sqlAddSlashes($column) . "'" : '');
1003 // ORDER BY ordinal_position
1004 } else {
1005 $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
1006 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table)
1007 . ($column ? "LIKE '" . PMA_sqlAddSlashes($column, true) . "'" : '');
1009 return $sql;
1013 * Returns descriptions of columns in given table (all or given by $column)
1015 * @param string $database name of database
1016 * @param string $table name of table to retrieve columns from
1017 * @param string $column name of column, null to show all columns
1018 * @param boolean $full whether to return full info or only column names
1019 * @param mixed $link mysql link resource
1020 * @return false|array array indexed by column names or, if $column is given, flat array description
1022 function PMA_DBI_get_columns($database, $table, $column = null, $full = false, $link = null)
1024 $sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
1025 $fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
1026 if (! is_array($fields) || count($fields) < 1) {
1027 return false;
1029 if (PMA_DRIZZLE) {
1030 // fix Key column, it's much simpler in PHP than in SQL
1031 $has_pk = false;
1032 $has_pk_candidates = false;
1033 foreach ($fields as $f) {
1034 if ($f['Key'] == 'PRI') {
1035 $has_pk = true;
1036 break;
1037 } else if ($f['Null'] == 'NO' && ($f['Key'] == 'MUL' || $f['Key'] == 'UNI')) {
1038 $has_pk_candidates = true;
1041 if (!$has_pk && $has_pk_candidates) {
1042 // check whether we can promote some unique index to PRI
1043 $sql = "
1044 SELECT i.index_name, p.column_name
1045 FROM data_dictionary.indexes i
1046 JOIN data_dictionary.index_parts p USING (table_schema, table_name)
1047 WHERE i.table_schema = '" . PMA_sqlAddSlashes($database) . "'
1048 AND i.table_name = '" . PMA_sqlAddSlashes($table) . "'
1049 AND i.is_unique
1050 AND NOT i.is_nullable";
1051 $fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
1052 $fs = $fs ? array_shift($fs) : array();
1053 foreach ($fs as $f) {
1054 $fields[$f]['Key'] = 'PRI';
1059 return $column ? array_shift($fields) : $fields;
1063 * Returns SQL for fetching informatin on table indexes (SHOW INDEXES)
1065 * @param string $database name of database
1066 * @param string $table name of the table whose indexes are to be retreived
1067 * @param string $where additional conditions for WHERE
1068 * @return array $indexes
1070 function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
1072 if (PMA_DRIZZLE) {
1073 $sql = "SELECT
1074 ip.table_name AS `Table`,
1075 (NOT ip.is_unique) AS Non_unique,
1076 ip.index_name AS Key_name,
1077 ip.sequence_in_index+1 AS Seq_in_index,
1078 ip.column_name AS Column_name,
1079 (CASE
1080 WHEN i.index_type = 'BTREE' THEN 'A'
1081 ELSE NULL END) AS Collation,
1082 NULL AS Cardinality,
1083 compare_length AS Sub_part,
1084 NULL AS Packed,
1085 ip.is_nullable AS `Null`,
1086 i.index_type AS Index_type,
1087 NULL AS Comment,
1088 i.index_comment AS Index_comment
1089 FROM data_dictionary.index_parts ip
1090 LEFT JOIN data_dictionary.indexes i USING (table_schema, table_name, index_name)
1091 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1092 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1094 } else {
1095 $sql = 'SHOW INDEXES FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table);
1097 if ($where) {
1098 $sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
1100 return $sql;
1104 * array PMA_DBI_get_table_indexes($database, $table, $link = null)
1106 * @param string $database name of database
1107 * @param string $table name of the table whose indexes are to be retreived
1108 * @param mixed $link mysql link resource
1109 * @return array $indexes
1111 function PMA_DBI_get_table_indexes($database, $table, $link = null)
1113 $sql = PMA_DBI_get_table_indexes_sql($database, $table);
1114 $indexes = PMA_DBI_fetch_result($sql, null, null, $link);
1116 if (! is_array($indexes) || count($indexes) < 1) {
1117 return false;
1119 return $indexes;
1123 * returns value of given mysql server variable
1125 * @param string $var mysql server variable name
1126 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
1127 * @param mixed $link mysql link resource|object
1128 * @return mixed value for mysql server variable
1130 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
1132 if ($link === null) {
1133 if (isset($GLOBALS['userlink'])) {
1134 $link = $GLOBALS['userlink'];
1135 } else {
1136 return false;
1140 switch ($type) {
1141 case PMA_DBI_GETVAR_SESSION:
1142 $modifier = ' SESSION';
1143 break;
1144 case PMA_DBI_GETVAR_GLOBAL:
1145 $modifier = ' GLOBAL';
1146 break;
1147 default:
1148 $modifier = '';
1150 return PMA_DBI_fetch_value(
1151 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link);
1155 * Function called just after a connection to the MySQL database server has been established
1156 * It sets the connection collation, and determins the version of MySQL which is running.
1158 * @param mixed $link mysql link resource|object
1159 * @param boolean $is_controluser
1161 function PMA_DBI_postConnect($link, $is_controluser = false)
1163 if (! defined('PMA_MYSQL_INT_VERSION')) {
1164 if (PMA_cacheExists('PMA_MYSQL_INT_VERSION', true)) {
1165 define('PMA_MYSQL_INT_VERSION', PMA_cacheGet('PMA_MYSQL_INT_VERSION', true));
1166 define('PMA_MYSQL_MAJOR_VERSION', PMA_cacheGet('PMA_MYSQL_MAJOR_VERSION', true));
1167 define('PMA_MYSQL_STR_VERSION', PMA_cacheGet('PMA_MYSQL_STR_VERSION', true));
1168 } else {
1169 $mysql_version = PMA_DBI_fetch_value(
1170 'SELECT VERSION()', 0, 0, $link, PMA_DBI_QUERY_STORE);
1171 if ($mysql_version) {
1172 $match = explode('.', $mysql_version);
1173 define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
1174 define('PMA_MYSQL_INT_VERSION',
1175 (int) sprintf('%d%02d%02d', $match[0], $match[1],
1176 intval($match[2])));
1177 define('PMA_MYSQL_STR_VERSION', $mysql_version);
1178 unset($mysql_version, $match);
1179 } else {
1180 define('PMA_MYSQL_INT_VERSION', 50015);
1181 define('PMA_MYSQL_MAJOR_VERSION', 5);
1182 define('PMA_MYSQL_STR_VERSION', '5.00.15');
1184 PMA_cacheSet('PMA_MYSQL_INT_VERSION', PMA_MYSQL_INT_VERSION, true);
1185 PMA_cacheSet('PMA_MYSQL_MAJOR_VERSION', PMA_MYSQL_MAJOR_VERSION, true);
1186 PMA_cacheSet('PMA_MYSQL_STR_VERSION', PMA_MYSQL_STR_VERSION, true);
1188 // detect Drizzle by version number - <year>.<month>.<build number>(.<patch rev)
1189 define('PMA_DRIZZLE', PMA_MYSQL_MAJOR_VERSION >= 2009);
1192 // Skip charsets for Drizzle
1193 if (!PMA_DRIZZLE) {
1194 if (! empty($GLOBALS['collation_connection'])) {
1195 PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
1196 PMA_DBI_query("SET collation_connection = '" . PMA_sqlAddSlashes($GLOBALS['collation_connection']) . "';", $link, PMA_DBI_QUERY_STORE);
1197 } else {
1198 PMA_DBI_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci';", $link, PMA_DBI_QUERY_STORE);
1202 // Cache plugin list for Drizzle
1203 if (PMA_DRIZZLE && !PMA_cacheExists('drizzle_engines', true)) {
1204 $sql = "SELECT p.plugin_name, m.module_library
1205 FROM data_dictionary.plugins p
1206 JOIN data_dictionary.modules m USING (module_name)
1207 WHERE p.plugin_type = 'StorageEngine'
1208 AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
1209 AND p.is_active = 'YES'";
1210 $engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
1211 PMA_cacheSet('drizzle_engines', $engines, true);
1216 * returns a single value from the given result or query,
1217 * if the query or the result has more than one row or field
1218 * the first field of the first row is returned
1220 * <code>
1221 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
1222 * $user_name = PMA_DBI_fetch_value($sql);
1223 * // produces
1224 * // $user_name = 'John Doe'
1225 * </code>
1227 * @param string|mysql_result $result query or mysql result
1228 * @param integer $row_number row to fetch the value from,
1229 * starting at 0, with 0 beeing default
1230 * @param integer|string $field field to fetch the value from,
1231 * starting at 0, with 0 beeing default
1232 * @param resource $link mysql link
1233 * @param mixed $options
1234 * @return mixed value of first field in first row from result
1235 * or false if not found
1237 function PMA_DBI_fetch_value($result, $row_number = 0, $field = 0, $link = null, $options = 0) {
1238 $value = false;
1240 if (is_string($result)) {
1241 $result = PMA_DBI_try_query($result, $link, $options | PMA_DBI_QUERY_STORE, false);
1244 // return false if result is empty or false
1245 // or requested row is larger than rows in result
1246 if (PMA_DBI_num_rows($result) < ($row_number + 1)) {
1247 return $value;
1250 // if $field is an integer use non associative mysql fetch function
1251 if (is_int($field)) {
1252 $fetch_function = 'PMA_DBI_fetch_row';
1253 } else {
1254 $fetch_function = 'PMA_DBI_fetch_assoc';
1257 // get requested row
1258 for ($i = 0; $i <= $row_number; $i++) {
1259 $row = $fetch_function($result);
1261 PMA_DBI_free_result($result);
1263 // return requested field
1264 if (isset($row[$field])) {
1265 $value = $row[$field];
1267 unset($row);
1269 return $value;
1273 * returns only the first row from the result
1275 * <code>
1276 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
1277 * $user = PMA_DBI_fetch_single_row($sql);
1278 * // produces
1279 * // $user = array('id' => 123, 'name' => 'John Doe')
1280 * </code>
1282 * @param string|mysql_result $result query or mysql result
1283 * @param string $type NUM|ASSOC|BOTH
1284 * returned array should either numeric
1285 * associativ or booth
1286 * @param resource $link mysql link
1287 * @param mixed $options
1288 * @return array|boolean first row from result
1289 * or false if result is empty
1291 function PMA_DBI_fetch_single_row($result, $type = 'ASSOC', $link = null, $options = 0) {
1292 if (is_string($result)) {
1293 $result = PMA_DBI_try_query($result, $link, $options | PMA_DBI_QUERY_STORE, false);
1296 // return null if result is empty or false
1297 if (! PMA_DBI_num_rows($result)) {
1298 return false;
1301 switch ($type) {
1302 case 'NUM' :
1303 $fetch_function = 'PMA_DBI_fetch_row';
1304 break;
1305 case 'ASSOC' :
1306 $fetch_function = 'PMA_DBI_fetch_assoc';
1307 break;
1308 case 'BOTH' :
1309 default :
1310 $fetch_function = 'PMA_DBI_fetch_array';
1311 break;
1314 $row = $fetch_function($result);
1315 PMA_DBI_free_result($result);
1316 return $row;
1320 * returns all rows in the resultset in one array
1322 * <code>
1323 * $sql = 'SELECT * FROM `user`';
1324 * $users = PMA_DBI_fetch_result($sql);
1325 * // produces
1326 * // $users[] = array('id' => 123, 'name' => 'John Doe')
1328 * $sql = 'SELECT `id`, `name` FROM `user`';
1329 * $users = PMA_DBI_fetch_result($sql, 'id');
1330 * // produces
1331 * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
1333 * $sql = 'SELECT `id`, `name` FROM `user`';
1334 * $users = PMA_DBI_fetch_result($sql, 0);
1335 * // produces
1336 * // $users['123'] = array(0 => 123, 1 => 'John Doe')
1338 * $sql = 'SELECT `id`, `name` FROM `user`';
1339 * $users = PMA_DBI_fetch_result($sql, 'id', 'name');
1340 * // or
1341 * $users = PMA_DBI_fetch_result($sql, 0, 1);
1342 * // produces
1343 * // $users['123'] = 'John Doe'
1345 * $sql = 'SELECT `name` FROM `user`';
1346 * $users = PMA_DBI_fetch_result($sql);
1347 * // produces
1348 * // $users[] = 'John Doe'
1350 * $sql = 'SELECT `group`, `name` FROM `user`'
1351 * $users = PMA_DBI_fetch_result($sql, array('group', null), 'name');
1352 * // produces
1353 * // $users['admin'][] = 'John Doe'
1355 * $sql = 'SELECT `group`, `name` FROM `user`'
1356 * $users = PMA_DBI_fetch_result($sql, array('group', 'name'), 'id');
1357 * // produces
1358 * // $users['admin']['John Doe'] = '123'
1359 * </code>
1361 * @param string|mysql_result $result query or mysql result
1362 * @param string|integer $key field-name or offset
1363 * used as key for array
1364 * @param string|integer $value value-name or offset
1365 * used as value for array
1366 * @param resource $link mysql link
1367 * @param mixed $options
1368 * @return array resultrows or values indexed by $key
1370 function PMA_DBI_fetch_result($result, $key = null, $value = null,
1371 $link = null, $options = 0)
1373 $resultrows = array();
1375 if (is_string($result)) {
1376 $result = PMA_DBI_try_query($result, $link, $options, false);
1379 // return empty array if result is empty or false
1380 if (! $result) {
1381 return $resultrows;
1384 $fetch_function = 'PMA_DBI_fetch_assoc';
1386 // no nested array if only one field is in result
1387 if (null === $key && 1 === PMA_DBI_num_fields($result)) {
1388 $value = 0;
1389 $fetch_function = 'PMA_DBI_fetch_row';
1392 // if $key is an integer use non associative mysql fetch function
1393 if (is_int($key)) {
1394 $fetch_function = 'PMA_DBI_fetch_row';
1397 if (null === $key && null === $value) {
1398 while ($row = $fetch_function($result)) {
1399 $resultrows[] = $row;
1401 } elseif (null === $key) {
1402 while ($row = $fetch_function($result)) {
1403 $resultrows[] = $row[$value];
1405 } elseif (null === $value) {
1406 if (is_array($key)) {
1407 while ($row = $fetch_function($result)) {
1408 $result_target =& $resultrows;
1409 foreach ($key as $key_index) {
1410 if (null === $key_index) {
1411 $result_target =& $result_target[];
1412 continue;
1415 if (! isset($result_target[$row[$key_index]])) {
1416 $result_target[$row[$key_index]] = array();
1418 $result_target =& $result_target[$row[$key_index]];
1420 $result_target = $row;
1422 } else {
1423 while ($row = $fetch_function($result)) {
1424 $resultrows[$row[$key]] = $row;
1427 } else {
1428 if (is_array($key)) {
1429 while ($row = $fetch_function($result)) {
1430 $result_target =& $resultrows;
1431 foreach ($key as $key_index) {
1432 if (null === $key_index) {
1433 $result_target =& $result_target[];
1434 continue;
1437 if (! isset($result_target[$row[$key_index]])) {
1438 $result_target[$row[$key_index]] = array();
1440 $result_target =& $result_target[$row[$key_index]];
1442 $result_target = $row[$value];
1444 } else {
1445 while ($row = $fetch_function($result)) {
1446 $resultrows[$row[$key]] = $row[$value];
1451 PMA_DBI_free_result($result);
1452 return $resultrows;
1456 * return default table engine for given database
1458 * @return string default table engine
1460 function PMA_DBI_get_default_engine()
1462 return PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'storage_engine\';', 0, 1);
1466 * Get supported SQL compatibility modes
1468 * @return array supported SQL compatibility modes
1470 function PMA_DBI_getCompatibilities()
1472 // Drizzle doesn't support compatibility modes
1473 if (PMA_DRIZZLE) {
1474 return array();
1477 $compats = array('NONE');
1478 $compats[] = 'ANSI';
1479 $compats[] = 'DB2';
1480 $compats[] = 'MAXDB';
1481 $compats[] = 'MYSQL323';
1482 $compats[] = 'MYSQL40';
1483 $compats[] = 'MSSQL';
1484 $compats[] = 'ORACLE';
1485 // removed; in MySQL 5.0.33, this produces exports that
1486 // can't be read by POSTGRESQL (see our bug #1596328)
1487 //$compats[] = 'POSTGRESQL';
1488 $compats[] = 'TRADITIONAL';
1490 return $compats;
1494 * returns warnings for last query
1496 * @param resource $link mysql link resource
1497 * @return array warnings
1499 function PMA_DBI_get_warnings($link = null)
1501 if (empty($link)) {
1502 if (isset($GLOBALS['userlink'])) {
1503 $link = $GLOBALS['userlink'];
1504 } else {
1505 return array();
1509 return PMA_DBI_fetch_result('SHOW WARNINGS', null, null, $link);
1513 * returns true (int > 0) if current user is superuser
1514 * otherwise 0
1516 * @return integer $is_superuser
1518 function PMA_isSuperuser()
1520 if (PMA_cacheExists('is_superuser', true)) {
1521 return PMA_cacheGet('is_superuser', true);
1524 // when connection failed we don't have a $userlink
1525 if (isset($GLOBALS['userlink'])) {
1526 if (PMA_DRIZZLE) {
1527 // Drizzle has no authorization by default, so when no plugin is enabled everyone is a superuser
1528 // Known authorization libraries: regex_policy, simple_user_policy
1529 // Plugins limit object visibility (dbs, tables, processes), we can safely assume we always deal with superuser
1530 $r = true;
1531 } else {
1532 // check access to mysql.user table
1533 $r = (bool) PMA_DBI_try_query('SELECT COUNT(*) FROM mysql.user', $GLOBALS['userlink'], PMA_DBI_QUERY_STORE);
1535 PMA_cacheSet('is_superuser', $r, true);
1536 } else {
1537 PMA_cacheSet('is_superuser', false, true);
1540 return PMA_cacheGet('is_superuser', true);
1544 * returns an array of PROCEDURE or FUNCTION names for a db
1546 * @param string $db db name
1547 * @param string $which PROCEDURE | FUNCTION
1548 * @param resource $link mysql link
1550 * @return array the procedure names or function names
1552 function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
1554 if (PMA_DRIZZLE) {
1555 // Drizzle doesn't support functions and procedures
1556 return array();
1558 $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
1559 $result = array();
1560 foreach ($shows as $one_show) {
1561 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1562 $result[] = $one_show['Name'];
1565 return($result);
1569 * returns the definition of a specific PROCEDURE, FUNCTION or EVENT
1571 * @param string $db db name
1572 * @param string $which PROCEDURE | FUNCTION | EVENT
1573 * @param string $name the procedure|function|event name
1574 * @param resource $link mysql link
1576 * @return string the definition
1578 function PMA_DBI_get_definition($db, $which, $name, $link = null)
1580 $returned_field = array(
1581 'PROCEDURE' => 'Create Procedure',
1582 'FUNCTION' => 'Create Function',
1583 'EVENT' => 'Create Event'
1585 $query = 'SHOW CREATE ' . $which . ' ' . PMA_backquote($db) . '.' . PMA_backquote($name);
1586 return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
1590 * returns details about the TRIGGERs for a specific table or database
1592 * @param string $db db name
1593 * @param string $table table name
1594 * @param string $delimiter the delimiter to use (may be empty)
1596 * @return array information about triggers (may be empty)
1598 function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
1600 if (PMA_DRIZZLE) {
1601 // Drizzle doesn't support triggers
1602 return array();
1605 $result = array();
1606 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1607 // Note: in http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html
1608 // their example uses WHERE TRIGGER_SCHEMA='dbname' so let's use this
1609 // instead of WHERE EVENT_OBJECT_SCHEMA='dbname'
1610 $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) . "';";
1611 if (! empty($table)) {
1612 $query .= " AND EVENT_OBJECT_TABLE = '" . PMA_sqlAddSlashes($table, true) . "';";
1614 } else {
1615 $query = "SHOW TRIGGERS FROM " . PMA_backquote(PMA_sqlAddSlashes($db,true));
1616 if (! empty($table)) {
1617 $query .= " LIKE '" . PMA_sqlAddSlashes($table, true) . "';";
1621 if ($triggers = PMA_DBI_fetch_result($query)) {
1622 foreach ($triggers as $trigger) {
1623 if ($GLOBALS['cfg']['Server']['DisableIS']) {
1624 $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
1625 $trigger['ACTION_TIMING'] = $trigger['Timing'];
1626 $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
1627 $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
1628 $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
1629 $trigger['DEFINER'] = $trigger['Definer'];
1631 $one_result = array();
1632 $one_result['name'] = $trigger['TRIGGER_NAME'];
1633 $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
1634 $one_result['action_timing'] = $trigger['ACTION_TIMING'];
1635 $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
1636 $one_result['definition'] = $trigger['ACTION_STATEMENT'];
1637 $one_result['definer'] = $trigger['DEFINER'];
1639 // do not prepend the schema name; this way, importing the
1640 // definition into another schema will work
1641 $one_result['full_trigger_name'] = PMA_backquote($trigger['TRIGGER_NAME']);
1642 $one_result['drop'] = 'DROP TRIGGER IF EXISTS ' . $one_result['full_trigger_name'];
1643 $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";
1645 $result[] = $one_result;
1649 // Sort results by name
1650 $name = array();
1651 foreach ($result as $key => $value) {
1652 $name[] = $value['name'];
1654 array_multisort($name, SORT_ASC, $result);
1656 return($result);
1660 * Returns true if $db.$view_name is a view, false if not
1662 * @param string $db database name
1663 * @param string $view_name view/table name
1665 * @return bool true if $db.$view_name is a view, false if not
1667 function PMA_isView($db, $view_name)
1669 $result = PMA_DBI_fetch_result(
1670 "SELECT TABLE_NAME
1671 FROM information_schema.VIEWS
1672 WHERE TABLE_SCHEMA = '" . PMA_sqlAddSlashes($db) . "'
1673 AND TABLE_NAME = '" . PMA_sqlAddSlashes($view_name) . "'");
1675 if ($result) {
1676 return true;
1677 } else {
1678 return false;