2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Holds the PMA_Table class
8 if (! defined('PHPMYADMIN')) {
13 * Handles everything related to tables
15 * @todo make use of PMA_Message and PMA_Error
21 * UI preferences properties
23 const PROP_SORTED_COLUMN
= 'sorted_col';
24 const PROP_COLUMN_ORDER
= 'col_order';
25 const PROP_COLUMN_VISIB
= 'col_visib';
27 static $cache = array();
30 * @var string table name
35 * @var string database name
40 * @var string engine (innodb, myisam, bdb, ...)
45 * @var string type (view, base table, system view)
52 var $settings = array();
55 * @var array UI preferences
60 * @var array errors occurred
62 var $errors = array();
67 var $messages = array();
72 * @param string $table_name table name
73 * @param string $db_name database name
75 function __construct($table_name, $db_name)
77 $this->setName($table_name);
78 $this->setDbName($db_name);
84 * @see PMA_Table::getName()
85 * @return string table name
89 return $this->getName();
93 * return the last error
95 * @return the last error
97 function getLastError()
99 return end($this->errors
);
103 * return the last message
105 * @return the last message
107 function getLastMessage()
109 return end($this->messages
);
115 * @param string $table_name new table name
119 function setName($table_name)
121 $this->name
= $table_name;
127 * @param boolean $backquoted whether to quote name with backticks ``
129 * @return string table name
131 function getName($backquoted = false)
134 return PMA_Util
::backquote($this->name
);
140 * sets database name for this table
142 * @param string $db_name database name
146 function setDbName($db_name)
148 $this->db_name
= $db_name;
152 * returns database name for this table
154 * @param boolean $backquoted whether to quote name with backticks ``
156 * @return string database name for this table
158 function getDbName($backquoted = false)
161 return PMA_Util
::backquote($this->db_name
);
163 return $this->db_name
;
167 * returns full name for table, including database name
169 * @param boolean $backquoted whether to quote name with backticks ``
173 function getFullName($backquoted = false)
175 return $this->getDbName($backquoted) . '.'
176 . $this->getName($backquoted);
180 * returns whether the table is actually a view
182 * @param string $db database
183 * @param string $table table
185 * @return whether the given is a view
187 static public function isView($db = null, $table = null)
189 if (empty($db) ||
empty($table)) {
193 // use cached data or load information with SHOW command
194 if (isset(PMA_Table
::$cache[$db][$table])
195 ||
$GLOBALS['cfg']['Server']['DisableIS']
197 $type = PMA_Table
::sGetStatusInfo($db, $table, 'TABLE_TYPE');
198 return $type == 'VIEW';
201 // query information_schema
202 $result = $GLOBALS['dbi']->fetchResult(
204 FROM information_schema.VIEWS
205 WHERE TABLE_SCHEMA = '" . PMA_Util
::sqlAddSlashes($db) . "'
206 AND TABLE_NAME = '" . PMA_Util
::sqlAddSlashes($table) . "'"
208 return $result ?
true : false;
212 * Returns whether the table is actually an updatable view
214 * @param string $db database
215 * @param string $table table
217 * @return boolean whether the given is an updatable view
219 static public function isUpdatableView($db = null, $table = null)
221 if (empty($db) ||
empty($table)) {
225 $result = $GLOBALS['dbi']->fetchResult(
227 FROM information_schema.VIEWS
228 WHERE TABLE_SCHEMA = '" . PMA_Util
::sqlAddSlashes($db) . "'
229 AND TABLE_NAME = '" . PMA_Util
::sqlAddSlashes($table) . "'
230 AND IS_UPDATABLE = 'YES'"
232 return $result ?
true : false;
236 * Returns the analysis of 'SHOW CREATE TABLE' query for the table.
237 * In case of a view, the values are taken from the information_schema.
239 * @param string $db database
240 * @param string $table table
242 * @return array analysis of 'SHOW CREATE TABLE' query for the table
244 static public function analyzeStructure($db = null, $table = null)
246 if (empty($db) ||
empty($table)) {
250 $analyzed_sql = array();
251 if (self
::isView($db, $table)) {
252 // For a view, 'SHOW CREATE TABLE' returns the definition,
253 // but the structure of the view. So, we try to mock
254 // the result of analyzing 'SHOW CREATE TABLE' query.
255 $analyzed_sql[0] = array();
256 $analyzed_sql[0]['create_table_fields'] = array();
258 $results = $GLOBALS['dbi']->fetchResult(
259 "SELECT COLUMN_NAME, DATA_TYPE
260 FROM information_schema.COLUMNS
261 WHERE TABLE_SCHEMA = '" . PMA_Util
::sqlAddSlashes($db) . "'
262 AND TABLE_NAME = '" . PMA_Util
::sqlAddSlashes($table) . "'"
264 foreach ($results as $result) {
265 $analyzed_sql[0]['create_table_fields'][$result['COLUMN_NAME']]
266 = array('type' => strtoupper($result['DATA_TYPE']));
269 $show_create_table = $GLOBALS['dbi']->fetchValue(
271 . PMA_Util
::backquote($db)
272 . '.' . PMA_Util
::backquote($table),
276 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
278 return $analyzed_sql;
282 * sets given $value for given $param
284 * @param string $param name
285 * @param mixed $value value
289 function set($param, $value)
291 $this->settings
[$param] = $value;
295 * returns value for given setting/param
297 * @param string $param name for value to return
299 * @return mixed value for $param
303 if (isset($this->settings
[$param])) {
304 return $this->settings
[$param];
311 * Checks if this is a merge table
313 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias),
314 * this is a merge table.
316 * @param string $db the database name
317 * @param string $table the table name
319 * @return boolean true if it is a merge table
321 static public function isMerge($db = null, $table = null)
324 // if called static, with parameters
325 if (! empty($db) && ! empty($table)) {
326 $engine = PMA_Table
::sGetStatusInfo(
327 $db, $table, 'ENGINE', null, true
331 // did we get engine?
332 if (empty($engine)) {
336 // any of known merge engines?
337 return in_array(strtoupper($engine), array('MERGE', 'MRG_MYISAM'));
341 * Returns tooltip for the table
342 * Format : <table_comment> (<number_of_rows>)
344 * @param string $db database name
345 * @param string $table table name
347 * @return string tooltip fot the table
349 static public function sGetToolTip($db, $table)
351 return PMA_Table
::sGetStatusInfo($db, $table, 'Comment')
352 . ' (' . PMA_Table
::countRecords($db, $table)
353 . ' ' . __('Rows') . ')';
357 * Returns full table status info, or specific if $info provided
358 * this info is collected from information_schema
360 * @param string $db database name
361 * @param string $table table name
362 * @param string $info specific information to be fetched
363 * @param boolean $force_read read new rather than serving from cache
364 * @param boolean $disable_error if true, disables error message
366 * @todo DatabaseInterface::getTablesFull needs to be merged
367 * somehow into this class or at least better documented
371 static public function sGetStatusInfo($db, $table, $info = null,
372 $force_read = false, $disable_error = false
374 if (! empty($_SESSION['is_multi_query'])) {
375 $disable_error = true;
378 if (! isset(PMA_Table
::$cache[$db][$table]) ||
$force_read) {
379 $GLOBALS['dbi']->getTablesFull($db, $table);
382 if (! isset(PMA_Table
::$cache[$db][$table])) {
383 // happens when we enter the table creation dialog
384 // or when we really did not get any status info, for example
385 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
389 if (null === $info) {
390 return PMA_Table
::$cache[$db][$table];
393 // array_key_exists allows for null values
394 if (!array_key_exists($info, PMA_Table
::$cache[$db][$table])) {
395 if (! $disable_error) {
397 __('unknown table status: ') . $info,
404 return PMA_Table
::$cache[$db][$table][$info];
408 * generates column specification for ALTER or CREATE TABLE syntax
410 * @param string $name name
411 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
412 * @param string $index index
413 * @param string $length length ('2', '5,2', '', ...)
414 * @param string $attribute attribute
415 * @param string $collation collation
416 * @param bool|string $null with 'NULL' or 'NOT NULL'
417 * @param string $default_type whether default is CURRENT_TIMESTAMP,
418 * NULL, NONE, USER_DEFINED
419 * @param string $default_value default value for USER_DEFINED
421 * @param string $extra 'AUTO_INCREMENT'
422 * @param string $comment field comment
423 * @param array &$field_primary list of fields for PRIMARY KEY
424 * @param string $move_to new position for column
426 * @todo move into class PMA_Column
427 * @todo on the interface, some js to clear the default value when the
428 * default current_timestamp is checked
430 * @return string field specification
432 static function generateFieldSpec($name, $type, $index, $length = '',
433 $attribute = '', $collation = '', $null = false,
434 $default_type = 'USER_DEFINED', $default_value = '', $extra = '',
435 $comment = '', &$field_primary = null, $move_to = ''
437 $is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
439 $query = PMA_Util
::backquote($name) . ' ' . $type;
443 '@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|'
444 . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN|UUID)$@i',
448 $query .= '(' . $length . ')';
451 if ($attribute != '') {
452 $query .= ' ' . $attribute;
455 $matches = preg_match(
456 '@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i',
459 if (! empty($collation) && $collation != 'NULL' && $matches) {
460 $query .= PMA_generateCharsetQueryPart($collation);
463 if ($null !== false) {
464 if ($null == 'NULL') {
467 $query .= ' NOT NULL';
471 switch ($default_type) {
472 case 'USER_DEFINED' :
473 if ($is_timestamp && $default_value === '0') {
474 // a TIMESTAMP does not accept DEFAULT '0'
475 // but DEFAULT 0 works
476 $query .= ' DEFAULT 0';
477 } elseif ($type == 'BIT') {
478 $query .= ' DEFAULT b\''
479 . preg_replace('/[^01]/', '0', $default_value)
481 } elseif ($type == 'BOOLEAN') {
482 if (preg_match('/^1|T|TRUE|YES$/i', $default_value)) {
483 $query .= ' DEFAULT TRUE';
484 } elseif (preg_match('/^0|F|FALSE|NO$/i', $default_value)) {
485 $query .= ' DEFAULT FALSE';
487 // Invalid BOOLEAN value
488 $query .= ' DEFAULT \''
489 . PMA_Util
::sqlAddSlashes($default_value) . '\'';
492 $query .= ' DEFAULT \''
493 . PMA_Util
::sqlAddSlashes($default_value) . '\'';
497 //If user uncheck null checkbox and not change default value null,
498 //default value will be ignored.
499 if ($null !== false && $null != 'NULL') {
502 case 'CURRENT_TIMESTAMP' :
503 $query .= ' DEFAULT ' . $default_type;
510 if (!empty($extra)) {
511 $query .= ' ' . $extra;
512 // Force an auto_increment field to be part of the primary key
513 // even if user did not tick the PK box;
514 if ($extra == 'AUTO_INCREMENT') {
515 $primary_cnt = count($field_primary);
516 if (1 == $primary_cnt) {
517 for ($j = 0; $j < $primary_cnt; $j++
) {
518 if ($field_primary[$j] == $index) {
522 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
523 $query .= ' PRIMARY KEY';
524 unset($field_primary[$j]);
527 // but the PK could contain other columns so do not append
528 // a PRIMARY KEY clause, just add a member to $field_primary
529 $found_in_pk = false;
530 for ($j = 0; $j < $primary_cnt; $j++
) {
531 if ($field_primary[$j] == $index) {
536 if (! $found_in_pk) {
537 $field_primary[] = $index;
540 } // end if (auto_increment)
542 if (!empty($comment)) {
543 $query .= " COMMENT '" . PMA_Util
::sqlAddSlashes($comment) . "'";
547 if ($move_to == '-first') { // dash can't appear as part of column name
549 } elseif ($move_to != '') {
550 $query .= ' AFTER ' . PMA_Util
::backquote($move_to);
556 * Counts and returns (or displays) the number of records in a table
558 * @param string $db the current database name
559 * @param string $table the current table name
560 * @param bool $force_exact whether to force an exact count
561 * @param bool $is_view whether the table is a view
563 * @return mixed the number of records if "retain" param is true,
566 static public function countRecords($db, $table, $force_exact = false,
569 if (isset(PMA_Table
::$cache[$db][$table]['ExactRows'])) {
570 $row_count = PMA_Table
::$cache[$db][$table]['ExactRows'];
574 if (null === $is_view) {
575 $is_view = PMA_Table
::isView($db, $table);
578 if (! $force_exact) {
579 if (! isset(PMA_Table
::$cache[$db][$table]['Rows']) && ! $is_view) {
580 $tmp_tables = $GLOBALS['dbi']->getTablesFull($db, $table);
581 if (isset($tmp_tables[$table])) {
582 PMA_Table
::$cache[$db][$table] = $tmp_tables[$table];
585 if (isset(PMA_Table
::$cache[$db][$table]['Rows'])) {
586 $row_count = PMA_Table
::$cache[$db][$table]['Rows'];
592 // for a VIEW, $row_count is always false at this point
593 if (false === $row_count
594 ||
$row_count < $GLOBALS['cfg']['MaxExactCount']
596 // Make an exception for views in I_S and D_D schema in
597 // Drizzle, as these map to in-memory data and should execute
600 ||
(PMA_DRIZZLE
&& $GLOBALS['dbi']->isSystemSchema($db))
602 $row_count = $GLOBALS['dbi']->fetchValue(
603 'SELECT COUNT(*) FROM ' . PMA_Util
::backquote($db) . '.'
604 . PMA_Util
::backquote($table)
607 // For complex views, even trying to get a partial record
608 // count could bring down a server, so we offer an
609 // alternative: setting MaxExactCountViews to 0 will bypass
610 // completely the record counting for views
612 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
615 // Counting all rows of a VIEW could be too long,
616 // so use a LIMIT clause.
617 // Use try_query because it can fail (when a VIEW is
618 // based on a table that no longer exists)
619 $result = $GLOBALS['dbi']->tryQuery(
620 'SELECT 1 FROM ' . PMA_Util
::backquote($db) . '.'
621 . PMA_Util
::backquote($table) . ' LIMIT '
622 . $GLOBALS['cfg']['MaxExactCountViews'],
624 PMA_DatabaseInterface
::QUERY_STORE
626 if (!$GLOBALS['dbi']->getError()) {
627 $row_count = $GLOBALS['dbi']->numRows($result);
628 $GLOBALS['dbi']->freeResult($result);
633 PMA_Table
::$cache[$db][$table]['ExactRows'] = $row_count;
639 } // end of the 'PMA_Table::countRecords()' function
642 * Generates column specification for ALTER syntax
644 * @param string $oldcol old column name
645 * @param string $newcol new column name
646 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
647 * @param string $length length ('2', '5,2', '', ...)
648 * @param string $attribute attribute
649 * @param string $collation collation
650 * @param bool|string $null with 'NULL' or 'NOT NULL'
651 * @param string $default_type whether default is CURRENT_TIMESTAMP,
652 * NULL, NONE, USER_DEFINED
653 * @param string $default_value default value for USER_DEFINED default
655 * @param string $extra 'AUTO_INCREMENT'
656 * @param string $comment field comment
657 * @param array &$field_primary list of fields for PRIMARY KEY
658 * @param string $index index
659 * @param string $move_to new position for column
661 * @see PMA_Table::generateFieldSpec()
663 * @return string field specification
665 static public function generateAlter($oldcol, $newcol, $type, $length,
666 $attribute, $collation, $null, $default_type, $default_value,
667 $extra, $comment, &$field_primary, $index, $move_to
669 return PMA_Util
::backquote($oldcol) . ' '
670 . PMA_Table
::generateFieldSpec(
671 $newcol, $type, $index, $length, $attribute,
672 $collation, $null, $default_type, $default_value, $extra,
673 $comment, $field_primary, $move_to
678 * Inserts existing entries in a PMA_* table by reading a value from an old
681 * @param string $work The array index, which Relation feature to
682 * check ('relwork', 'commwork', ...)
683 * @param string $pma_table The array index, which PMA-table to update
684 * ('bookmark', 'relation', ...)
685 * @param array $get_fields Which fields will be SELECT'ed from the old entry
686 * @param array $where_fields Which fields will be used for the WHERE query
687 * (array('FIELDNAME' => 'FIELDVALUE'))
688 * @param array $new_fields Which fields will be used as new VALUES.
689 * These are the important keys which differ
691 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
693 * @global relation variable
697 static public function duplicateInfo($work, $pma_table, $get_fields,
698 $where_fields, $new_fields
702 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
703 $select_parts = array();
704 $row_fields = array();
705 foreach ($get_fields as $get_field) {
706 $select_parts[] = PMA_Util
::backquote($get_field);
707 $row_fields[$get_field] = 'cc';
710 $where_parts = array();
711 foreach ($where_fields as $_where => $_value) {
712 $where_parts[] = PMA_Util
::backquote($_where) . ' = \''
713 . PMA_Util
::sqlAddSlashes($_value) . '\'';
716 $new_parts = array();
717 $new_value_parts = array();
718 foreach ($new_fields as $_where => $_value) {
719 $new_parts[] = PMA_Util
::backquote($_where);
720 $new_value_parts[] = PMA_Util
::sqlAddSlashes($_value);
723 $table_copy_query = '
724 SELECT ' . implode(', ', $select_parts) . '
725 FROM ' . PMA_Util
::backquote($GLOBALS['cfgRelation']['db']) . '.'
726 . PMA_Util
::backquote($GLOBALS['cfgRelation'][$pma_table]) . '
727 WHERE ' . implode(' AND ', $where_parts);
729 // must use PMA_DatabaseInterface::QUERY_STORE here, since we execute
730 // another query inside the loop
731 $table_copy_rs = PMA_queryAsControlUser(
732 $table_copy_query, true, PMA_DatabaseInterface
::QUERY_STORE
735 while ($table_copy_row = @$GLOBALS['dbi']->fetchAssoc($table_copy_rs)) {
736 $value_parts = array();
737 foreach ($table_copy_row as $_key => $_val) {
738 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
739 $value_parts[] = PMA_Util
::sqlAddSlashes($_val);
743 $new_table_query = 'INSERT IGNORE INTO '
744 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
746 . PMA_Util
::backquote($GLOBALS['cfgRelation'][$pma_table])
747 . ' (' . implode(', ', $select_parts)
748 . ', ' . implode(', ', $new_parts)
750 . implode('\', \'', $value_parts) . '\', \''
751 . implode('\', \'', $new_value_parts) . '\')';
753 PMA_queryAsControlUser($new_table_query);
754 $last_id = $GLOBALS['dbi']->insertId();
757 $GLOBALS['dbi']->freeResult($table_copy_rs);
763 } // end of 'PMA_Table::duplicateInfo()' function
766 * Copies or renames table
768 * @param string $source_db source database
769 * @param string $source_table source table
770 * @param string $target_db target database
771 * @param string $target_table target table
772 * @param string $what what to be moved or copied (data, dataonly)
773 * @param bool $move whether to move
774 * @param string $mode mode
776 * @return bool true if success, false otherwise
778 static public function moveCopy($source_db, $source_table, $target_db,
779 $target_table, $what, $move, $mode
783 /* Try moving table directly */
784 if ($move && $what == 'data') {
785 $tbl = new PMA_Table($source_table, $source_db);
786 $result = $tbl->rename($target_table, $target_db);
788 $GLOBALS['message'] = $tbl->getLastMessage();
793 // set export settings we need
794 $GLOBALS['sql_backquotes'] = 1;
795 $GLOBALS['asfile'] = 1;
797 // Ensure the target is valid
798 if (! $GLOBALS['pma']->databases
->exists($source_db, $target_db)) {
799 if (! $GLOBALS['pma']->databases
->exists($source_db)) {
800 $GLOBALS['message'] = PMA_Message
::rawError(
802 __('Source database `%s` was not found!'),
803 htmlspecialchars($source_db)
807 if (! $GLOBALS['pma']->databases
->exists($target_db)) {
808 $GLOBALS['message'] = PMA_Message
::rawError(
810 __('Target database `%s` was not found!'),
811 htmlspecialchars($target_db)
818 $source = PMA_Util
::backquote($source_db)
819 . '.' . PMA_Util
::backquote($source_table);
820 if (! isset($target_db) ||
! strlen($target_db)) {
821 $target_db = $source_db;
824 // Doing a select_db could avoid some problems with replicated databases,
825 // when moving table from replicated one to not replicated one
826 $GLOBALS['dbi']->selectDb($target_db);
828 $target = PMA_Util
::backquote($target_db)
829 . '.' . PMA_Util
::backquote($target_table);
831 // do not create the table if dataonly
832 if ($what != 'dataonly') {
833 include_once "libraries/plugin_interface.lib.php";
834 // get Export SQL instance
835 $export_sql_plugin = PMA_getPlugin(
838 'libraries/plugins/export/',
840 'export_type' => 'table',
841 'single_table' => false,
845 $no_constraints_comments = true;
846 $GLOBALS['sql_constraints_query'] = '';
847 // set the value of global sql_auto_increment variable
848 if (isset($_POST['sql_auto_increment'])) {
849 $GLOBALS['sql_auto_increment'] = $_POST['sql_auto_increment'];
852 $sql_structure = $export_sql_plugin->getTableDef(
853 $source_db, $source_table, "\n", $err_url, false, false
855 unset($no_constraints_comments);
856 $parsed_sql = PMA_SQP_parse($sql_structure);
857 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
859 if (empty($analyzed_sql[0]['create_table_fields'])) {
860 // this is not a CREATE TABLE, so find the first VIEW
861 $target_for_view = PMA_Util
::backquote($target_db);
863 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord'
864 && $parsed_sql[$i]['data'] == 'VIEW'
871 unset($analyzed_sql);
873 $table_delimiter = 'quote_backtick';
875 $server_sql_mode = $GLOBALS['dbi']->fetchValue(
876 "SHOW VARIABLES LIKE 'sql_mode'",
880 // ANSI_QUOTES might be a subset of sql_mode, for example
881 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
882 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
883 $table_delimiter = 'quote_double';
885 $table_delimiter = 'quote_backtick';
887 unset($server_sql_mode);
890 /* Find table name in query and replace it */
891 while ($parsed_sql[$i]['type'] != $table_delimiter) {
895 /* no need to backquote() */
896 if (isset($target_for_view)) {
897 // this a view definition; we just found the first db name
898 // that follows DEFINER VIEW
899 // so change it for the new db name
900 $parsed_sql[$i]['data'] = $target_for_view;
901 // then we have to find all references to the source db
902 // and change them to the target db, ensuring we stay into
903 // the $parsed_sql limits
904 $last = $parsed_sql['len'] - 1;
905 $backquoted_source_db = PMA_Util
::backquote($source_db);
906 for (++
$i; $i <= $last; $i++
) {
907 if ($parsed_sql[$i]['type'] == $table_delimiter
908 && $parsed_sql[$i]['data'] == $backquoted_source_db
909 && $parsed_sql[$i - 1]['type'] != 'punct_qualifier'
911 $parsed_sql[$i]['data'] = $target_for_view;
914 unset($last,$backquoted_source_db);
916 $parsed_sql[$i]['data'] = $target;
919 /* Generate query back */
920 $sql_structure = PMA_SQP_format($parsed_sql, 'query_only');
921 // If table exists, and 'add drop table' is selected: Drop it!
923 if (isset($_REQUEST['drop_if_exists'])
924 && $_REQUEST['drop_if_exists'] == 'true'
926 if (PMA_Table
::isView($target_db, $target_table)) {
927 $drop_query = 'DROP VIEW';
929 $drop_query = 'DROP TABLE';
931 $drop_query .= ' IF EXISTS '
932 . PMA_Util
::backquote($target_db) . '.'
933 . PMA_Util
::backquote($target_table);
934 $GLOBALS['dbi']->query($drop_query);
936 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
938 // If an existing table gets deleted, maintain any
939 // entries for the PMA_* tables
940 $maintain_relations = true;
943 @$GLOBALS['dbi']->query($sql_structure);
944 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
946 if (($move ||
isset($GLOBALS['add_constraints']))
947 && !empty($GLOBALS['sql_constraints_query'])
949 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
952 // find the first $table_delimiter, it must be the source
954 while ($parsed_sql[$i]['type'] != $table_delimiter) {
956 // maybe someday we should guard against going over limit
957 //if ($i == $parsed_sql['len']) {
962 // replace it by the target table name, no need
964 $parsed_sql[$i]['data'] = $target;
966 // now we must remove all $table_delimiter that follow a
967 // CONSTRAINT keyword, because a constraint name must be
970 $cnt = $parsed_sql['len'] - 1;
972 for ($j = $i; $j < $cnt; $j++
) {
973 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
974 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT'
976 if ($parsed_sql[$j+
1]['type'] == $table_delimiter) {
977 $parsed_sql[$j+
1]['data'] = '';
982 // Generate query back
983 $GLOBALS['sql_constraints_query'] = PMA_SQP_format(
984 $parsed_sql, 'query_only'
986 if ($mode == 'one_table') {
987 $GLOBALS['dbi']->query($GLOBALS['sql_constraints_query']);
989 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
990 if ($mode == 'one_table') {
991 unset($GLOBALS['sql_constraints_query']);
995 $GLOBALS['sql_query'] = '';
998 // Copy the data unless this is a VIEW
999 if (($what == 'data' ||
$what == 'dataonly')
1000 && ! PMA_Table
::isView($target_db, $target_table)
1002 $sql_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
1003 $GLOBALS['dbi']->query($sql_set_mode);
1004 $GLOBALS['sql_query'] .= "\n\n" . $sql_set_mode . ';';
1006 $sql_insert_data = 'INSERT INTO ' . $target
1007 . ' SELECT * FROM ' . $source;
1008 $GLOBALS['dbi']->query($sql_insert_data);
1009 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
1012 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1014 // Drops old table if the user has requested to move it
1017 // This could avoid some problems with replicated databases, when
1018 // moving table from replicated one to not replicated one
1019 $GLOBALS['dbi']->selectDb($source_db);
1021 if (PMA_Table
::isView($source_db, $source_table)) {
1022 $sql_drop_query = 'DROP VIEW';
1024 $sql_drop_query = 'DROP TABLE';
1026 $sql_drop_query .= ' ' . $source;
1027 $GLOBALS['dbi']->query($sql_drop_query);
1029 // Renable table in configuration storage
1030 PMA_REL_renameTable(
1031 $source_db, $target_db,
1032 $source_table, $target_table
1035 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
1039 // Create new entries as duplicates from old PMA DBs
1040 if ($what != 'dataonly' && ! isset($maintain_relations)) {
1041 if ($GLOBALS['cfgRelation']['commwork']) {
1042 // Get all comments and MIME-Types for current table
1043 $comments_copy_rs = PMA_queryAsControlUser(
1044 'SELECT column_name, comment'
1045 . ($GLOBALS['cfgRelation']['mimework']
1046 ?
', mimetype, transformation, transformation_options'
1049 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
1051 . PMA_Util
::backquote($GLOBALS['cfgRelation']['column_info'])
1054 . PMA_Util
::sqlAddSlashes($source_db) . '\''
1056 . ' table_name = \''
1057 . PMA_Util
::sqlAddSlashes($source_table) . '\''
1060 // Write every comment as new copied entry. [MIME]
1061 while ($comments_copy_row = $GLOBALS['dbi']->fetchAssoc($comments_copy_rs)) {
1062 $new_comment_query = 'REPLACE INTO ' . PMA_Util
::backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_Util
::backquote($GLOBALS['cfgRelation']['column_info'])
1063 . ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ?
', mimetype, transformation, transformation_options' : '') . ') '
1065 . '\'' . PMA_Util
::sqlAddSlashes($target_db) . '\','
1066 . '\'' . PMA_Util
::sqlAddSlashes($target_table) . '\','
1067 . '\'' . PMA_Util
::sqlAddSlashes($comments_copy_row['column_name']) . '\''
1068 . ($GLOBALS['cfgRelation']['mimework'] ?
',\'' . PMA_Util
::sqlAddSlashes($comments_copy_row['comment']) . '\','
1069 . '\'' . PMA_Util
::sqlAddSlashes($comments_copy_row['mimetype']) . '\','
1070 . '\'' . PMA_Util
::sqlAddSlashes($comments_copy_row['transformation']) . '\','
1071 . '\'' . PMA_Util
::sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
1073 PMA_queryAsControlUser($new_comment_query);
1075 $GLOBALS['dbi']->freeResult($comments_copy_rs);
1076 unset($comments_copy_rs);
1079 // duplicating the bookmarks must not be done here, but
1082 $get_fields = array('display_field');
1083 $where_fields = array(
1084 'db_name' => $source_db,
1085 'table_name' => $source_table
1087 $new_fields = array(
1088 'db_name' => $target_db,
1089 'table_name' => $target_table
1091 PMA_Table
::duplicateInfo(
1101 * @todo revise this code when we support cross-db relations
1103 $get_fields = array(
1108 $where_fields = array(
1109 'master_db' => $source_db,
1110 'master_table' => $source_table
1112 $new_fields = array(
1113 'master_db' => $target_db,
1114 'foreign_db' => $target_db,
1115 'master_table' => $target_table
1117 PMA_Table
::duplicateInfo(
1126 $get_fields = array(
1131 $where_fields = array(
1132 'foreign_db' => $source_db,
1133 'foreign_table' => $source_table
1135 $new_fields = array(
1136 'master_db' => $target_db,
1137 'foreign_db' => $target_db,
1138 'foreign_table' => $target_table
1140 PMA_Table
::duplicateInfo(
1149 $get_fields = array('x', 'y', 'v', 'h');
1150 $where_fields = array(
1151 'db_name' => $source_db,
1152 'table_name' => $source_table
1154 $new_fields = array(
1155 'db_name' => $target_db,
1156 'table_name' => $target_table
1158 PMA_Table
::duplicateInfo(
1167 * @todo Can't get duplicating PDFs the right way. The
1168 * page numbers always get screwed up independently from
1169 * duplication because the numbers do not seem to be stored on a
1170 * per-database basis. Would the author of pdf support please
1171 * have a look at it?
1173 $get_fields = array('page_descr');
1174 $where_fields = array('db_name' => $source_db);
1175 $new_fields = array('db_name' => $target_db);
1176 $last_id = PMA_Table::duplicateInfo(
1184 if (isset($last_id) && $last_id >= 0) {
1185 $get_fields = array('x', 'y');
1186 $where_fields = array(
1187 'db_name' => $source_db,
1188 'table_name' => $source_table
1190 $new_fields = array(
1191 'db_name' => $target_db,
1192 'table_name' => $target_table,
1193 'pdf_page_number' => $last_id
1195 PMA_Table::duplicateInfo(
1210 * checks if given name is a valid table name,
1211 * currently if not empty, trailing spaces, '.', '/' and '\'
1213 * @param string $table_name name to check
1215 * @todo add check for valid chars in filename on current system/os
1216 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1218 * @return boolean whether the string is valid or not
1220 static function isValidName($table_name)
1222 if ($table_name !== trim($table_name)) {
1227 if (! strlen($table_name)) {
1232 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1233 // illegal char . / \
1243 * @param string $new_name new table name
1244 * @param string $new_db new database name
1246 * @return bool success
1248 function rename($new_name, $new_db = null)
1250 if (null !== $new_db && $new_db !== $this->getDbName()) {
1251 // Ensure the target is valid
1252 if (! $GLOBALS['pma']->databases
->exists($new_db)) {
1253 $this->errors
[] = __('Invalid database:') . ' ' . $new_db;
1257 $new_db = $this->getDbName();
1260 $new_table = new PMA_Table($new_name, $new_db);
1262 if ($this->getFullName() === $new_table->getFullName()) {
1266 if (! PMA_Table
::isValidName($new_name)) {
1267 $this->errors
[] = __('Invalid table name:') . ' '
1268 . $new_table->getFullName();
1272 // If the table is moved to a different database drop its triggers first
1273 $triggers = $GLOBALS['dbi']->getTriggers(
1274 $this->getDbName(), $this->getName(), ''
1276 $handle_triggers = $this->getDbName() != $new_db && $triggers;
1277 if ($handle_triggers) {
1278 foreach ($triggers as $trigger) {
1279 $sql = 'DROP TRIGGER IF EXISTS '
1280 . PMA_Util
::backquote($this->getDbName())
1281 . '.' . PMA_Util
::backquote($trigger['name']) . ';';
1282 $GLOBALS['dbi']->query($sql);
1287 * tested also for a view, in MySQL 5.0.92, 5.1.55 and 5.5.13
1289 $GLOBALS['sql_query'] = '
1290 RENAME TABLE ' . $this->getFullName(true) . '
1291 TO ' . $new_table->getFullName(true) . ';';
1292 // I don't think a specific error message for views is necessary
1293 if (! $GLOBALS['dbi']->query($GLOBALS['sql_query'])) {
1294 // Restore triggers in the old database
1295 if ($handle_triggers) {
1296 $GLOBALS['dbi']->selectDb($this->getDbName());
1297 foreach ($triggers as $trigger) {
1298 $GLOBALS['dbi']->query($trigger['create']);
1301 $this->errors
[] = sprintf(
1302 __('Error renaming table %1$s to %2$s'),
1303 $this->getFullName(),
1304 $new_table->getFullName()
1309 $old_name = $this->getName();
1310 $old_db = $this->getDbName();
1311 $this->setName($new_name);
1312 $this->setDbName($new_db);
1314 // Renable table in configuration storage
1315 PMA_REL_renameTable(
1317 $old_name, $new_name
1320 $this->messages
[] = sprintf(
1321 __('Table %1$s has been renamed to %2$s.'),
1322 htmlspecialchars($old_name),
1323 htmlspecialchars($new_name)
1329 * Get all unique columns
1331 * returns an array with all columns with unqiue content, in fact these are
1332 * all columns being single indexed in PRIMARY or UNIQUE
1335 * - PRIMARY(id) // id
1336 * - UNIQUE(name) // name
1337 * - PRIMARY(fk_id1, fk_id2) // NONE
1338 * - UNIQUE(x,y) // NONE
1340 * @param bool $backquoted whether to quote name with backticks ``
1341 * @param bool $fullName whether to include full name of the table as a prefix
1345 public function getUniqueColumns($backquoted = true, $fullName = true)
1347 $sql = $GLOBALS['dbi']->getTableIndexesSql(
1352 $uniques = $GLOBALS['dbi']->fetchResult(
1354 array('Key_name', null),
1359 foreach ($uniques as $index) {
1360 if (count($index) > 1) {
1363 $return[] = ($fullName ?
$this->getFullName($backquoted) . '.' : '')
1364 . ($backquoted ? PMA_Util
::backquote($index[0]) : $index[0]);
1371 * Get all indexed columns
1373 * returns an array with all columns make use of an index, in fact only
1374 * first columns in an index
1376 * e.g. index(col1, col2) would only return col1
1378 * @param bool $backquoted whether to quote name with backticks ``
1382 public function getIndexedColumns($backquoted = true)
1384 $sql = $GLOBALS['dbi']->getTableIndexesSql(
1389 $indexed = $GLOBALS['dbi']->fetchResult($sql, 'Column_name', 'Column_name');
1392 foreach ($indexed as $column) {
1393 $return[] = $this->getFullName($backquoted) . '.'
1394 . ($backquoted ? PMA_Util
::backquote($column) : $column);
1403 * returns an array with all columns
1405 * @param bool $backquoted whether to quote name with backticks ``
1409 public function getColumns($backquoted = true)
1411 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1412 $indexed = $GLOBALS['dbi']->fetchResult($sql, 'Field', 'Field');
1415 foreach ($indexed as $column) {
1416 $return[] = $this->getFullName($backquoted) . '.'
1417 . ($backquoted ? PMA_Util
::backquote($column) : $column);
1424 * Return UI preferences for this table from phpMyAdmin database.
1428 protected function getUiPrefsFromDb()
1430 $pma_table = PMA_Util
::backquote($GLOBALS['cfg']['Server']['pmadb']) ."."
1431 . PMA_Util
::backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1433 // Read from phpMyAdmin database
1434 $sql_query = " SELECT `prefs` FROM " . $pma_table
1435 . " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'"
1436 . " AND `db_name` = '" . PMA_Util
::sqlAddSlashes($this->db_name
) . "'"
1437 . " AND `table_name` = '" . PMA_Util
::sqlAddSlashes($this->name
) . "'";
1439 $row = $GLOBALS['dbi']->fetchArray(PMA_queryAsControlUser($sql_query));
1440 if (isset($row[0])) {
1441 return json_decode($row[0], true);
1448 * Save this table's UI preferences into phpMyAdmin database.
1450 * @return true|PMA_Message
1452 protected function saveUiPrefsToDb()
1454 $pma_table = PMA_Util
::backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
1455 . PMA_Util
::backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1457 $username = $GLOBALS['cfg']['Server']['user'];
1458 $sql_query = " REPLACE INTO " . $pma_table
1459 . " VALUES ('" . $username . "', '" . PMA_Util
::sqlAddSlashes($this->db_name
)
1460 . "', '" . PMA_Util
::sqlAddSlashes($this->name
) . "', '"
1461 . PMA_Util
::sqlAddSlashes(json_encode($this->uiprefs
)) . "', NULL)";
1463 $success = $GLOBALS['dbi']->tryQuery($sql_query, $GLOBALS['controllink']);
1466 $message = PMA_Message
::error(
1467 __('Could not save table UI preferences')
1469 $message->addMessage('<br /><br />');
1470 $message->addMessage(
1471 PMA_Message
::rawError(
1472 $GLOBALS['dbi']->getError($GLOBALS['controllink'])
1478 // Remove some old rows in table_uiprefs if it exceeds the configured
1480 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1481 $rows_count = $GLOBALS['dbi']->fetchValue($sql_query);
1482 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1483 if ($rows_count > $max_rows) {
1484 $num_rows_to_delete = $rows_count - $max_rows;
1486 = ' DELETE FROM ' . $pma_table .
1487 ' ORDER BY last_update ASC' .
1488 ' LIMIT ' . $num_rows_to_delete;
1489 $success = $GLOBALS['dbi']->tryQuery(
1490 $sql_query, $GLOBALS['controllink']
1494 $message = PMA_Message
::error(
1496 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1497 PMA_Util
::showDocu('config', 'cfg_Servers_MaxTableUiprefs')
1500 $message->addMessage('<br /><br />');
1501 $message->addMessage(
1502 PMA_Message
::rawError(
1503 $GLOBALS['dbi']->getError($GLOBALS['controllink'])
1515 * Loads the UI preferences for this table.
1516 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1517 * phpMyAdmin database.
1521 protected function loadUiPrefs()
1523 $server_id = $GLOBALS['server'];
1524 // set session variable if it's still undefined
1525 if (! isset($_SESSION['tmpval']['table_uiprefs'][$server_id][$this->db_name
][$this->name
])) {
1526 // check whether we can get from pmadb
1527 $_SESSION['tmpval']['table_uiprefs'][$server_id][$this->db_name
][$this->name
]
1528 = (strlen($GLOBALS['cfg']['Server']['pmadb'])
1529 && strlen($GLOBALS['cfg']['Server']['table_uiprefs']))
1530 ?
$this->getUiPrefsFromDb()
1533 $this->uiprefs
=& $_SESSION['tmpval']['table_uiprefs'][$server_id]
1534 [$this->db_name
][$this->name
];
1538 * Get a property from UI preferences.
1539 * Return false if the property is not found.
1540 * Available property:
1541 * - PROP_SORTED_COLUMN
1542 * - PROP_COLUMN_ORDER
1543 * - PROP_COLUMN_VISIB
1545 * @param string $property property
1549 public function getUiProp($property)
1551 if (! isset($this->uiprefs
)) {
1552 $this->loadUiPrefs();
1554 // do checking based on property
1555 if ($property == self
::PROP_SORTED_COLUMN
) {
1556 if (isset($this->uiprefs
[$property])) {
1557 // check if the column name is exist in this table
1558 $tmp = explode(' ', $this->uiprefs
[$property]);
1560 $avail_columns = $this->getColumns();
1561 foreach ($avail_columns as $each_col) {
1562 // check if $each_col ends with $colname
1566 strlen($each_col) - strlen($colname)
1568 return $this->uiprefs
[$property];
1571 // remove the property, since it is not exist anymore in database
1572 $this->removeUiProp(self
::PROP_SORTED_COLUMN
);
1577 } elseif ($property == self
::PROP_COLUMN_ORDER
1578 ||
$property == self
::PROP_COLUMN_VISIB
1580 if (! PMA_Table
::isView($this->db_name
, $this->name
)
1581 && isset($this->uiprefs
[$property])
1583 // check if the table has not been modified
1584 if (self
::sGetStatusInfo(
1586 $this->name
, 'Create_time'
1587 ) == $this->uiprefs
['CREATE_TIME']) {
1588 return $this->uiprefs
[$property];
1590 // remove the property, since the table has been modified
1591 $this->removeUiProp(self
::PROP_COLUMN_ORDER
);
1598 // default behaviour for other property:
1599 return isset($this->uiprefs
[$property]) ?
$this->uiprefs
[$property] : false;
1603 * Set a property from UI preferences.
1604 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1605 * phpMyAdmin database.
1606 * Available property:
1607 * - PROP_SORTED_COLUMN
1608 * - PROP_COLUMN_ORDER
1609 * - PROP_COLUMN_VISIB
1611 * @param string $property Property
1612 * @param mixed $value Value for the property
1613 * @param string $table_create_time Needed for PROP_COLUMN_ORDER
1614 * and PROP_COLUMN_VISIB
1616 * @return boolean|PMA_Message
1618 public function setUiProp($property, $value, $table_create_time = null)
1620 if (! isset($this->uiprefs
)) {
1621 $this->loadUiPrefs();
1623 // we want to save the create time if the property is PROP_COLUMN_ORDER
1624 if (! PMA_Table
::isView($this->db_name
, $this->name
)
1625 && ($property == self
::PROP_COLUMN_ORDER
1626 ||
$property == self
::PROP_COLUMN_VISIB
)
1628 $curr_create_time = self
::sGetStatusInfo(
1633 if (isset($table_create_time)
1634 && $table_create_time == $curr_create_time
1636 $this->uiprefs
['CREATE_TIME'] = $curr_create_time;
1638 // there is no $table_create_time, or
1639 // supplied $table_create_time is older than current create time,
1641 return PMA_Message
::error(
1643 __('Cannot save UI property "%s". The changes made will not be persistent after you refresh this page. Please check if the table structure has been changed.'),
1650 $this->uiprefs
[$property] = $value;
1651 // check if pmadb is set
1652 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1653 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1655 return $this->saveUiprefsToDb();
1661 * Remove a property from UI preferences.
1663 * @param string $property the property
1665 * @return true|PMA_Message
1667 public function removeUiProp($property)
1669 if (! isset($this->uiprefs
)) {
1670 $this->loadUiPrefs();
1672 if (isset($this->uiprefs
[$property])) {
1673 unset($this->uiprefs
[$property]);
1674 // check if pmadb is set
1675 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1676 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1678 return $this->saveUiprefsToDb();
1685 * Get all column names which are MySQL reserved words
1690 public function getReservedColumnNames()
1692 $columns = $this->getColumns(false);
1694 foreach ($columns as $column) {
1695 $temp = explode('.', $column);
1696 $column_name = $temp[2];
1697 if (PMA_SQP_isKeyWord($column_name)) {
1698 $return[] = $column_name;