Translated using Weblate.
[phpmyadmin.git] / libraries / Table.class.php
blob7793347f9603960bc01bb15ff4352566fdc1d7b2
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
5 * @package PhpMyAdmin
6 */
8 /**
9 * @todo make use of PMA_Message and PMA_Error
10 * @package PhpMyAdmin
12 class PMA_Table
14 /**
15 * UI preferences properties
17 const PROP_SORTED_COLUMN = 'sorted_col';
18 const PROP_COLUMN_ORDER = 'col_order';
19 const PROP_COLUMN_VISIB = 'col_visib';
21 static $cache = array();
23 /**
24 * @var string table name
26 var $name = '';
28 /**
29 * @var string database name
31 var $db_name = '';
33 /**
34 * @var string engine (innodb, myisam, bdb, ...)
36 var $engine = '';
38 /**
39 * @var string type (view, base table, system view)
41 var $type = '';
43 /**
44 * @var array settings
46 var $settings = array();
48 /**
49 * @var array UI preferences
51 var $uiprefs;
53 /**
54 * @var array errors occured
56 var $errors = array();
58 /**
59 * @var array messages
61 var $messages = array();
63 /**
64 * Constructor
66 * @param string $table_name table name
67 * @param string $db_name database name
69 function __construct($table_name, $db_name)
71 $this->setName($table_name);
72 $this->setDbName($db_name);
75 /**
76 * returns table name
78 * @see PMA_Table::getName()
79 * @return string table name
81 function __toString()
83 return $this->getName();
86 /**
87 * return the last error
89 * @return the last error
91 function getLastError()
93 return end($this->errors);
96 /**
97 * return the last message
99 * @return the last message
101 function getLastMessage()
103 return end($this->messages);
107 * sets table name
109 * @param string $table_name new table name
111 * @return nothing
113 function setName($table_name)
115 $this->name = $table_name;
119 * returns table name
121 * @param boolean $backquoted whether to quote name with backticks ``
123 * @return string table name
125 function getName($backquoted = false)
127 if ($backquoted) {
128 return PMA_backquote($this->name);
130 return $this->name;
134 * sets database name for this table
136 * @param string $db_name database name
138 * @return nothing
140 function setDbName($db_name)
142 $this->db_name = $db_name;
146 * returns database name for this table
148 * @param boolean $backquoted whether to quote name with backticks ``
150 * @return string database name for this table
152 function getDbName($backquoted = false)
154 if ($backquoted) {
155 return PMA_backquote($this->db_name);
157 return $this->db_name;
161 * returns full name for table, including database name
163 * @param boolean $backquoted whether to quote name with backticks ``
165 * @return string
167 function getFullName($backquoted = false)
169 return $this->getDbName($backquoted) . '.' . $this->getName($backquoted);
173 * returns whether the table is actually a view
175 * @param string $db database
176 * @param string $table table
178 * @return whether the given is a view
180 static public function isView($db = null, $table = null)
182 if (empty($db) || empty($table)) {
183 return false;
186 // use cached data or load information with SHOW command
187 if (isset(PMA_Table::$cache[$db][$table]) || $GLOBALS['cfg']['Server']['DisableIS']) {
188 $type = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_TYPE');
189 return $type == 'VIEW';
192 // query information_schema
193 $result = PMA_DBI_fetch_result(
194 "SELECT TABLE_NAME
195 FROM information_schema.VIEWS
196 WHERE TABLE_SCHEMA = '" . PMA_sqlAddSlashes($db) . "'
197 AND TABLE_NAME = '" . PMA_sqlAddSlashes($table) . "'");
198 return $result ? true : false;
202 * sets given $value for given $param
204 * @param string $param name
205 * @param mixed $value value
207 * @return nothing
209 function set($param, $value)
211 $this->settings[$param] = $value;
215 * returns value for given setting/param
217 * @param string $param name for value to return
219 * @return mixed value for $param
221 function get($param)
223 if (isset($this->settings[$param])) {
224 return $this->settings[$param];
227 return null;
231 * loads structure data
232 * (this function is work in progress? not yet used)
234 * @return boolean
236 function loadStructure()
238 $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
240 if (false === $table_info) {
241 return false;
244 $this->settings = $table_info;
246 if ($this->get('TABLE_ROWS') === null) {
247 $this->set(
248 'TABLE_ROWS',
249 PMA_Table::countRecords($this->getDbName(), $this->getName(), true)
253 $create_options = explode(' ', $this->get('TABLE_ROWS'));
255 // export create options by its name as variables into gloabel namespace
256 // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
257 foreach ($create_options as $each_create_option) {
258 $each_create_option = explode('=', $each_create_option);
259 if (isset($each_create_option[1])) {
260 $this->set($$each_create_option[0], $each_create_option[1]);
263 return true;
267 * Checks if this is a merge table
269 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias),
270 * this is a merge table.
272 * @param string $db the database name
273 * @param string $table the table name
275 * @return boolean true if it is a merge table
277 static public function isMerge($db = null, $table = null)
279 $engine = null;
280 // if called static, with parameters
281 if (! empty($db) && ! empty($table)) {
282 $engine = PMA_Table::sGetStatusInfo($db, $table, 'ENGINE', null, true);
285 return (! empty($engine) && ((strtoupper($engine) == 'MERGE') || (strtoupper($engine) == 'MRG_MYISAM')));
288 static public function sGetToolTip($db, $table)
290 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
291 . ' (' . PMA_Table::countRecords($db, $table) . ')';
295 * Returns full table status info, or specific if $info provided
296 * this info is collected from information_schema
298 * @param string $db database name
299 * @param string $table table name
300 * @param string $info
301 * @param boolean $force_read read new rather than serving from cache
302 * @param boolean $disable_error if true, disables error message
304 * @todo PMA_DBI_get_tables_full needs to be merged somehow into this class
305 * or at least better documented
307 * @return mixed
309 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false, $disable_error = false)
311 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
312 PMA_DBI_get_tables_full($db, $table);
315 if (! isset(PMA_Table::$cache[$db][$table])) {
316 // happens when we enter the table creation dialog
317 // or when we really did not get any status info, for example
318 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
319 return '';
322 if (null === $info) {
323 return PMA_Table::$cache[$db][$table];
326 // array_key_exists allows for null values
327 if (!array_key_exists($info, PMA_Table::$cache[$db][$table])) {
328 if (! $disable_error) {
329 trigger_error(__('unknown table status: ') . $info, E_USER_WARNING);
331 return false;
334 return PMA_Table::$cache[$db][$table][$info];
338 * generates column specification for ALTER or CREATE TABLE syntax
340 * @param string $name name
341 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
342 * @param string $length length ('2', '5,2', '', ...)
343 * @param string $attribute attribute
344 * @param string $collation collation
345 * @param bool|string $null with 'NULL' or 'NOT NULL'
346 * @param string $default_type whether default is CURRENT_TIMESTAMP,
347 * NULL, NONE, USER_DEFINED
348 * @param string $default_value default value for USER_DEFINED default type
349 * @param string $extra 'AUTO_INCREMENT'
350 * @param string $comment field comment
351 * @param array &$field_primary list of fields for PRIMARY KEY
352 * @param string $index
354 * @todo move into class PMA_Column
355 * @todo on the interface, some js to clear the default value when the default
356 * current_timestamp is checked
358 * @return string field specification
360 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
361 $collation = '', $null = false, $default_type = 'USER_DEFINED',
362 $default_value = '', $extra = '', $comment = '',
363 &$field_primary, $index)
366 $is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
368 $query = PMA_backquote($name) . ' ' . $type;
370 if ($length != ''
371 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|'
372 . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN|UUID)$@i', $type)) {
373 $query .= '(' . $length . ')';
376 if ($attribute != '') {
377 $query .= ' ' . $attribute;
380 if (! empty($collation) && $collation != 'NULL'
381 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)
383 $query .= PMA_generateCharsetQueryPart($collation);
386 if ($null !== false) {
387 if ($null == 'NULL') {
388 $query .= ' NULL';
389 } else {
390 $query .= ' NOT NULL';
394 switch ($default_type) {
395 case 'USER_DEFINED' :
396 if ($is_timestamp && $default_value === '0') {
397 // a TIMESTAMP does not accept DEFAULT '0'
398 // but DEFAULT 0 works
399 $query .= ' DEFAULT 0';
400 } elseif ($type == 'BIT') {
401 $query .= ' DEFAULT b\''
402 . preg_replace('/[^01]/', '0', $default_value)
403 . '\'';
404 } elseif ($type == 'BOOLEAN') {
405 if (preg_match('/^1|T|TRUE|YES$/i', $default_value)) {
406 $query .= ' DEFAULT TRUE';
407 } elseif (preg_match('/^0|F|FALSE|NO$/i', $default_value)) {
408 $query .= ' DEFAULT FALSE';
409 } else {
410 // Invalid BOOLEAN value
411 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
413 } else {
414 $query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
416 break;
417 case 'NULL' :
418 case 'CURRENT_TIMESTAMP' :
419 $query .= ' DEFAULT ' . $default_type;
420 break;
421 case 'NONE' :
422 default :
423 break;
426 if (!empty($extra)) {
427 $query .= ' ' . $extra;
428 // Force an auto_increment field to be part of the primary key
429 // even if user did not tick the PK box;
430 if ($extra == 'AUTO_INCREMENT') {
431 $primary_cnt = count($field_primary);
432 if (1 == $primary_cnt) {
433 for ($j = 0; $j < $primary_cnt; $j++) {
434 if ($field_primary[$j] == $index) {
435 break;
438 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
439 $query .= ' PRIMARY KEY';
440 unset($field_primary[$j]);
442 } else {
443 // but the PK could contain other columns so do not append
444 // a PRIMARY KEY clause, just add a member to $field_primary
445 $found_in_pk = false;
446 for ($j = 0; $j < $primary_cnt; $j++) {
447 if ($field_primary[$j] == $index) {
448 $found_in_pk = true;
449 break;
451 } // end for
452 if (! $found_in_pk) {
453 $field_primary[] = $index;
456 } // end if (auto_increment)
458 if (!empty($comment)) {
459 $query .= " COMMENT '" . PMA_sqlAddSlashes($comment) . "'";
461 return $query;
462 } // end function
465 * Counts and returns (or displays) the number of records in a table
467 * Revision 13 July 2001: Patch for limiting dump size from
468 * vinay@sanisoft.com & girish@sanisoft.com
470 * @param string $db the current database name
471 * @param string $table the current table name
472 * @param bool $force_exact whether to force an exact count
473 * @param bool $is_view whether the table is a view
475 * @return mixed the number of records if "retain" param is true,
476 * otherwise true
478 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
480 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
481 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
482 } else {
483 $row_count = false;
485 if (null === $is_view) {
486 $is_view = PMA_Table::isView($db, $table);
489 if (! $force_exact) {
490 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
491 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
492 if (isset($tmp_tables[$table])) {
493 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
496 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
497 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
498 } else {
499 $row_count = false;
503 // for a VIEW, $row_count is always false at this point
504 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
505 // Make an exception for views in I_S and D_D schema in Drizzle, as these map to
506 // in-memory data and should execute fast enough
507 if (! $is_view || (PMA_DRIZZLE && PMA_is_system_schema($db))) {
508 $row_count = PMA_DBI_fetch_value(
509 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
510 . PMA_backquote($table)
512 } else {
513 // For complex views, even trying to get a partial record
514 // count could bring down a server, so we offer an
515 // alternative: setting MaxExactCountViews to 0 will bypass
516 // completely the record counting for views
518 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
519 $row_count = 0;
520 } else {
521 // Counting all rows of a VIEW could be too long, so use
522 // a LIMIT clause.
523 // Use try_query because it can fail (when a VIEW is
524 // based on a table that no longer exists)
525 $result = PMA_DBI_try_query(
526 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
527 . PMA_backquote($table) . ' LIMIT '
528 . $GLOBALS['cfg']['MaxExactCountViews'],
529 null,
530 PMA_DBI_QUERY_STORE
532 if (!PMA_DBI_getError()) {
533 $row_count = PMA_DBI_num_rows($result);
534 PMA_DBI_free_result($result);
538 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
542 return $row_count;
543 } // end of the 'PMA_Table::countRecords()' function
546 * Generates column specification for ALTER syntax
548 * @param string $oldcol old column name
549 * @param string $newcol new column name
550 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
551 * @param string $length length ('2', '5,2', '', ...)
552 * @param string $attribute attribute
553 * @param string $collation collation
554 * @param bool|string $null with 'NULL' or 'NOT NULL'
555 * @param string $default_type whether default is CURRENT_TIMESTAMP,
556 * NULL, NONE, USER_DEFINED
557 * @param string $default_value default value for USER_DEFINED default type
558 * @param string $extra 'AUTO_INCREMENT'
559 * @param string $comment field comment
560 * @param array &$field_primary list of fields for PRIMARY KEY
561 * @param string $index
562 * @param mixed $default_orig
564 * @see PMA_Table::generateFieldSpec()
566 * @return string field specification
568 static public function generateAlter($oldcol, $newcol, $type, $length,
569 $attribute, $collation, $null, $default_type, $default_value,
570 $extra, $comment = '', &$field_primary, $index, $default_orig)
572 return PMA_backquote($oldcol) . ' '
573 . PMA_Table::generateFieldSpec(
574 $newcol, $type, $length, $attribute,
575 $collation, $null, $default_type, $default_value, $extra,
576 $comment, $field_primary, $index, $default_orig
578 } // end function
581 * Inserts existing entries in a PMA_* table by reading a value from an old entry
583 * @param string $work The array index, which Relation feature to check
584 * ('relwork', 'commwork', ...)
585 * @param string $pma_table The array index, which PMA-table to update
586 * ('bookmark', 'relation', ...)
587 * @param array $get_fields Which fields will be SELECT'ed from the old entry
588 * @param array $where_fields Which fields will be used for the WHERE query
589 * (array('FIELDNAME' => 'FIELDVALUE'))
590 * @param array $new_fields Which fields will be used as new VALUES. These are
591 * the important keys which differ from the old entry
592 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
594 * @global relation variable
596 * @return int|true
598 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields, $new_fields)
600 $last_id = -1;
602 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
603 $select_parts = array();
604 $row_fields = array();
605 foreach ($get_fields as $get_field) {
606 $select_parts[] = PMA_backquote($get_field);
607 $row_fields[$get_field] = 'cc';
610 $where_parts = array();
611 foreach ($where_fields as $_where => $_value) {
612 $where_parts[] = PMA_backquote($_where) . ' = \''
613 . PMA_sqlAddSlashes($_value) . '\'';
616 $new_parts = array();
617 $new_value_parts = array();
618 foreach ($new_fields as $_where => $_value) {
619 $new_parts[] = PMA_backquote($_where);
620 $new_value_parts[] = PMA_sqlAddSlashes($_value);
623 $table_copy_query = '
624 SELECT ' . implode(', ', $select_parts) . '
625 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
626 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
627 WHERE ' . implode(' AND ', $where_parts);
629 // must use PMA_DBI_QUERY_STORE here, since we execute another
630 // query inside the loop
631 $table_copy_rs = PMA_query_as_controluser(
632 $table_copy_query, true, PMA_DBI_QUERY_STORE
635 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
636 $value_parts = array();
637 foreach ($table_copy_row as $_key => $_val) {
638 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
639 $value_parts[] = PMA_sqlAddSlashes($_val);
643 $new_table_query = 'INSERT IGNORE INTO '
644 . PMA_backquote($GLOBALS['cfgRelation']['db'])
645 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
646 (' . implode(', ', $select_parts) . ',
647 ' . implode(', ', $new_parts) . ')
648 VALUES
649 (\'' . implode('\', \'', $value_parts) . '\',
650 \'' . implode('\', \'', $new_value_parts) . '\')';
652 PMA_query_as_controluser($new_table_query);
653 $last_id = PMA_DBI_insert_id();
654 } // end while
656 PMA_DBI_free_result($table_copy_rs);
658 return $last_id;
661 return true;
662 } // end of 'PMA_Table::duplicateInfo()' function
666 * Copies or renames table
668 * @param string $source_db source database
669 * @param string $source_table source table
670 * @param string $target_db target database
671 * @param string $target_table target table
672 * @param string $what what to be moved or copied (data, dataonly)
673 * @param bool $move whether to move
674 * @param string $mode mode
676 * @return bool true if success, false otherwise
678 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
680 global $err_url;
682 /* Try moving table directly */
683 if ($move && $what == 'data') {
684 $tbl = new PMA_Table($source_table, $source_db);
685 $result = $tbl->rename(
686 $target_table, $target_db,
687 PMA_Table::isView($source_db, $source_table)
689 if ($result) {
690 $GLOBALS['message'] = $tbl->getLastMessage();
691 return true;
695 // set export settings we need
696 $GLOBALS['sql_backquotes'] = 1;
697 $GLOBALS['asfile'] = 1;
699 // Ensure the target is valid
700 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
701 if (! $GLOBALS['pma']->databases->exists($source_db)) {
702 $GLOBALS['message'] = PMA_Message::rawError(
703 'source database `' . htmlspecialchars($source_db) . '` not found'
706 if (! $GLOBALS['pma']->databases->exists($target_db)) {
707 $GLOBALS['message'] = PMA_Message::rawError(
708 'target database `' . htmlspecialchars($target_db) . '` not found'
711 return false;
714 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
715 if (! isset($target_db) || ! strlen($target_db)) {
716 $target_db = $source_db;
719 // Doing a select_db could avoid some problems with replicated databases,
720 // when moving table from replicated one to not replicated one
721 PMA_DBI_select_db($target_db);
723 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
725 // do not create the table if dataonly
726 if ($what != 'dataonly') {
727 include_once './libraries/export/sql.php';
729 $no_constraints_comments = true;
730 $GLOBALS['sql_constraints_query'] = '';
732 $sql_structure = PMA_getTableDef(
733 $source_db, $source_table, "\n", $err_url, false, false
735 unset($no_constraints_comments);
736 $parsed_sql = PMA_SQP_parse($sql_structure);
737 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
738 $i = 0;
739 if (empty($analyzed_sql[0]['create_table_fields'])) {
740 // this is not a CREATE TABLE, so find the first VIEW
741 $target_for_view = PMA_backquote($target_db);
742 while (true) {
743 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord'
744 && $parsed_sql[$i]['data'] == 'VIEW'
746 break;
748 $i++;
751 unset($analyzed_sql);
752 if (PMA_DRIZZLE) {
753 $table_delimiter = 'quote_backtick';
754 } else {
755 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
756 // ANSI_QUOTES might be a subset of sql_mode, for example
757 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
758 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
759 $table_delimiter = 'quote_double';
760 } else {
761 $table_delimiter = 'quote_backtick';
763 unset($server_sql_mode);
766 /* Find table name in query and replace it */
767 while ($parsed_sql[$i]['type'] != $table_delimiter) {
768 $i++;
771 /* no need to PMA_backquote() */
772 if (isset($target_for_view)) {
773 // this a view definition; we just found the first db name
774 // that follows DEFINER VIEW
775 // so change it for the new db name
776 $parsed_sql[$i]['data'] = $target_for_view;
777 // then we have to find all references to the source db
778 // and change them to the target db, ensuring we stay into
779 // the $parsed_sql limits
780 $last = $parsed_sql['len'] - 1;
781 $backquoted_source_db = PMA_backquote($source_db);
782 for (++$i; $i <= $last; $i++) {
783 if ($parsed_sql[$i]['type'] == $table_delimiter
784 && $parsed_sql[$i]['data'] == $backquoted_source_db
786 $parsed_sql[$i]['data'] = $target_for_view;
789 unset($last,$backquoted_source_db);
790 } else {
791 $parsed_sql[$i]['data'] = $target;
794 /* Generate query back */
795 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
796 // If table exists, and 'add drop table' is selected: Drop it!
797 $drop_query = '';
798 if (isset($GLOBALS['drop_if_exists'])
799 && $GLOBALS['drop_if_exists'] == 'true'
801 if (PMA_Table::isView($target_db, $target_table)) {
802 $drop_query = 'DROP VIEW';
803 } else {
804 $drop_query = 'DROP TABLE';
806 $drop_query .= ' IF EXISTS '
807 . PMA_backquote($target_db) . '.'
808 . PMA_backquote($target_table);
809 PMA_DBI_query($drop_query);
811 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
813 // If an existing table gets deleted, maintain any
814 // entries for the PMA_* tables
815 $maintain_relations = true;
818 @PMA_DBI_query($sql_structure);
819 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
821 if (($move || isset($GLOBALS['add_constraints']))
822 && !empty($GLOBALS['sql_constraints_query'])
824 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
825 $i = 0;
827 // find the first $table_delimiter, it must be the source table name
828 while ($parsed_sql[$i]['type'] != $table_delimiter) {
829 $i++;
830 // maybe someday we should guard against going over limit
831 //if ($i == $parsed_sql['len']) {
832 // break;
836 // replace it by the target table name, no need to PMA_backquote()
837 $parsed_sql[$i]['data'] = $target;
839 // now we must remove all $table_delimiter that follow a CONSTRAINT
840 // keyword, because a constraint name must be unique in a db
842 $cnt = $parsed_sql['len'] - 1;
844 for ($j = $i; $j < $cnt; $j++) {
845 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
846 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT'
848 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
849 $parsed_sql[$j+1]['data'] = '';
854 // Generate query back
855 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml(
856 $parsed_sql, 'query_only'
858 if ($mode == 'one_table') {
859 PMA_DBI_query($GLOBALS['sql_constraints_query']);
861 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
862 if ($mode == 'one_table') {
863 unset($GLOBALS['sql_constraints_query']);
866 } else {
867 $GLOBALS['sql_query'] = '';
870 // Copy the data unless this is a VIEW
871 if (($what == 'data' || $what == 'dataonly')
872 && ! PMA_Table::isView($target_db, $target_table)
874 $sql_set_mode = "SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO'";
875 PMA_DBI_query($sql_set_mode);
876 $GLOBALS['sql_query'] .= "\n\n" . $sql_set_mode . ';';
878 $sql_insert_data = 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
879 PMA_DBI_query($sql_insert_data);
880 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
883 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
885 // Drops old table if the user has requested to move it
886 if ($move) {
888 // This could avoid some problems with replicated databases, when
889 // moving table from replicated one to not replicated one
890 PMA_DBI_select_db($source_db);
892 if (PMA_Table::isView($source_db, $source_table)) {
893 $sql_drop_query = 'DROP VIEW';
894 } else {
895 $sql_drop_query = 'DROP TABLE';
897 $sql_drop_query .= ' ' . $source;
898 PMA_DBI_query($sql_drop_query);
900 // Move old entries from PMA-DBs to new table
901 if ($GLOBALS['cfgRelation']['commwork']) {
902 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
903 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\', '
904 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
905 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
906 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
907 PMA_query_as_controluser($remove_query);
908 unset($remove_query);
911 // updating bookmarks is not possible since only a single table is moved,
912 // and not the whole DB.
914 if ($GLOBALS['cfgRelation']['displaywork']) {
915 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
916 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\', '
917 . ' table_name = \'' . PMA_sqlAddSlashes($target_table) . '\''
918 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
919 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
920 PMA_query_as_controluser($table_query);
921 unset($table_query);
924 if ($GLOBALS['cfgRelation']['relwork']) {
925 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
926 . ' SET foreign_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
927 . ' foreign_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
928 . ' WHERE foreign_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
929 . ' AND foreign_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
930 PMA_query_as_controluser($table_query);
931 unset($table_query);
933 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
934 . ' SET master_table = \'' . PMA_sqlAddSlashes($target_table) . '\','
935 . ' master_db = \'' . PMA_sqlAddSlashes($target_db) . '\''
936 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($source_db) . '\''
937 . ' AND master_table = \'' . PMA_sqlAddSlashes($source_table) . '\'';
938 PMA_query_as_controluser($table_query);
939 unset($table_query);
943 * @todo Can't get moving PDFs the right way. The page numbers
944 * always get screwed up independently from duplication because the
945 * numbers do not seem to be stored on a per-database basis. Would
946 * the author of pdf support please have a look at it?
949 if ($GLOBALS['cfgRelation']['pdfwork']) {
950 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
951 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
952 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
953 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
954 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
955 PMA_query_as_controluser($table_query);
956 unset($table_query);
958 $pdf_query = 'SELECT pdf_page_number '
959 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
960 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
961 . ' AND table_name = \'' . PMA_sqlAddSlashes($target_table) . '\'';
962 $pdf_rs = PMA_query_as_controluser($pdf_query);
964 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
965 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
966 . ' SET db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
967 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
968 . ' AND page_nr = \'' . PMA_sqlAddSlashes($pdf_copy_row['pdf_page_number']) . '\'';
969 $tb_rs = PMA_query_as_controluser($table_query);
970 unset($table_query);
971 unset($tb_rs);
976 if ($GLOBALS['cfgRelation']['designerwork']) {
977 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
978 . ' SET table_name = \'' . PMA_sqlAddSlashes($target_table) . '\','
979 . ' db_name = \'' . PMA_sqlAddSlashes($target_db) . '\''
980 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($source_db) . '\''
981 . ' AND table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
982 PMA_query_as_controluser($table_query);
983 unset($table_query);
986 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
987 // end if ($move)
988 } else {
989 // we are copying
990 // Create new entries as duplicates from old PMA DBs
991 if ($what != 'dataonly' && ! isset($maintain_relations)) {
992 if ($GLOBALS['cfgRelation']['commwork']) {
993 // Get all comments and MIME-Types for current table
994 $comments_copy_query = 'SELECT
995 column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
996 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
997 WHERE
998 db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND
999 table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
1000 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
1002 // Write every comment as new copied entry. [MIME]
1003 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
1004 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
1005 . ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
1006 . ' VALUES('
1007 . '\'' . PMA_sqlAddSlashes($target_db) . '\','
1008 . '\'' . PMA_sqlAddSlashes($target_table) . '\','
1009 . '\'' . PMA_sqlAddSlashes($comments_copy_row['column_name']) . '\''
1010 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddSlashes($comments_copy_row['comment']) . '\','
1011 . '\'' . PMA_sqlAddSlashes($comments_copy_row['mimetype']) . '\','
1012 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation']) . '\','
1013 . '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
1014 . ')';
1015 PMA_query_as_controluser($new_comment_query);
1016 } // end while
1017 PMA_DBI_free_result($comments_copy_rs);
1018 unset($comments_copy_rs);
1021 // duplicating the bookmarks must not be done here, but
1022 // just once per db
1024 $get_fields = array('display_field');
1025 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1026 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
1027 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
1031 * @todo revise this code when we support cross-db relations
1033 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
1034 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
1035 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
1036 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
1039 $get_fields = array('foreign_field', 'master_table', 'master_field');
1040 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
1041 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
1042 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
1045 $get_fields = array('x', 'y', 'v', 'h');
1046 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1047 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
1048 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
1051 * @todo Can't get duplicating PDFs the right way. The
1052 * page numbers always get screwed up independently from
1053 * duplication because the numbers do not seem to be stored on a
1054 * per-database basis. Would the author of pdf support please
1055 * have a look at it?
1057 $get_fields = array('page_descr');
1058 $where_fields = array('db_name' => $source_db);
1059 $new_fields = array('db_name' => $target_db);
1060 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
1062 if (isset($last_id) && $last_id >= 0) {
1063 $get_fields = array('x', 'y');
1064 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
1065 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
1066 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
1071 return true;
1075 * checks if given name is a valid table name,
1076 * currently if not empty, trailing spaces, '.', '/' and '\'
1078 * @param string $table_name name to check
1080 * @todo add check for valid chars in filename on current system/os
1081 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
1083 * @return boolean whether the string is valid or not
1085 function isValidName($table_name)
1087 if ($table_name !== trim($table_name)) {
1088 // trailing spaces
1089 return false;
1092 if (! strlen($table_name)) {
1093 // zero length
1094 return false;
1097 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
1098 // illegal char . / \
1099 return false;
1102 return true;
1106 * renames table
1108 * @param string $new_name new table name
1109 * @param string $new_db new database name
1110 * @param bool $is_view is this for a VIEW rename?
1111 * @todo remove the $is_view parameter (also in callers)
1113 * @return bool success
1115 function rename($new_name, $new_db = null, $is_view = false)
1117 if (null !== $new_db && $new_db !== $this->getDbName()) {
1118 // Ensure the target is valid
1119 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1120 $this->errors[] = __('Invalid database') . ': ' . $new_db;
1121 return false;
1123 } else {
1124 $new_db = $this->getDbName();
1127 $new_table = new PMA_Table($new_name, $new_db);
1129 if ($this->getFullName() === $new_table->getFullName()) {
1130 return true;
1133 if (! PMA_Table::isValidName($new_name)) {
1134 $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
1135 return false;
1138 // If the table is moved to a different database drop its triggers first
1139 $triggers = PMA_DBI_get_triggers($this->getDbName(), $this->getName(), '');
1140 $handle_triggers = $this->getDbName() != $new_db && $triggers;
1141 if ($handle_triggers) {
1142 foreach ($triggers as $trigger) {
1143 $sql = 'DROP TRIGGER IF EXISTS ' . PMA_backquote($this->getDbName()) . '.'
1144 . PMA_backquote($trigger['name']) . ';';
1145 PMA_DBI_query($sql);
1150 * tested also for a view, in MySQL 5.0.92, 5.1.55 and 5.5.13
1152 $GLOBALS['sql_query'] = '
1153 RENAME TABLE ' . $this->getFullName(true) . '
1154 TO ' . $new_table->getFullName(true) . ';';
1155 // I don't think a specific error message for views is necessary
1156 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1157 // Restore triggers in the old database
1158 if ($handle_triggers) {
1159 PMA_DBI_select_db($this->getDbName());
1160 foreach ($triggers as $trigger) {
1161 PMA_DBI_query($trigger['create']);
1164 $this->errors[] = sprintf(
1165 __('Error renaming table %1$s to %2$s'),
1166 $this->getFullName(),
1167 $new_table->getFullName()
1169 return false;
1172 $old_name = $this->getName();
1173 $old_db = $this->getDbName();
1174 $this->setName($new_name);
1175 $this->setDbName($new_db);
1178 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1180 // Move old entries from comments to new table
1181 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1182 if ($GLOBALS['cfgRelation']['commwork']) {
1183 $remove_query = '
1184 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1185 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1186 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1187 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1188 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1189 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1190 PMA_query_as_controluser($remove_query);
1191 unset($remove_query);
1194 if ($GLOBALS['cfgRelation']['displaywork']) {
1195 $table_query = '
1196 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1197 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1198 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1199 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1200 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1201 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1202 PMA_query_as_controluser($table_query);
1203 unset($table_query);
1206 if ($GLOBALS['cfgRelation']['relwork']) {
1207 $table_query = '
1208 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1209 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1210 SET `foreign_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1211 `foreign_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1212 WHERE `foreign_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1213 AND `foreign_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1214 PMA_query_as_controluser($table_query);
1216 $table_query = '
1217 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1218 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1219 SET `master_db` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1220 `master_table` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1221 WHERE `master_db` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1222 AND `master_table` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1223 PMA_query_as_controluser($table_query);
1224 unset($table_query);
1227 if ($GLOBALS['cfgRelation']['pdfwork']) {
1228 $table_query = '
1229 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1230 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1231 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1232 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1233 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1234 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1235 PMA_query_as_controluser($table_query);
1236 unset($table_query);
1239 if ($GLOBALS['cfgRelation']['designerwork']) {
1240 $table_query = '
1241 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1242 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1243 SET `db_name` = \'' . PMA_sqlAddSlashes($new_db) . '\',
1244 `table_name` = \'' . PMA_sqlAddSlashes($new_name) . '\'
1245 WHERE `db_name` = \'' . PMA_sqlAddSlashes($old_db) . '\'
1246 AND `table_name` = \'' . PMA_sqlAddSlashes($old_name) . '\'';
1247 PMA_query_as_controluser($table_query);
1248 unset($table_query);
1251 $this->messages[] = sprintf(
1252 __('Table %s has been renamed to %s'),
1253 htmlspecialchars($old_name),
1254 htmlspecialchars($new_name)
1256 return true;
1260 * Get all unique columns
1262 * returns an array with all columns with unqiue content, in fact these are
1263 * all columns being single indexed in PRIMARY or UNIQUE
1265 * e.g.
1266 * - PRIMARY(id) // id
1267 * - UNIQUE(name) // name
1268 * - PRIMARY(fk_id1, fk_id2) // NONE
1269 * - UNIQUE(x,y) // NONE
1271 * @param bool $backquoted whether to quote name with backticks ``
1273 * @return array
1275 public function getUniqueColumns($backquoted = true)
1277 $sql = PMA_DBI_get_table_indexes_sql($this->getDbName(), $this->getName(), 'Non_unique = 0');
1278 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1280 $return = array();
1281 foreach ($uniques as $index) {
1282 if (count($index) > 1) {
1283 continue;
1285 $return[] = $this->getFullName($backquoted) . '.'
1286 . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1289 return $return;
1293 * Get all indexed columns
1295 * returns an array with all columns make use of an index, in fact only
1296 * first columns in an index
1298 * e.g. index(col1, col2) would only return col1
1300 * @param bool $backquoted whether to quote name with backticks ``
1302 * @return array
1304 public function getIndexedColumns($backquoted = true)
1306 $sql = PMA_DBI_get_table_indexes_sql($this->getDbName(), $this->getName(), 'Seq_in_index = 1');
1307 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1309 $return = array();
1310 foreach ($indexed as $column) {
1311 $return[] = $this->getFullName($backquoted) . '.'
1312 . ($backquoted ? PMA_backquote($column) : $column);
1315 return $return;
1319 * Get all columns
1321 * returns an array with all columns
1323 * @param bool $backquoted whether to quote name with backticks ``
1325 * @return array
1327 public function getColumns($backquoted = true)
1329 $sql = 'SHOW COLUMNS FROM ' . $this->getFullName(true);
1330 $indexed = PMA_DBI_fetch_result($sql, 'Field', 'Field');
1332 $return = array();
1333 foreach ($indexed as $column) {
1334 $return[] = $this->getFullName($backquoted) . '.'
1335 . ($backquoted ? PMA_backquote($column) : $column);
1338 return $return;
1342 * Return UI preferences for this table from phpMyAdmin database.
1344 * @return array
1346 protected function getUiPrefsFromDb()
1348 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
1349 PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1351 // Read from phpMyAdmin database
1352 $sql_query = " SELECT `prefs` FROM " . $pma_table
1353 . " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'"
1354 . " AND `db_name` = '" . PMA_sqlAddSlashes($this->db_name) . "'"
1355 . " AND `table_name` = '" . PMA_sqlAddSlashes($this->name) . "'";
1357 $row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
1358 if (isset($row[0])) {
1359 return json_decode($row[0], true);
1360 } else {
1361 return array();
1366 * Save this table's UI preferences into phpMyAdmin database.
1368 * @return true|PMA_Message
1370 protected function saveUiPrefsToDb()
1372 $pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
1373 . PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
1375 $username = $GLOBALS['cfg']['Server']['user'];
1376 $sql_query = " REPLACE INTO " . $pma_table
1377 . " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name)
1378 . "', '" . PMA_sqlAddSlashes($this->name) . "', '"
1379 . PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
1381 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1383 if (!$success) {
1384 $message = PMA_Message::error(__('Could not save table UI preferences'));
1385 $message->addMessage('<br /><br />');
1386 $message->addMessage(
1387 PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink']))
1389 return $message;
1392 // Remove some old rows in table_uiprefs if it exceeds the configured maximum rows
1393 $sql_query = 'SELECT COUNT(*) FROM ' . $pma_table;
1394 $rows_count = PMA_DBI_fetch_value($sql_query);
1395 $max_rows = $GLOBALS['cfg']['Server']['MaxTableUiprefs'];
1396 if ($rows_count > $max_rows) {
1397 $num_rows_to_delete = $rows_count - $max_rows;
1398 $sql_query
1399 = ' DELETE FROM ' . $pma_table .
1400 ' ORDER BY last_update ASC' .
1401 ' LIMIT ' . $num_rows_to_delete;
1402 $success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
1404 if (!$success) {
1405 $message = PMA_Message::error(
1406 sprintf(
1407 __('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
1408 PMA_showDocu('cfg_Servers_MaxTableUiprefs')
1411 $message->addMessage('<br /><br />');
1412 $message->addMessage(PMA_Message::rawError(PMA_DBI_getError($GLOBALS['controllink'])));
1413 print_r($message);
1414 return $message;
1418 return true;
1422 * Loads the UI preferences for this table.
1423 * If pmadb and table_uiprefs is set, it will load the UI preferences from
1424 * phpMyAdmin database.
1426 * @return nothing
1428 protected function loadUiPrefs()
1430 $server_id = $GLOBALS['server'];
1431 // set session variable if it's still undefined
1432 if (! isset($_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name])) {
1433 $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name] =
1434 // check whether we can get from pmadb
1435 (strlen($GLOBALS['cfg']['Server']['pmadb'])
1436 && strlen($GLOBALS['cfg']['Server']['table_uiprefs']))
1437 ? $this->getUiPrefsFromDb()
1438 : array();
1440 $this->uiprefs =& $_SESSION['tmp_user_values']['table_uiprefs'][$server_id][$this->db_name][$this->name];
1444 * Get a property from UI preferences.
1445 * Return false if the property is not found.
1446 * Available property:
1447 * - PROP_SORTED_COLUMN
1448 * - PROP_COLUMN_ORDER
1449 * - PROP_COLUMN_VISIB
1451 * @param string $property property
1453 * @return mixed
1455 public function getUiProp($property)
1457 if (! isset($this->uiprefs)) {
1458 $this->loadUiPrefs();
1460 // do checking based on property
1461 if ($property == self::PROP_SORTED_COLUMN) {
1462 if (isset($this->uiprefs[$property])) {
1463 // check if the column name is exist in this table
1464 $tmp = explode(' ', $this->uiprefs[$property]);
1465 $colname = $tmp[0];
1466 $avail_columns = $this->getColumns();
1467 foreach ($avail_columns as $each_col) {
1468 // check if $each_col ends with $colname
1469 if (substr_compare($each_col, $colname, strlen($each_col) - strlen($colname)) === 0) {
1470 return $this->uiprefs[$property];
1473 // remove the property, since it is not exist anymore in database
1474 $this->removeUiProp(self::PROP_SORTED_COLUMN);
1475 return false;
1476 } else {
1477 return false;
1479 } elseif ($property == self::PROP_COLUMN_ORDER
1480 || $property == self::PROP_COLUMN_VISIB
1482 if (! PMA_Table::isView($this->db_name, $this->name) && isset($this->uiprefs[$property])) {
1483 // check if the table has not been modified
1484 if (self::sGetStatusInfo($this->db_name, $this->name, 'Create_time') == $this->uiprefs['CREATE_TIME']) {
1485 return $this->uiprefs[$property];
1486 } else {
1487 // remove the property, since the table has been modified
1488 $this->removeUiProp(self::PROP_COLUMN_ORDER);
1489 return false;
1491 } else {
1492 return false;
1495 // default behaviour for other property:
1496 return isset($this->uiprefs[$property]) ? $this->uiprefs[$property] : false;
1500 * Set a property from UI preferences.
1501 * If pmadb and table_uiprefs is set, it will save the UI preferences to
1502 * phpMyAdmin database.
1503 * Available property:
1504 * - PROP_SORTED_COLUMN
1505 * - PROP_COLUMN_ORDER
1506 * - PROP_COLUMN_VISIB
1508 * @param string $property Property
1509 * @param mixed $value Value for the property
1510 * @param string $table_create_time Needed for PROP_COLUMN_ORDER and PROP_COLUMN_VISIB
1512 * @return boolean|PMA_Message
1514 public function setUiProp($property, $value, $table_create_time = null)
1516 if (! isset($this->uiprefs)) {
1517 $this->loadUiPrefs();
1519 // we want to save the create time if the property is PROP_COLUMN_ORDER
1520 if (! PMA_Table::isView($this->db_name, $this->name)
1521 && ($property == self::PROP_COLUMN_ORDER || $property == self::PROP_COLUMN_VISIB)
1523 $curr_create_time = self::sGetStatusInfo($this->db_name, $this->name, 'CREATE_TIME');
1524 if (isset($table_create_time)
1525 && $table_create_time == $curr_create_time
1527 $this->uiprefs['CREATE_TIME'] = $curr_create_time;
1528 } else {
1529 // there is no $table_create_time, or
1530 // supplied $table_create_time is older than current create time,
1531 // so don't save
1532 return PMA_Message::error(sprintf(
1533 __('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.'), $property));
1536 // save the value
1537 $this->uiprefs[$property] = $value;
1538 // check if pmadb is set
1539 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1540 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1542 return $this->saveUiprefsToDb();
1544 return true;
1548 * Remove a property from UI preferences.
1550 * @param string $property the property
1552 * @return true|PMA_Message
1554 public function removeUiProp($property)
1556 if (! isset($this->uiprefs)) {
1557 $this->loadUiPrefs();
1559 if (isset($this->uiprefs[$property])) {
1560 unset($this->uiprefs[$property]);
1561 // check if pmadb is set
1562 if (strlen($GLOBALS['cfg']['Server']['pmadb'])
1563 && strlen($GLOBALS['cfg']['Server']['table_uiprefs'])
1565 return $this->saveUiprefsToDb();
1568 return true;