Translation update done using Pootle.
[phpmyadmin/madhuracj.git] / libraries / database_interface.lib.php
blobc356b903fce1c5300edaa28f43b4f221f5c8d634
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Common Option Constants For DBI Functions
6 * @package PhpMyAdmin
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
13 * Force STORE_RESULT method, ignored by classic MySQL.
15 define('PMA_DBI_QUERY_STORE', 1);
16 /**
17 * Do not read whole query.
19 define('PMA_DBI_QUERY_UNBUFFERED', 2);
20 /**
21 * Get session variable.
23 define('PMA_DBI_GETVAR_SESSION', 1);
24 /**
25 * Get global variable.
27 define('PMA_DBI_GETVAR_GLOBAL', 2);
29 /**
30 * Checks whether database extension is loaded
32 * @param string $extension mysql extension to check
33 * @return bool
35 function PMA_DBI_checkDbExtension($extension = 'mysql')
37 if ($extension == 'drizzle' && function_exists('drizzle_create')) {
38 return true;
39 } else if (function_exists($extension . '_connect')) {
40 return true;
43 return false;
46 /**
47 * check for requested extension
49 if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
51 // if it fails try alternative extension ...
52 // and display an error ...
54 /**
55 * @todo add different messages for alternative extension
56 * and complete fail (no alternative extension too)
58 PMA_warnMissingExtension(
59 $GLOBALS['cfg']['Server']['extension'],
60 false,
61 PMA_showDocu('faqmysql')
64 if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
65 $alternativ_extension = 'mysqli';
66 } else {
67 $alternativ_extension = 'mysql';
70 if (! PMA_DBI_checkDbExtension($alternativ_extension)) {
71 // if alternative fails too ...
72 PMA_warnMissingExtension(
73 $GLOBALS['cfg']['Server']['extension'],
74 true,
75 PMA_showDocu('faqmysql')
79 $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
80 unset($alternativ_extension);
83 /**
84 * Including The DBI Plugin
86 require_once './libraries/dbi/'
87 . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php';
89 /**
90 * runs a query
92 * @param string $query SQL query to execte
93 * @param mixed $link optional database link to use
94 * @param int $options optional query options
95 * @param bool $cache_affected_rows whether to cache affected rows
96 * @return mixed
98 function PMA_DBI_query($query, $link = null, $options = 0, $cache_affected_rows = true)
100 $res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
101 or PMA_mysqlDie(PMA_DBI_getError($link), $query);
102 return $res;
106 * runs a query and returns the result
108 * @param string $query query to run
109 * @param resource $link mysql link resource
110 * @param integer $options
111 * @param bool $cache_affected_rows
112 * @return mixed
114 function PMA_DBI_try_query($query, $link = null, $options = 0, $cache_affected_rows = true)
116 if (empty($link)) {
117 if (isset($GLOBALS['userlink'])) {
118 $link = $GLOBALS['userlink'];
119 } else {
120 return false;
124 if ($GLOBALS['cfg']['DBG']['sql']) {
125 $time = microtime(true);
128 $r = PMA_DBI_real_query($query, $link, $options);
130 if ($cache_affected_rows) {
131 $GLOBALS['cached_affected_rows'] = PMA_DBI_affected_rows($link, $get_from_cache = false);
134 if ($GLOBALS['cfg']['DBG']['sql']) {
135 $time = microtime(true) - $time;
137 $hash = md5($query);
139 if (isset($_SESSION['debug']['queries'][$hash])) {
140 $_SESSION['debug']['queries'][$hash]['count']++;
141 } else {
142 $_SESSION['debug']['queries'][$hash] = array();
143 if ($r == false) {
144 $_SESSION['debug']['queries'][$hash]['error'] = '<b style="color:red">'.mysqli_error($link).'</b>';
146 $_SESSION['debug']['queries'][$hash]['count'] = 1;
147 $_SESSION['debug']['queries'][$hash]['query'] = $query;
148 $_SESSION['debug']['queries'][$hash]['time'] = $time;
151 $trace = array();
152 foreach (debug_backtrace() as $trace_step) {
153 $trace[] = PMA_Error::relPath($trace_step['file']) . '#'
154 . $trace_step['line'] . ': '
155 . (isset($trace_step['class']) ? $trace_step['class'] : '')
156 //. (isset($trace_step['object']) ? get_class($trace_step['object']) : '')
157 . (isset($trace_step['type']) ? $trace_step['type'] : '')
158 . (isset($trace_step['function']) ? $trace_step['function'] : '')
159 . '('
160 . (isset($trace_step['params']) ? implode(', ', $trace_step['params']) : '')
161 . ')'
164 $_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
166 if ($r != false && PMA_Tracker::isActive() == true ) {
167 PMA_Tracker::handleQuery($query);
170 return $r;
174 * converts charset of a mysql message, usually coming from mysql_error(),
175 * into PMA charset, usally UTF-8
176 * uses language to charset mapping from mysql/share/errmsg.txt
177 * and charset names to ISO charset from information_schema.CHARACTER_SETS
179 * @param string $message
180 * @return string $message
182 function PMA_DBI_convert_message($message)
184 // latin always last!
185 $encodings = array(
186 'japanese' => 'EUC-JP', //'ujis',
187 'japanese-sjis' => 'Shift-JIS', //'sjis',
188 'korean' => 'EUC-KR', //'euckr',
189 'russian' => 'KOI8-R', //'koi8r',
190 'ukrainian' => 'KOI8-U', //'koi8u',
191 'greek' => 'ISO-8859-7', //'greek',
192 'serbian' => 'CP1250', //'cp1250',
193 'estonian' => 'ISO-8859-13', //'latin7',
194 'slovak' => 'ISO-8859-2', //'latin2',
195 'czech' => 'ISO-8859-2', //'latin2',
196 'hungarian' => 'ISO-8859-2', //'latin2',
197 'polish' => 'ISO-8859-2', //'latin2',
198 'romanian' => 'ISO-8859-2', //'latin2',
199 'spanish' => 'CP1252', //'latin1',
200 'swedish' => 'CP1252', //'latin1',
201 'italian' => 'CP1252', //'latin1',
202 'norwegian-ny' => 'CP1252', //'latin1',
203 'norwegian' => 'CP1252', //'latin1',
204 'portuguese' => 'CP1252', //'latin1',
205 'danish' => 'CP1252', //'latin1',
206 'dutch' => 'CP1252', //'latin1',
207 'english' => 'CP1252', //'latin1',
208 'french' => 'CP1252', //'latin1',
209 'german' => 'CP1252', //'latin1',
212 if ($server_language = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'language\';', 0, 1)) {
213 $found = array();
214 if (preg_match('&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i', $server_language, $found)) {
215 $server_language = $found[1];
219 if (! empty($server_language) && isset($encodings[$server_language])) {
220 if (function_exists('iconv')) {
221 if ((@stristr(PHP_OS, 'AIX')) && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) {
222 include_once './libraries/iconv_wrapper.lib.php';
223 $message = PMA_aix_iconv_wrapper($encodings[$server_language],
224 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'], $message);
225 } else {
226 $message = iconv($encodings[$server_language],
227 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'], $message);
229 } elseif (function_exists('recode_string')) {
230 $message = recode_string($encodings[$server_language] . '..' . 'utf-8',
231 $message);
232 } elseif (function_exists('libiconv')) {
233 $message = libiconv($encodings[$server_language], 'utf-8', $message);
234 } elseif (function_exists('mb_convert_encoding')) {
235 // do not try unsupported charsets
236 if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
237 $message = mb_convert_encoding($message, 'utf-8',
238 $encodings[$server_language]);
241 } else {
243 * @todo lang not found, try all, what TODO ?
247 return $message;
251 * returns array with table names for given db
253 * @param string $database name of database
254 * @param mixed $link mysql link resource|object
255 * @return array tables names
257 function PMA_DBI_get_tables($database, $link = null)
259 return PMA_DBI_fetch_result('SHOW TABLES FROM ' . PMA_backquote($database) . ';',
260 null, 0, $link, PMA_DBI_QUERY_STORE);
264 * usort comparison callback
266 * @param string $a first argument to sort
267 * @param string $b second argument to sort
269 * @return integer a value representing whether $a should be before $b in the
270 * sorted array or not
272 * @access private
274 function PMA_usort_comparison_callback($a, $b)
276 if ($GLOBALS['cfg']['NaturalOrder']) {
277 $sorter = 'strnatcasecmp';
278 } else {
279 $sorter = 'strcasecmp';
281 /* No sorting when key is not present */
282 if (! isset($a[$GLOBALS['callback_sort_by']]) || ! isset($b[$GLOBALS['callback_sort_by']])) {
283 return 0;
285 // produces f.e.:
286 // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
287 return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter($a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]);
288 } // end of the 'PMA_usort_comparison_callback()' function
291 * returns array of all tables in given db or dbs
292 * this function expects unquoted names:
293 * RIGHT: my_database
294 * WRONG: `my_database`
295 * WRONG: my\_database
296 * if $tbl_is_group is true, $table is used as filter for table names
297 * if $tbl_is_group is 'comment, $table is used as filter for table comments
299 * <code>
300 * PMA_DBI_get_tables_full('my_database');
301 * PMA_DBI_get_tables_full('my_database', 'my_table'));
302 * PMA_DBI_get_tables_full('my_database', 'my_tables_', true));
303 * PMA_DBI_get_tables_full('my_database', 'my_tables_', 'comment'));
304 * </code>
306 * @todo move into PMA_Table
307 * @param string $database database
308 * @param string|bool $table table or false
309 * @param boolean|string $tbl_is_group $table is a table group
310 * @param mixed $link mysql link
311 * @param integer $limit_offset zero-based offset for the count
312 * @param boolean|integer $limit_count number of tables to return
313 * @param string $sort_by table attribute to sort by
314 * @param string $sort_order direction to sort (ASC or DESC)
315 * @return array list of tables in given db(s)
317 function PMA_DBI_get_tables_full($database, $table = false, $tbl_is_group = false, $link = null,
318 $limit_offset = 0, $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC')
320 if (true === $limit_count) {
321 $limit_count = $GLOBALS['cfg']['MaxTableList'];
323 // prepare and check parameters
324 if (! is_array($database)) {
325 $databases = array($database);
326 } else {
327 $databases = $database;
330 $tables = array();
332 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
333 // get table information from information_schema
334 if ($table) {
335 if (true === $tbl_is_group) {
336 $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
337 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
338 } elseif ('comment' === $tbl_is_group) {
339 $sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
340 . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table)) . '%\'';
341 } else {
342 $sql_where_table = 'AND t.`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\'';
344 } else {
345 $sql_where_table = '';
348 // for PMA bc:
349 // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
351 // on non-Windows servers,
352 // added BINARY in the WHERE clause to force a case sensitive
353 // comparison (if we are looking for the db Aa we don't want
354 // to find the db aa)
355 $this_databases = array_map('PMA_sqlAddSlashes', $databases);
357 if (PMA_DRIZZLE) {
358 $engine_info = PMA_cacheGet('drizzle_engines', true);
359 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
360 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
361 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
364 // data_dictionary.table_cache may not contain any data for some tables, it's just a table cache
365 // auto_increment == 0 is cast to NULL because currently (2011.03.13 GA) Drizzle doesn't provide correct value
366 $sql = "
367 SELECT t.*,
368 t.TABLE_SCHEMA AS `Db`,
369 t.TABLE_NAME AS `Name`,
370 t.TABLE_TYPE AS `TABLE_TYPE`,
371 t.ENGINE AS `Engine`,
372 t.ENGINE AS `Type`,
373 t.TABLE_VERSION AS `Version`,-- VERSION
374 t.ROW_FORMAT AS `Row_format`,
375 coalesce(tc.ROWS, stat.NUM_ROWS)
376 AS `Rows`,-- TABLE_ROWS,
377 coalesce(tc.ROWS, stat.NUM_ROWS)
378 AS `TABLE_ROWS`,
379 tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
380 tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
381 NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
382 NULL AS `Index_length`, -- INDEX_LENGTH
383 NULL AS `Data_free`, -- DATA_FREE
384 nullif(t.AUTO_INCREMENT, 0)
385 AS `Auto_increment`,
386 t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
387 t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
388 NULL AS `Check_time`, -- CHECK_TIME
389 t.TABLE_COLLATION AS `Collation`,
390 NULL AS `Checksum`, -- CHECKSUM
391 NULL AS `Create_options`, -- CREATE_OPTIONS
392 t.TABLE_COMMENT AS `Comment`
393 FROM data_dictionary.TABLES t
394 LEFT JOIN data_dictionary.TABLE_CACHE tc ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME = t.TABLE_NAME
395 $stats_join
396 WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
397 " . $sql_where_table;
398 } else {
399 $sql = '
400 SELECT *,
401 `TABLE_SCHEMA` AS `Db`,
402 `TABLE_NAME` AS `Name`,
403 `TABLE_TYPE` AS `TABLE_TYPE`,
404 `ENGINE` AS `Engine`,
405 `ENGINE` AS `Type`,
406 `VERSION` AS `Version`,
407 `ROW_FORMAT` AS `Row_format`,
408 `TABLE_ROWS` AS `Rows`,
409 `AVG_ROW_LENGTH` AS `Avg_row_length`,
410 `DATA_LENGTH` AS `Data_length`,
411 `MAX_DATA_LENGTH` AS `Max_data_length`,
412 `INDEX_LENGTH` AS `Index_length`,
413 `DATA_FREE` AS `Data_free`,
414 `AUTO_INCREMENT` AS `Auto_increment`,
415 `CREATE_TIME` AS `Create_time`,
416 `UPDATE_TIME` AS `Update_time`,
417 `CHECK_TIME` AS `Check_time`,
418 `TABLE_COLLATION` AS `Collation`,
419 `CHECKSUM` AS `Checksum`,
420 `CREATE_OPTIONS` AS `Create_options`,
421 `TABLE_COMMENT` AS `Comment`
422 FROM `information_schema`.`TABLES` t
423 WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA` IN (\'' . implode("', '", $this_databases) . '\')
424 ' . $sql_where_table;
427 // Sort the tables
428 $sql .= " ORDER BY $sort_by $sort_order";
430 if ($limit_count) {
431 $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
434 $tables = PMA_DBI_fetch_result($sql, array('TABLE_SCHEMA', 'TABLE_NAME'),
435 null, $link);
436 unset($sql_where_table, $sql);
438 if (PMA_DRIZZLE) {
439 // correct I_S and D_D names returned by D_D.TABLES - Drizzle generally uses lower case for them,
440 // but TABLES returns uppercase
441 foreach ((array)$database as $db) {
442 $db_upper = strtoupper($db);
443 if (!isset($tables[$db]) && isset($tables[$db_upper])) {
444 $tables[$db] = $tables[$db_upper];
445 unset($tables[$db_upper]);
450 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
451 // here, the array's first key is by schema name
452 foreach ($tables as $one_database_name => $one_database_tables) {
453 uksort($one_database_tables, 'strnatcasecmp');
455 if ($sort_order == 'DESC') {
456 $one_database_tables = array_reverse($one_database_tables);
458 $tables[$one_database_name] = $one_database_tables;
461 } // end (get information from table schema)
463 // If permissions are wrong on even one database directory,
464 // information_schema does not return any table info for any database
465 // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
466 if (empty($tables) && !PMA_DRIZZLE) {
467 foreach ($databases as $each_database) {
468 if ($table || (true === $tbl_is_group)) {
469 $sql = 'SHOW TABLE STATUS FROM '
470 . PMA_backquote($each_database)
471 .' LIKE \'' . PMA_escape_mysql_wildcards(PMA_sqlAddSlashes($table, true)) . '%\'';
472 } else {
473 $sql = 'SHOW TABLE STATUS FROM '
474 . PMA_backquote($each_database);
477 $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
479 // Sort naturally if the config allows it and we're sorting
480 // the Name column.
481 if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
482 uksort($each_tables, 'strnatcasecmp');
484 if ($sort_order == 'DESC') {
485 $each_tables = array_reverse($each_tables);
487 } else {
488 // Prepare to sort by creating array of the selected sort
489 // value to pass to array_multisort
491 // Size = Data_length + Index_length
492 if ($sort_by == 'Data_length') {
493 foreach ($each_tables as $table_name => $table_data) {
494 ${$sort_by}[$table_name] = strtolower($table_data['Data_length'] + $table_data['Index_length']);
496 } else {
497 foreach ($each_tables as $table_name => $table_data) {
498 ${$sort_by}[$table_name] = strtolower($table_data[$sort_by]);
502 if ($sort_order == 'DESC') {
503 array_multisort($$sort_by, SORT_DESC, $each_tables);
504 } else {
505 array_multisort($$sort_by, SORT_ASC, $each_tables);
508 // cleanup the temporary sort array
509 unset($$sort_by);
512 if ($limit_count) {
513 $each_tables = array_slice($each_tables, $limit_offset, $limit_count);
516 foreach ($each_tables as $table_name => $each_table) {
517 if ('comment' === $tbl_is_group
518 && 0 === strpos($each_table['Comment'], $table)
520 // remove table from list
521 unset($each_tables[$table_name]);
522 continue;
525 if (! isset($each_tables[$table_name]['Type'])
526 && isset($each_tables[$table_name]['Engine'])) {
527 // pma BC, same parts of PMA still uses 'Type'
528 $each_tables[$table_name]['Type']
529 =& $each_tables[$table_name]['Engine'];
530 } elseif (! isset($each_tables[$table_name]['Engine'])
531 && isset($each_tables[$table_name]['Type'])) {
532 // old MySQL reports Type, newer MySQL reports Engine
533 $each_tables[$table_name]['Engine']
534 =& $each_tables[$table_name]['Type'];
537 // MySQL forward compatibility
538 // so pma could use this array as if every server is of version >5.0
539 $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
540 $each_tables[$table_name]['TABLE_NAME'] =& $each_tables[$table_name]['Name'];
541 $each_tables[$table_name]['ENGINE'] =& $each_tables[$table_name]['Engine'];
542 $each_tables[$table_name]['VERSION'] =& $each_tables[$table_name]['Version'];
543 $each_tables[$table_name]['ROW_FORMAT'] =& $each_tables[$table_name]['Row_format'];
544 $each_tables[$table_name]['TABLE_ROWS'] =& $each_tables[$table_name]['Rows'];
545 $each_tables[$table_name]['AVG_ROW_LENGTH'] =& $each_tables[$table_name]['Avg_row_length'];
546 $each_tables[$table_name]['DATA_LENGTH'] =& $each_tables[$table_name]['Data_length'];
547 $each_tables[$table_name]['MAX_DATA_LENGTH'] =& $each_tables[$table_name]['Max_data_length'];
548 $each_tables[$table_name]['INDEX_LENGTH'] =& $each_tables[$table_name]['Index_length'];
549 $each_tables[$table_name]['DATA_FREE'] =& $each_tables[$table_name]['Data_free'];
550 $each_tables[$table_name]['AUTO_INCREMENT'] =& $each_tables[$table_name]['Auto_increment'];
551 $each_tables[$table_name]['CREATE_TIME'] =& $each_tables[$table_name]['Create_time'];
552 $each_tables[$table_name]['UPDATE_TIME'] =& $each_tables[$table_name]['Update_time'];
553 $each_tables[$table_name]['CHECK_TIME'] =& $each_tables[$table_name]['Check_time'];
554 $each_tables[$table_name]['TABLE_COLLATION'] =& $each_tables[$table_name]['Collation'];
555 $each_tables[$table_name]['CHECKSUM'] =& $each_tables[$table_name]['Checksum'];
556 $each_tables[$table_name]['CREATE_OPTIONS'] =& $each_tables[$table_name]['Create_options'];
557 $each_tables[$table_name]['TABLE_COMMENT'] =& $each_tables[$table_name]['Comment'];
559 if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
560 && $each_tables[$table_name]['Engine'] == null) {
561 $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
562 } else {
564 * @todo difference between 'TEMPORARY' and 'BASE TABLE' but how to detect?
566 $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
570 $tables[$each_database] = $each_tables;
574 // cache table data
575 // so PMA_Table does not require to issue SHOW TABLE STATUS again
576 // Note: I don't see why we would need array_merge_recursive() here,
577 // as it creates double entries for the same table (for example a double
578 // entry for Comment when changing the storage engine in Operations)
579 // Note 2: Instead of array_merge(), simply use the + operator because
580 // array_merge() renumbers numeric keys starting with 0, therefore
581 // we would lose a db name thats consists only of numbers
582 foreach ($tables as $one_database => $its_tables) {
583 if (isset(PMA_Table::$cache[$one_database])) {
584 PMA_Table::$cache[$one_database] = PMA_Table::$cache[$one_database] + $tables[$one_database];
585 } else {
586 PMA_Table::$cache[$one_database] = $tables[$one_database];
589 unset($one_database, $its_tables);
591 if (! is_array($database)) {
592 if (isset($tables[$database])) {
593 return $tables[$database];
594 } elseif (isset($tables[strtolower($database)])) {
595 // on windows with lower_case_table_names = 1
596 // MySQL returns
597 // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
598 // but information_schema.TABLES gives `test`
599 // bug #1436171
600 // http://sf.net/support/tracker.php?aid=1436171
601 return $tables[strtolower($database)];
602 } else {
603 // one database but inexact letter case match
604 // as Drizzle is always case insensitive, we can safely return the only result
605 if (PMA_DRIZZLE && count($tables) == 1) {
606 $keys = array_keys($tables);
607 if (strlen(array_pop($keys)) == strlen($database)) {
608 return array_pop($tables);
611 return $tables;
613 } else {
614 return $tables;
619 * returns array with databases containing extended infos about them
621 * @todo move into PMA_List_Database?
623 * @param string $database database
624 * @param boolean $force_stats retrieve stats also for MySQL < 5
625 * @param resource $link mysql link
626 * @param string $sort_by column to order by
627 * @param string $sort_order ASC or DESC
628 * @param integer $limit_offset starting offset for LIMIT
629 * @param bool|int $limit_count row count for LIMIT or true for $GLOBALS['cfg']['MaxDbList']
631 * @return array $databases
633 function PMA_DBI_get_databases_full($database = null, $force_stats = false,
634 $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
635 $limit_offset = 0, $limit_count = false)
637 $sort_order = strtoupper($sort_order);
639 if (true === $limit_count) {
640 $limit_count = $GLOBALS['cfg']['MaxDbList'];
643 // initialize to avoid errors when there are no databases
644 $databases = array();
646 $apply_limit_and_order_manual = true;
648 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
650 * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
651 * cause MySQL does not support natural ordering, we have to do it afterward
653 $limit = '';
654 if (!$GLOBALS['cfg']['NaturalOrder']) {
655 if ($limit_count) {
656 $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
659 $apply_limit_and_order_manual = false;
662 // get table information from information_schema
663 if ($database) {
664 $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
665 . PMA_sqlAddSlashes($database) . '\'';
666 } else {
667 $sql_where_schema = '';
670 if (PMA_DRIZZLE) {
671 // data_dictionary.table_cache may not contain any data for some
672 // tables, it's just a table cache
673 $sql = 'SELECT
674 s.SCHEMA_NAME,
675 s.DEFAULT_COLLATION_NAME';
676 if ($force_stats) {
677 // no TABLE_CACHE data, stable results are better than
678 // constantly changing
679 $sql .= ',
680 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
681 SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
683 $sql .= '
684 FROM data_dictionary.SCHEMAS s';
685 if ($force_stats) {
686 $engine_info = PMA_cacheGet('drizzle_engines', true);
687 $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
688 if (isset($engine_info['InnoDB']) && $engine_info['InnoDB']['module_library'] == 'innobase') {
689 $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat ON (t.ENGINE = 'InnoDB' AND stat.NAME = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
692 $sql .= "
693 LEFT JOIN data_dictionary.TABLES t
694 ON t.TABLE_SCHEMA = s.SCHEMA_NAME
695 $stats_join";
697 $sql .= $sql_where_schema . '
698 GROUP BY s.SCHEMA_NAME
699 ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
700 . $limit;
701 } else {
702 $sql = 'SELECT
703 s.SCHEMA_NAME,
704 s.DEFAULT_COLLATION_NAME';
705 if ($force_stats) {
706 $sql .= ',
707 COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
708 SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
709 SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
710 SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
711 SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
712 SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
713 AS SCHEMA_LENGTH,
714 SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
716 $sql .= '
717 FROM `information_schema`.SCHEMATA s';
718 if ($force_stats) {
719 $sql .= '
720 LEFT JOIN `information_schema`.TABLES t
721 ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
723 $sql .= $sql_where_schema . '
724 GROUP BY BINARY s.SCHEMA_NAME
725 ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order
726 . $limit;
729 $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
731 $mysql_error = PMA_DBI_getError($link);
732 if (! count($databases) && $GLOBALS['errno']) {
733 PMA_mysqlDie($mysql_error, $sql);
736 // display only databases also in official database list
737 // f.e. to apply hide_db and only_db
738 $drops = array_diff(array_keys($databases), (array) $GLOBALS['pma']->databases);
739 if (count($drops)) {
740 foreach ($drops as $drop) {
741 unset($databases[$drop]);
743 unset($drop);
745 unset($sql_where_schema, $sql, $drops);
746 } else {
747 foreach ($GLOBALS['pma']->databases as $database_name) {
748 // MySQL forward compatibility
749 // so pma could use this array as if every server is of version >5.0
750 $databases[$database_name]['SCHEMA_NAME'] = $database_name;
752 if ($force_stats) {
753 include_once './libraries/mysql_charsets.lib.php';
755 $databases[$database_name]['DEFAULT_COLLATION_NAME']
756 = PMA_getDbCollation($database_name);
758 // get additional info about tables
759 $databases[$database_name]['SCHEMA_TABLES'] = 0;
760 $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
761 $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
762 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
763 $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
764 $databases[$database_name]['SCHEMA_LENGTH'] = 0;
765 $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
767 $res = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($database_name) . ';');
768 while ($row = PMA_DBI_fetch_assoc($res)) {
769 $databases[$database_name]['SCHEMA_TABLES']++;
770 $databases[$database_name]['SCHEMA_TABLE_ROWS']
771 += $row['Rows'];
772 $databases[$database_name]['SCHEMA_DATA_LENGTH']
773 += $row['Data_length'];
774 $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
775 += $row['Max_data_length'];
776 $databases[$database_name]['SCHEMA_INDEX_LENGTH']
777 += $row['Index_length'];
779 // for InnoDB, this does not contain the number of
780 // overhead bytes but the total free space
781 if ('InnoDB' != $row['Engine']) {
782 $databases[$database_name]['SCHEMA_DATA_FREE']
783 += $row['Data_free'];
785 $databases[$database_name]['SCHEMA_LENGTH']
786 += $row['Data_length'] + $row['Index_length'];
788 PMA_DBI_free_result($res);
789 unset($res);
796 * apply limit and order manually now
797 * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
799 if ($apply_limit_and_order_manual) {
800 $GLOBALS['callback_sort_order'] = $sort_order;
801 $GLOBALS['callback_sort_by'] = $sort_by;
802 usort($databases, 'PMA_usort_comparison_callback');
803 unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
806 * now apply limit
808 if ($limit_count) {
809 $databases = array_slice($databases, $limit_offset, $limit_count);
813 return $databases;
817 * returns detailed array with all columns for given table in database,
818 * or all tables/databases
820 * @param string $database name of database
821 * @param string $table name of table to retrieve columns from
822 * @param string $column name of specific column
823 * @param mixed $link mysql link resource
825 * @return array
827 function PMA_DBI_get_columns_full($database = null, $table = null,
828 $column = null, $link = null)
830 $columns = array();
832 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
833 $sql_wheres = array();
834 $array_keys = array();
836 // get columns information from information_schema
837 if (null !== $database) {
838 $sql_wheres[] = '`TABLE_SCHEMA` = \'' . PMA_sqlAddSlashes($database) . '\' ';
839 } else {
840 $array_keys[] = 'TABLE_SCHEMA';
842 if (null !== $table) {
843 $sql_wheres[] = '`TABLE_NAME` = \'' . PMA_sqlAddSlashes($table) . '\' ';
844 } else {
845 $array_keys[] = 'TABLE_NAME';
847 if (null !== $column) {
848 $sql_wheres[] = '`COLUMN_NAME` = \'' . PMA_sqlAddSlashes($column) . '\' ';
849 } else {
850 $array_keys[] = 'COLUMN_NAME';
853 // for PMA bc:
854 // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
855 if (PMA_DRIZZLE) {
856 $sql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME,
857 column_name AS `Field`,
858 (CASE
859 WHEN character_maximum_length > 0
860 THEN concat(lower(data_type), '(', character_maximum_length, ')')
861 WHEN numeric_precision > 0 OR numeric_scale > 0
862 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
863 WHEN enum_values IS NOT NULL
864 THEN concat(lower(data_type), '(', enum_values, ')')
865 ELSE lower(data_type) END)
866 AS `Type`,
867 collation_name AS `Collation`,
868 (CASE is_nullable
869 WHEN 1 THEN 'YES'
870 ELSE 'NO' END) AS `Null`,
871 (CASE
872 WHEN is_used_in_primary THEN 'PRI'
873 ELSE '' END) AS `Key`,
874 column_default AS `Default`,
875 (CASE
876 WHEN is_auto_increment THEN 'auto_increment'
877 WHEN column_default_update THEN 'on update ' || column_default_update
878 ELSE '' END) AS `Extra`,
879 NULL AS `Privileges`,
880 column_comment AS `Comment`
881 FROM data_dictionary.columns";
882 } else {
883 $sql = '
884 SELECT *,
885 `COLUMN_NAME` AS `Field`,
886 `COLUMN_TYPE` AS `Type`,
887 `COLLATION_NAME` AS `Collation`,
888 `IS_NULLABLE` AS `Null`,
889 `COLUMN_KEY` AS `Key`,
890 `COLUMN_DEFAULT` AS `Default`,
891 `EXTRA` AS `Extra`,
892 `PRIVILEGES` AS `Privileges`,
893 `COLUMN_COMMENT` AS `Comment`
894 FROM `information_schema`.`COLUMNS`';
896 if (count($sql_wheres)) {
897 $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
900 $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
901 unset($sql_wheres, $sql);
902 } else {
903 if (null === $database) {
904 foreach ($GLOBALS['pma']->databases as $database) {
905 $columns[$database] = PMA_DBI_get_columns_full($database, null,
906 null, $link);
908 return $columns;
909 } elseif (null === $table) {
910 $tables = PMA_DBI_get_tables($database);
911 foreach ($tables as $table) {
912 $columns[$table] = PMA_DBI_get_columns_full(
913 $database, $table, null, $link);
915 return $columns;
918 $sql = 'SHOW FULL COLUMNS FROM '
919 . PMA_backquote($database) . '.' . PMA_backquote($table);
920 if (null !== $column) {
921 $sql .= " LIKE '" . PMA_sqlAddSlashes($column, true) . "'";
924 $columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
926 $ordinal_position = 1;
927 foreach ($columns as $column_name => $each_column) {
929 // MySQL forward compatibility
930 // so pma could use this array as if every server is of version >5.0
931 $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
932 $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
933 $columns[$column_name]['COLLATION_NAME'] =& $columns[$column_name]['Collation'];
934 $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
935 $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
936 $columns[$column_name]['COLUMN_DEFAULT'] =& $columns[$column_name]['Default'];
937 $columns[$column_name]['EXTRA'] =& $columns[$column_name]['Extra'];
938 $columns[$column_name]['PRIVILEGES'] =& $columns[$column_name]['Privileges'];
939 $columns[$column_name]['COLUMN_COMMENT'] =& $columns[$column_name]['Comment'];
941 $columns[$column_name]['TABLE_CATALOG'] = null;
942 $columns[$column_name]['TABLE_SCHEMA'] = $database;
943 $columns[$column_name]['TABLE_NAME'] = $table;
944 $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
945 $columns[$column_name]['DATA_TYPE'] =
946 substr($columns[$column_name]['COLUMN_TYPE'], 0,
947 strpos($columns[$column_name]['COLUMN_TYPE'], '('));
949 * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
951 $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
953 * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
955 $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
956 $columns[$column_name]['NUMERIC_PRECISION'] = null;
957 $columns[$column_name]['NUMERIC_SCALE'] = null;
958 $columns[$column_name]['CHARACTER_SET_NAME'] =
959 substr($columns[$column_name]['COLLATION_NAME'], 0,
960 strpos($columns[$column_name]['COLLATION_NAME'], '_'));
962 $ordinal_position++;
965 if (null !== $column) {
966 reset($columns);
967 $columns = current($columns);
970 return $columns;
974 * Returns SQL query for fetching columns for a table
976 * The 'Key' column is not calculated properly, use PMA_DBI_get_columns() to get
977 * correct values.
979 * @see PMA_DBI_get_columns()
980 * @param string $database name of database
981 * @param string $table name of table to retrieve columns from
982 * @param string $column name of column, null to show all columns
983 * @param boolean $full whether to return full info or only column names
985 * @return string
987 function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
989 if (PMA_DRIZZLE) {
990 // `Key` column:
991 // * used in primary key => PRI
992 // * unique one-column => UNI
993 // * indexed, one-column or first in multi-column => MUL
994 // Promotion of UNI to PRI in case no promary index exists is done after query is executed
995 $sql = "SELECT
996 column_name AS `Field`,
997 (CASE
998 WHEN character_maximum_length > 0
999 THEN concat(lower(data_type), '(', character_maximum_length, ')')
1000 WHEN numeric_precision > 0 OR numeric_scale > 0
1001 THEN concat(lower(data_type), '(', numeric_precision, ',', numeric_scale, ')')
1002 WHEN enum_values IS NOT NULL
1003 THEN concat(lower(data_type), '(', enum_values, ')')
1004 ELSE lower(data_type) END)
1005 AS `Type`,
1006 " . ($full ? "
1007 collation_name AS `Collation`," : '') . "
1008 (CASE is_nullable
1009 WHEN 1 THEN 'YES'
1010 ELSE 'NO' END) AS `Null`,
1011 (CASE
1012 WHEN is_used_in_primary THEN 'PRI'
1013 WHEN is_unique AND NOT is_multi THEN 'UNI'
1014 WHEN is_indexed AND (NOT is_multi OR is_first_in_multi) THEN 'MUL'
1015 ELSE '' END) AS `Key`,
1016 column_default AS `Default`,
1017 (CASE
1018 WHEN is_auto_increment THEN 'auto_increment'
1019 WHEN column_default_update <> '' THEN 'on update ' || column_default_update
1020 ELSE '' END) AS `Extra`
1021 " . ($full ? " ,
1022 NULL AS `Privileges`,
1023 column_comment AS `Comment`" : '') . "
1024 FROM data_dictionary.columns
1025 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1026 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1027 " . ($column ? "
1028 AND column_name = '" . PMA_sqlAddSlashes($column) . "'" : '');
1029 // ORDER BY ordinal_position
1030 } else {
1031 $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
1032 FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table)
1033 . ($column ? "LIKE '" . PMA_sqlAddSlashes($column, true) . "'" : '');
1035 return $sql;
1039 * Returns descriptions of columns in given table (all or given by $column)
1041 * @param string $database name of database
1042 * @param string $table name of table to retrieve columns from
1043 * @param string $column name of column, null to show all columns
1044 * @param boolean $full whether to return full info or only column names
1045 * @param mixed $link mysql link resource
1046 * @return false|array array indexed by column names or, if $column is given, flat array description
1048 function PMA_DBI_get_columns($database, $table, $column = null, $full = false, $link = null)
1050 $sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
1051 $fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
1052 if (! is_array($fields) || count($fields) == 0) {
1053 return null;
1055 if (PMA_DRIZZLE) {
1056 // fix Key column, it's much simpler in PHP than in SQL
1057 $has_pk = false;
1058 $has_pk_candidates = false;
1059 foreach ($fields as $f) {
1060 if ($f['Key'] == 'PRI') {
1061 $has_pk = true;
1062 break;
1063 } else if ($f['Null'] == 'NO' && ($f['Key'] == 'MUL' || $f['Key'] == 'UNI')) {
1064 $has_pk_candidates = true;
1067 if (!$has_pk && $has_pk_candidates) {
1068 // check whether we can promote some unique index to PRI
1069 $sql = "
1070 SELECT i.index_name, p.column_name
1071 FROM data_dictionary.indexes i
1072 JOIN data_dictionary.index_parts p USING (table_schema, table_name)
1073 WHERE i.table_schema = '" . PMA_sqlAddSlashes($database) . "'
1074 AND i.table_name = '" . PMA_sqlAddSlashes($table) . "'
1075 AND i.is_unique
1076 AND NOT i.is_nullable";
1077 $fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
1078 $fs = $fs ? array_shift($fs) : array();
1079 foreach ($fs as $f) {
1080 $fields[$f]['Key'] = 'PRI';
1085 return $column ? array_shift($fields) : $fields;
1089 * Returns SQL for fetching information on table indexes (SHOW INDEXES)
1091 * @param string $database name of database
1092 * @param string $table name of the table whose indexes are to be retreived
1093 * @param string $where additional conditions for WHERE
1094 * @return array $indexes
1096 function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
1098 if (PMA_DRIZZLE) {
1099 $sql = "SELECT
1100 ip.table_name AS `Table`,
1101 (NOT ip.is_unique) AS Non_unique,
1102 ip.index_name AS Key_name,
1103 ip.sequence_in_index+1 AS Seq_in_index,
1104 ip.column_name AS Column_name,
1105 (CASE
1106 WHEN i.index_type = 'BTREE' THEN 'A'
1107 ELSE NULL END) AS Collation,
1108 NULL AS Cardinality,
1109 compare_length AS Sub_part,
1110 NULL AS Packed,
1111 ip.is_nullable AS `Null`,
1112 i.index_type AS Index_type,
1113 NULL AS Comment,
1114 i.index_comment AS Index_comment
1115 FROM data_dictionary.index_parts ip
1116 LEFT JOIN data_dictionary.indexes i USING (table_schema, table_name, index_name)
1117 WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
1118 AND table_name = '" . PMA_sqlAddSlashes($table) . "'
1120 } else {
1121 $sql = 'SHOW INDEXES FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table);
1123 if ($where) {
1124 $sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
1126 return $sql;
1130 * Returns indexes of a table
1132 * @param string $database name of database
1133 * @param string $table name of the table whose indexes are to be retrieved
1134 * @param mixed $link mysql link resource
1135 * @return array $indexes
1137 function PMA_DBI_get_table_indexes($database, $table, $link = null)
1139 $sql = PMA_DBI_get_table_indexes_sql($database, $table);
1140 $indexes = PMA_DBI_fetch_result($sql, null, null, $link);
1142 if (! is_array($indexes) || count($indexes) < 1) {
1143 return array();
1145 return $indexes;
1149 * returns value of given mysql server variable
1151 * @param string $var mysql server variable name
1152 * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
1153 * @param mixed $link mysql link resource|object
1154 * @return mixed value for mysql server variable
1156 function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
1158 if ($link === null) {
1159 if (isset($GLOBALS['userlink'])) {
1160 $link = $GLOBALS['userlink'];
1161 } else {
1162 return false;
1166 switch ($type) {
1167 case PMA_DBI_GETVAR_SESSION:
1168 $modifier = ' SESSION';
1169 break;
1170 case PMA_DBI_GETVAR_GLOBAL:
1171 $modifier = ' GLOBAL';
1172 break;
1173 default:
1174 $modifier = '';
1176 return PMA_DBI_fetch_value(
1177 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link);
1181 * Function called just after a connection to the MySQL database server has
1182 * been established. It sets the connection collation, and determins the
1183 * version of MySQL which is running.
1185 * @param mixed $link mysql link resource|object
1186 * @param boolean $is_controluser whether link is for control user
1188 function PMA_DBI_postConnect($link, $is_controluser = false)
1190 if (! defined('PMA_MYSQL_INT_VERSION')) {
1191 if (PMA_cacheExists('PMA_MYSQL_INT_VERSION', true)) {
1192 define(
1193 'PMA_MYSQL_INT_VERSION',
1194 PMA_cacheGet('PMA_MYSQL_INT_VERSION', true)
1196 define(
1197 'PMA_MYSQL_MAJOR_VERSION',
1198 PMA_cacheGet('PMA_MYSQL_MAJOR_VERSION', true)
1200 define(
1201 'PMA_MYSQL_STR_VERSION',
1202 PMA_cacheGet('PMA_MYSQL_STR_VERSION', true)
1204 define(
1205 'PMA_MYSQL_VERSION_COMMENT',
1206 PMA_cacheGet('PMA_MYSQL_VERSION_COMMENT', true)
1208 } else {
1209 $version = PMA_DBI_fetch_single_row(
1210 'SELECT @@version, @@version_comment',
1211 'ASSOC',
1212 $link
1215 if ($version) {
1216 $match = explode('.', $version['@@version']);
1217 define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
1218 define('PMA_MYSQL_INT_VERSION',
1219 (int) sprintf('%d%02d%02d', $match[0], $match[1],
1220 intval($match[2])));
1221 define('PMA_MYSQL_STR_VERSION', $version['@@version']);
1222 define('PMA_MYSQL_VERSION_COMMENT', $version['@@version_comment']);
1223 } else {
1224 define('PMA_MYSQL_INT_VERSION', 50015);
1225 define('PMA_MYSQL_MAJOR_VERSION', 5);
1226 define('PMA_MYSQL_STR_VERSION', '5.00.15');
1227 define('PMA_MYSQL_VERSION_COMMENT', '');
1229 PMA_cacheSet(
1230 'PMA_MYSQL_INT_VERSION',
1231 PMA_MYSQL_INT_VERSION,
1232 true
1234 PMA_cacheSet(
1235 'PMA_MYSQL_MAJOR_VERSION',
1236 PMA_MYSQL_MAJOR_VERSION,
1237 true
1239 PMA_cacheSet(
1240 'PMA_MYSQL_STR_VERSION',
1241 PMA_MYSQL_STR_VERSION,
1242 true
1244 PMA_cacheSet(
1245 'PMA_MYSQL_VERSION_COMMENT',
1246 PMA_MYSQL_VERSION_COMMENT,
1247 true
1250 // detect Drizzle by version number:
1251 // <year>.<month>.<build number>(.<patch rev)
1252 define('PMA_DRIZZLE', PMA_MYSQL_MAJOR_VERSION >= 2009);
1255 // Skip charsets for Drizzle
1256 if (!PMA_DRIZZLE) {
1257 if (! empty($GLOBALS['collation_connection'])) {
1258 PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
1259 PMA_DBI_query(
1260 "SET collation_connection = '" . PMA_sqlAddSlashes($GLOBALS['collation_connection']) . "';",
1261 $link,
1262 PMA_DBI_QUERY_STORE
1264 } else {
1265 PMA_DBI_query(
1266 "SET NAMES 'utf8' COLLATE 'utf8_general_ci';",
1267 $link,
1268 PMA_DBI_QUERY_STORE
1273 // Cache plugin list for Drizzle
1274 if (PMA_DRIZZLE && !PMA_cacheExists('drizzle_engines', true)) {
1275 $sql = "SELECT p.plugin_name, m.module_library
1276 FROM data_dictionary.plugins p
1277 JOIN data_dictionary.modules m USING (module_name)
1278 WHERE p.plugin_type = 'StorageEngine'
1279 AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
1280 AND p.is_active = 'YES'";
1281 $engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
1282 PMA_cacheSet('drizzle_engines', $engines, true);
1287 * returns a single value from the given result or query,
1288 * if the query or the result has more than one row or field
1289 * the first field of the first row is returned
1291 * <code>
1292 * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
1293 * $user_name = PMA_DBI_fetch_value($sql);
1294 * // produces
1295 * // $user_name = 'John Doe'
1296 * </code>
1298 * @param string|mysql_result $result query or mysql result
1299 * @param integer $row_number row to fetch the value from,
1300 * starting at 0, with 0 beeing default
1301 * @param integer|string $field field to fetch the value from,
1302 * starting at 0, with 0 beeing default
1303 * @param resource $link mysql link
1304 * @return mixed value of first field in first row from result
1305 * or false if not found
1307 function PMA_DBI_fetch_value($result, $row_number = 0, $field = 0, $link = null)
1309 $value = false;
1311 if (is_string($result)) {
1312 $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
1315 // return false if result is empty or false
1316 // or requested row is larger than rows in result
1317 if (PMA_DBI_num_rows($result) < ($row_number + 1)) {
1318 return $value;
1321 // if $field is an integer use non associative mysql fetch function
1322 if (is_int($field)) {
1323 $fetch_function = 'PMA_DBI_fetch_row';
1324 } else {
1325 $fetch_function = 'PMA_DBI_fetch_assoc';
1328 // get requested row
1329 for ($i = 0; $i <= $row_number; $i++) {
1330 $row = $fetch_function($result);
1332 PMA_DBI_free_result($result);
1334 // return requested field
1335 if (isset($row[$field])) {
1336 $value = $row[$field];
1338 unset($row);
1340 return $value;
1344 * returns only the first row from the result
1346 * <code>
1347 * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
1348 * $user = PMA_DBI_fetch_single_row($sql);
1349 * // produces
1350 * // $user = array('id' => 123, 'name' => 'John Doe')
1351 * </code>
1353 * @param string|mysql_result $result query or mysql result
1354 * @param string $type NUM|ASSOC|BOTH
1355 * returned array should either numeric
1356 * associativ or booth
1357 * @param resource $link mysql link
1359 * @return array|boolean first row from result
1360 * or false if result is empty
1362 function PMA_DBI_fetch_single_row($result, $type = 'ASSOC', $link = null)
1364 if (is_string($result)) {
1365 $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
1368 // return null if result is empty or false
1369 if (! PMA_DBI_num_rows($result)) {
1370 return false;
1373 switch ($type) {
1374 case 'NUM' :
1375 $fetch_function = 'PMA_DBI_fetch_row';
1376 break;
1377 case 'ASSOC' :
1378 $fetch_function = 'PMA_DBI_fetch_assoc';
1379 break;
1380 case 'BOTH' :
1381 default :
1382 $fetch_function = 'PMA_DBI_fetch_array';
1383 break;
1386 $row = $fetch_function($result);
1387 PMA_DBI_free_result($result);
1388 return $row;
1392 * returns all rows in the resultset in one array
1394 * <code>
1395 * $sql = 'SELECT * FROM `user`';
1396 * $users = PMA_DBI_fetch_result($sql);
1397 * // produces
1398 * // $users[] = array('id' => 123, 'name' => 'John Doe')
1400 * $sql = 'SELECT `id`, `name` FROM `user`';
1401 * $users = PMA_DBI_fetch_result($sql, 'id');
1402 * // produces
1403 * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
1405 * $sql = 'SELECT `id`, `name` FROM `user`';
1406 * $users = PMA_DBI_fetch_result($sql, 0);
1407 * // produces
1408 * // $users['123'] = array(0 => 123, 1 => 'John Doe')
1410 * $sql = 'SELECT `id`, `name` FROM `user`';
1411 * $users = PMA_DBI_fetch_result($sql, 'id', 'name');
1412 * // or
1413 * $users = PMA_DBI_fetch_result($sql, 0, 1);
1414 * // produces
1415 * // $users['123'] = 'John Doe'
1417 * $sql = 'SELECT `name` FROM `user`';
1418 * $users = PMA_DBI_fetch_result($sql);
1419 * // produces
1420 * // $users[] = 'John Doe'
1422 * $sql = 'SELECT `group`, `name` FROM `user`'
1423 * $users = PMA_DBI_fetch_result($sql, array('group', null), 'name');
1424 * // produces
1425 * // $users['admin'][] = 'John Doe'
1427 * $sql = 'SELECT `group`, `name` FROM `user`'
1428 * $users = PMA_DBI_fetch_result($sql, array('group', 'name'), 'id');
1429 * // produces
1430 * // $users['admin']['John Doe'] = '123'
1431 * </code>
1433 * @param string|mysql_result $result query or mysql result
1434 * @param string|integer $key field-name or offset
1435 * used as key for array
1436 * @param string|integer $value value-name or offset
1437 * used as value for array
1438 * @param resource $link mysql link
1439 * @param mixed $options
1441 * @return array resultrows or values indexed by $key
1443 function PMA_DBI_fetch_result($result, $key = null, $value = null,
1444 $link = null, $options = 0)
1446 $resultrows = array();
1448 if (is_string($result)) {
1449 $result = PMA_DBI_try_query($result, $link, $options, false);
1452 // return empty array if result is empty or false
1453 if (! $result) {
1454 return $resultrows;
1457 $fetch_function = 'PMA_DBI_fetch_assoc';
1459 // no nested array if only one field is in result
1460 if (null === $key && 1 === PMA_DBI_num_fields($result)) {
1461 $value = 0;
1462 $fetch_function = 'PMA_DBI_fetch_row';
1465 // if $key is an integer use non associative mysql fetch function
1466 if (is_int($key)) {
1467 $fetch_function = 'PMA_DBI_fetch_row';
1470 if (null === $key && null === $value) {
1471 while ($row = $fetch_function($result)) {
1472 $resultrows[] = $row;
1474 } elseif (null === $key) {
1475 while ($row = $fetch_function($result)) {
1476 $resultrows[] = $row[$value];
1478 } elseif (null === $value) {
1479 if (is_array($key)) {
1480 while ($row = $fetch_function($result)) {
1481 $result_target =& $resultrows;
1482 foreach ($key as $key_index) {
1483 if (null === $key_index) {
1484 $result_target =& $result_target[];
1485 continue;
1488 if (! isset($result_target[$row[$key_index]])) {
1489 $result_target[$row[$key_index]] = array();
1491 $result_target =& $result_target[$row[$key_index]];
1493 $result_target = $row;
1495 } else {
1496 while ($row = $fetch_function($result)) {
1497 $resultrows[$row[$key]] = $row;
1500 } else {
1501 if (is_array($key)) {
1502 while ($row = $fetch_function($result)) {
1503 $result_target =& $resultrows;
1504 foreach ($key as $key_index) {
1505 if (null === $key_index) {
1506 $result_target =& $result_target[];
1507 continue;
1510 if (! isset($result_target[$row[$key_index]])) {
1511 $result_target[$row[$key_index]] = array();
1513 $result_target =& $result_target[$row[$key_index]];
1515 $result_target = $row[$value];
1517 } else {
1518 while ($row = $fetch_function($result)) {
1519 $resultrows[$row[$key]] = $row[$value];
1524 PMA_DBI_free_result($result);
1525 return $resultrows;
1529 * Get supported SQL compatibility modes
1531 * @return array supported SQL compatibility modes
1533 function PMA_DBI_getCompatibilities()
1535 // Drizzle doesn't support compatibility modes
1536 if (PMA_DRIZZLE) {
1537 return array();
1540 $compats = array('NONE');
1541 $compats[] = 'ANSI';
1542 $compats[] = 'DB2';
1543 $compats[] = 'MAXDB';
1544 $compats[] = 'MYSQL323';
1545 $compats[] = 'MYSQL40';
1546 $compats[] = 'MSSQL';
1547 $compats[] = 'ORACLE';
1548 // removed; in MySQL 5.0.33, this produces exports that
1549 // can't be read by POSTGRESQL (see our bug #1596328)
1550 //$compats[] = 'POSTGRESQL';
1551 $compats[] = 'TRADITIONAL';
1553 return $compats;
1557 * returns warnings for last query
1559 * @param resource $link mysql link resource
1561 * @return array warnings
1563 function PMA_DBI_get_warnings($link = null)
1565 if (empty($link)) {
1566 if (isset($GLOBALS['userlink'])) {
1567 $link = $GLOBALS['userlink'];
1568 } else {
1569 return array();
1573 return PMA_DBI_fetch_result('SHOW WARNINGS', null, null, $link);
1577 * returns true (int > 0) if current user is superuser
1578 * otherwise 0
1580 * @return bool Whether use is a superuser
1582 function PMA_isSuperuser()
1584 if (PMA_cacheExists('is_superuser', true)) {
1585 return PMA_cacheGet('is_superuser', true);
1588 // when connection failed we don't have a $userlink
1589 if (isset($GLOBALS['userlink'])) {
1590 if (PMA_DRIZZLE) {
1591 // Drizzle has no authorization by default, so when no plugin is
1592 // enabled everyone is a superuser
1593 // Known authorization libraries: regex_policy, simple_user_policy
1594 // Plugins limit object visibility (dbs, tables, processes), we can
1595 // safely assume we always deal with superuser
1596 $r = true;
1597 } else {
1598 // check access to mysql.user table
1599 $r = (bool) PMA_DBI_try_query(
1600 'SELECT COUNT(*) FROM mysql.user',
1601 $GLOBALS['userlink'],
1602 PMA_DBI_QUERY_STORE
1605 PMA_cacheSet('is_superuser', $r, true);
1606 } else {
1607 PMA_cacheSet('is_superuser', false, true);
1610 return PMA_cacheGet('is_superuser', true);
1614 * returns an array of PROCEDURE or FUNCTION names for a db
1616 * @param string $db db name
1617 * @param string $which PROCEDURE | FUNCTION
1618 * @param resource $link mysql link
1620 * @returnarray the procedure names or function names
1622 function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
1624 if (PMA_DRIZZLE) {
1625 // Drizzle doesn't support functions and procedures
1626 return array();
1628 $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
1629 $result = array();
1630 foreach ($shows as $one_show) {
1631 if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
1632 $result[] = $one_show['Name'];
1635 return($result);
1639 * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
1641 * @param string $db db name
1642 * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
1643 * @param string $name the procedure|function|event|view name
1644 * @param resource $link mysql link
1646 * @return string the definition
1648 function PMA_DBI_get_definition($db, $which, $name, $link = null)
1650 $returned_field = array(
1651 'PROCEDURE' => 'Create Procedure',
1652 'FUNCTION' => 'Create Function',
1653 'EVENT' => 'Create Event',
1654 'VIEW' => 'Create View'
1656 $query = 'SHOW CREATE ' . $which . ' '
1657 . PMA_backquote($db) . '.' . PMA_backquote($name);
1658 return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
1662 * returns details about the TRIGGERs for a specific table or database
1664 * @param string $db db name
1665 * @param string $table table name
1666 * @param string $delimiter the delimiter to use (may be empty)
1668 * @return array information about triggers (may be empty)
1670 function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
1672 if (PMA_DRIZZLE) {
1673 // Drizzle doesn't support triggers
1674 return array();
1677 $result = array();
1678 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1679 // Note: in http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html
1680 // their example uses WHERE TRIGGER_SCHEMA='dbname' so let's use this
1681 // instead of WHERE EVENT_OBJECT_SCHEMA='dbname'
1682 $query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
1683 . ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
1684 . ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
1685 . ' FROM information_schema.TRIGGERS'
1686 . ' WHERE TRIGGER_SCHEMA= \'' . PMA_sqlAddSlashes($db) . '\'';
1688 if (! empty($table)) {
1689 $query .= " AND EVENT_OBJECT_TABLE = '" . PMA_sqlAddSlashes($table) . "';";
1691 } else {
1692 $query = "SHOW TRIGGERS FROM " . PMA_backquote($db);
1693 if (! empty($table)) {
1694 $query .= " LIKE '" . PMA_sqlAddSlashes($table, true) . "';";
1698 if ($triggers = PMA_DBI_fetch_result($query)) {
1699 foreach ($triggers as $trigger) {
1700 if ($GLOBALS['cfg']['Server']['DisableIS']) {
1701 $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
1702 $trigger['ACTION_TIMING'] = $trigger['Timing'];
1703 $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
1704 $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
1705 $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
1706 $trigger['DEFINER'] = $trigger['Definer'];
1708 $one_result = array();
1709 $one_result['name'] = $trigger['TRIGGER_NAME'];
1710 $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
1711 $one_result['action_timing'] = $trigger['ACTION_TIMING'];
1712 $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
1713 $one_result['definition'] = $trigger['ACTION_STATEMENT'];
1714 $one_result['definer'] = $trigger['DEFINER'];
1716 // do not prepend the schema name; this way, importing the
1717 // definition into another schema will work
1718 $one_result['full_trigger_name'] = PMA_backquote($trigger['TRIGGER_NAME']);
1719 $one_result['drop'] = 'DROP TRIGGER IF EXISTS '
1720 . $one_result['full_trigger_name'];
1721 $one_result['create'] = 'CREATE TRIGGER '
1722 . $one_result['full_trigger_name'] . ' '
1723 . $trigger['ACTION_TIMING']. ' '
1724 . $trigger['EVENT_MANIPULATION']
1725 . ' ON ' . PMA_backquote($trigger['EVENT_OBJECT_TABLE'])
1726 . "\n" . ' FOR EACH ROW '
1727 . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
1729 $result[] = $one_result;
1733 // Sort results by name
1734 $name = array();
1735 foreach ($result as $key => $value) {
1736 $name[] = $value['name'];
1738 array_multisort($name, SORT_ASC, $result);
1740 return($result);
1744 * Formats database error message in a friendly way.
1745 * This is needed because some errors messages cannot
1746 * be obtained by mysql_error().
1748 * @param int $error_number Error code
1749 * @param string $error_message Error message as returned by server
1751 * @return string HML text with error details
1753 function PMA_DBI_formatError($error_number, $error_message)
1755 if (! empty($error_message)) {
1756 $error_message = PMA_DBI_convert_message($error_message);
1759 $error_message = htmlspecialchars($error_message);
1761 $error = '#' . ((string) $error_number);
1763 if ($error_number == 2002) {
1764 $error .= ' - ' . $error_message;
1765 $error .= '<br />' . __('The server is not responding (or the local server\'s socket is not correctly configured).');
1766 } elseif ($error_number == 2003) {
1767 $error .= ' - ' . $error_message;
1768 $error .= '<br />' . __('The server is not responding.');
1769 } elseif ($error_number == 1005) {
1770 if (strpos($error_message, 'errno: 13') !== false) {
1771 $error .= ' - ' . $error_message;
1772 $error .= '<br />' . __('Please check privileges of directory containing database.');
1773 } else {
1774 /* InnoDB contraints, see
1775 * http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
1777 $error .= ' - ' . $error_message .
1778 ' (<a href="server_engines.php' .
1779 PMA_generate_common_url(array('engine' => 'InnoDB', 'page' => 'Status')) .
1780 '">' . __('Details...') . '</a>)';
1782 } else {
1783 $error .= ' - ' . $error_message;
1786 return $error;
1790 * Checks whether given schema is a system schema: information_schema
1791 * (MySQL and Drizzle) or data_dictionary (Drizzle)
1793 * @param string $schema_name Name of schema (database) to test
1794 * @param bool $test_for_mysql_schema Whether 'mysql' schema should
1795 * be treated the same as IS and DD
1796 * @return bool
1798 function PMA_is_system_schema($schema_name, $test_for_mysql_schema = false)
1800 return strtolower($schema_name) == 'information_schema'
1801 || (PMA_DRIZZLE && strtolower($schema_name) == 'data_dictionary')
1802 || ($test_for_mysql_schema && !PMA_DRIZZLE && $schema_name == 'mysql');