value can be negative
[phpmyadmin-themes.git] / libraries / Table.class.php
blobceed355b9f62c7e2ecc94f5afeda3e24bac0c1ce
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
5 * @version $Id$
6 * @package phpMyAdmin
7 */
9 /**
10 * @todo make use of PMA_Message and PMA_Error
11 * @package phpMyAdmin
13 class PMA_Table
16 static $cache = array();
18 /**
19 * @var string table name
21 var $name = '';
23 /**
24 * @var string database name
26 var $db_name = '';
28 /**
29 * @var string engine (innodb, myisam, bdb, ...)
31 var $engine = '';
33 /**
34 * @var string type (view, base table, system view)
36 var $type = '';
38 /**
39 * @var array settings
41 var $settings = array();
43 /**
44 * @var array errors occured
46 var $errors = array();
48 /**
49 * @var array messages
51 var $messages = array();
53 /**
54 * Constructor
56 * @param string $table_name table name
57 * @param string $db_name database name
59 function __construct($table_name, $db_name)
61 $this->setName($table_name);
62 $this->setDbName($db_name);
65 /**
66 * @see PMA_Table::getName()
68 function __toString()
70 return $this->getName();
73 function getLastError()
75 return end($this->errors);
78 function getLastMessage()
80 return end($this->messages);
83 /**
84 * sets table name
86 * @uses $this->name to set it
87 * @param string $table_name new table name
89 function setName($table_name)
91 $this->name = $table_name;
94 /**
95 * returns table name
97 * @uses $this->name as return value
98 * @param boolean whether to quote name with backticks ``
99 * @return string table name
101 function getName($backquoted = false)
103 if ($backquoted) {
104 return PMA_backquote($this->name);
106 return $this->name;
110 * sets database name for this table
112 * @uses $this->db_name to set it
113 * @param string $db_name
115 function setDbName($db_name)
117 $this->db_name = $db_name;
121 * returns database name for this table
123 * @uses $this->db_name as return value
124 * @param boolean whether to quote name with backticks ``
125 * @return string database name for this table
127 function getDbName($backquoted = false)
129 if ($backquoted) {
130 return PMA_backquote($this->db_name);
132 return $this->db_name;
136 * returns full name for table, including database name
138 * @param boolean whether to quote name with backticks ``
140 function getFullName($backquoted = false)
142 return $this->getDbName($backquoted) . '.' . $this->getName($backquoted);
145 static public function isView($db = null, $table = null)
147 if (strlen($db) && strlen($table)) {
148 return PMA_Table::_isView($db, $table);
151 if (isset($this) && strpos($this->get('TABLE TYPE'), 'VIEW')) {
152 return true;
155 return false;
159 * sets given $value for given $param
161 * @uses $this->settings to add or change value
162 * @param string param name
163 * @param mixed param value
165 function set($param, $value)
167 $this->settings[$param] = $value;
171 * returns value for given setting/param
173 * @uses $this->settings to return value
174 * @param string name for value to return
175 * @return mixed value for $param
177 function get($param)
179 if (isset($this->settings[$param])) {
180 return $this->settings[$param];
183 return null;
187 * loads structure data
188 * (this function is work in progress? not yet used)
190 function loadStructure()
192 $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
194 if (false === $table_info) {
195 return false;
198 $this->settings = $table_info;
200 if ($this->get('TABLE_ROWS') === null) {
201 $this->set('TABLE_ROWS', PMA_Table::countRecords($this->getDbName(),
202 $this->getName(), true));
205 $create_options = explode(' ', $this->get('TABLE_ROWS'));
207 // export create options by its name as variables into gloabel namespace
208 // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
209 foreach ($create_options as $each_create_option) {
210 $each_create_option = explode('=', $each_create_option);
211 if (isset($each_create_option[1])) {
212 $this->set($$each_create_option[0], $each_create_option[1]);
218 * Checks if this "table" is a view
220 * @deprecated
221 * @todo see what we could do with the possible existence of $table_is_view
222 * @param string the database name
223 * @param string the table name
225 * @return boolean whether this is a view
227 * @access public
229 static protected function _isView($db, $table)
231 // maybe we already know if the table is a view
232 if (isset($GLOBALS['tbl_is_view']) && $GLOBALS['tbl_is_view']) {
233 return true;
236 // Since phpMyAdmin 3.2 the field TABLE_TYPE is properly filled by PMA_DBI_get_tables_full()
237 $type = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_TYPE');
238 return $type == 'VIEW';
242 * Checks if this is a merge table
244 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias), this is a merge table.
246 * @param string the database name
247 * @param string the table name
248 * @return boolean true if it is a merge table
249 * @access public
251 static public function isMerge($db = null, $table = null)
253 // if called static, with parameters
254 if (! empty($db) && ! empty($table)) {
255 $engine = PMA_Table::sGetStatusInfo($db, $table, 'ENGINE', null, true);
257 // if called as an object
258 // does not work yet, because $this->settings[] is not filled correctly
259 else if (! empty($this)) {
260 $engine = $this->get('ENGINE');
263 return (! empty($engine) && ((strtoupper($engine) == 'MERGE') || (strtoupper($engine) == 'MRG_MYISAM')));
266 static public function sGetToolTip($db, $table)
268 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
269 . ' (' . PMA_Table::countRecords($db, $table) . ')';
273 * Returns full table status info, or specific if $info provided
275 * this info is collected from information_schema
277 * @todo PMA_DBI_get_tables_full needs to be merged somehow into this class or at least better documented
278 * @param string $db
279 * @param string $table
280 * @param string $info
281 * @param boolean $force_read
282 * @param boolean if true, disables error message
283 * @return mixed
285 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false, $disable_error = false)
287 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
288 PMA_DBI_get_tables_full($db, $table);
291 if (! isset(PMA_Table::$cache[$db][$table])) {
292 // happens when we enter the table creation dialog
293 // or when we really did not get any status info, for example
294 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
295 return '';
298 if (null === $info) {
299 return PMA_Table::$cache[$db][$table];
302 if (! isset(PMA_Table::$cache[$db][$table][$info])) {
303 if (! $disable_error) {
304 trigger_error('unknown table status: ' . $info, E_USER_WARNING);
306 return false;
309 return PMA_Table::$cache[$db][$table][$info];
313 * generates column/field specification for ALTER or CREATE TABLE syntax
315 * @todo move into class PMA_Column
316 * @todo on the interface, some js to clear the default value when the default
317 * current_timestamp is checked
318 * @static
319 * @param string $name name
320 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
321 * @param string $length length ('2', '5,2', '', ...)
322 * @param string $attribute
323 * @param string $collation
324 * @param string $null with 'NULL' or 'NOT NULL'
325 * @param string $default_type whether default is CURRENT_TIMESTAMP,
326 * NULL, NONE, USER_DEFINED
327 * @param boolean $default_value default value for USER_DEFINED default type
328 * @param string $extra 'AUTO_INCREMENT'
329 * @param string $comment field comment
330 * @param array &$field_primary list of fields for PRIMARY KEY
331 * @param string $index
332 * @return string field specification
334 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
335 $collation = '', $null = false, $default_type = 'USER_DEFINED',
336 $default_value = '', $extra = '', $comment = '',
337 &$field_primary, $index, $default_orig = false)
340 $is_timestamp = strpos(' ' . strtoupper($type), 'TIMESTAMP') == 1;
343 * @todo include db-name
345 $query = PMA_backquote($name) . ' ' . $type;
347 if ($length != ''
348 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT)$@i', $type)) {
349 $query .= '(' . $length . ')';
352 if ($attribute != '') {
353 $query .= ' ' . $attribute;
356 if (!empty($collation) && $collation != 'NULL'
357 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
358 $query .= PMA_generateCharsetQueryPart($collation);
361 if ($null !== false) {
362 if ($null == 'NULL') {
363 $query .= ' NULL';
364 } else {
365 $query .= ' NOT NULL';
369 switch ($default_type) {
370 case 'USER_DEFINED' :
371 if ($is_timestamp && $default_value === '0') {
372 // a TIMESTAMP does not accept DEFAULT '0'
373 // but DEFAULT 0 works
374 $query .= ' DEFAULT 0';
375 } elseif ($type == 'BIT') {
376 $query .= ' DEFAULT b\'' . preg_replace('/[^01]/', '0', $default_value) . '\'';
377 } else {
378 $query .= ' DEFAULT \'' . PMA_sqlAddslashes($default_value) . '\'';
380 break;
381 case 'NULL' :
382 case 'CURRENT_TIMESTAMP' :
383 $query .= ' DEFAULT ' . $default_type;
384 break;
385 case 'NONE' :
386 default :
387 break;
390 if (!empty($extra)) {
391 $query .= ' ' . $extra;
392 // Force an auto_increment field to be part of the primary key
393 // even if user did not tick the PK box;
394 if ($extra == 'AUTO_INCREMENT') {
395 $primary_cnt = count($field_primary);
396 if (1 == $primary_cnt) {
397 for ($j = 0; $j < $primary_cnt && $field_primary[$j] != $index; $j++) {
398 //void
400 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
401 $query .= ' PRIMARY KEY';
402 unset($field_primary[$j]);
404 // but the PK could contain other columns so do not append
405 // a PRIMARY KEY clause, just add a member to $field_primary
406 } else {
407 $found_in_pk = false;
408 for ($j = 0; $j < $primary_cnt; $j++) {
409 if ($field_primary[$j] == $index) {
410 $found_in_pk = true;
411 break;
413 } // end for
414 if (! $found_in_pk) {
415 $field_primary[] = $index;
418 } // end if (auto_increment)
420 if (!empty($comment)) {
421 $query .= " COMMENT '" . PMA_sqlAddslashes($comment) . "'";
423 return $query;
424 } // end function
427 * Counts and returns (or displays) the number of records in a table
429 * Revision 13 July 2001: Patch for limiting dump size from
430 * vinay@sanisoft.com & girish@sanisoft.com
432 * @param string the current database name
433 * @param string the current table name
434 * @param boolean whether to force an exact count
436 * @return mixed the number of records if "retain" param is true,
437 * otherwise true
439 * @access public
441 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
443 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
444 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
445 } else {
446 $row_count = false;
448 if (null === $is_view) {
449 $is_view = PMA_Table::isView($db, $table);
452 if (! $force_exact) {
453 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
454 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
455 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
457 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
460 // for a VIEW, $row_count is always false at this point
461 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
462 if (! $is_view) {
463 $row_count = PMA_DBI_fetch_value(
464 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
465 . PMA_backquote($table));
466 } else {
467 // For complex views, even trying to get a partial record
468 // count could bring down a server, so we offer an
469 // alternative: setting MaxExactCountViews to 0 will bypass
470 // completely the record counting for views
472 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
473 $row_count = 0;
474 } else {
475 // Counting all rows of a VIEW could be too long, so use
476 // a LIMIT clause.
477 // Use try_query because it can fail (when a VIEW is
478 // based on a table that no longer exists)
479 $result = PMA_DBI_try_query(
480 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
481 . PMA_backquote($table) . ' LIMIT '
482 . $GLOBALS['cfg']['MaxExactCountViews'],
483 null, PMA_DBI_QUERY_STORE);
484 if (!PMA_DBI_getError()) {
485 $row_count = PMA_DBI_num_rows($result);
486 PMA_DBI_free_result($result);
490 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
494 return $row_count;
495 } // end of the 'PMA_Table::countRecords()' function
498 * @see PMA_Table::generateFieldSpec()
500 static public function generateAlter($oldcol, $newcol, $type, $length,
501 $attribute, $collation, $null, $default_type, $default_value,
502 $extra, $comment = '', &$field_primary, $index, $default_orig)
504 return PMA_backquote($oldcol) . ' '
505 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
506 $collation, $null, $default_type, $default_value, $extra,
507 $comment, $field_primary, $index, $default_orig);
508 } // end function
511 * Inserts existing entries in a PMA_* table by reading a value from an old entry
513 * @param string The array index, which Relation feature to check
514 * ('relwork', 'commwork', ...)
515 * @param string The array index, which PMA-table to update
516 * ('bookmark', 'relation', ...)
517 * @param array Which fields will be SELECT'ed from the old entry
518 * @param array Which fields will be used for the WHERE query
519 * (array('FIELDNAME' => 'FIELDVALUE'))
520 * @param array Which fields will be used as new VALUES. These are the important
521 * keys which differ from the old entry.
522 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
524 * @global string relation variable
526 * @author Garvin Hicking <me@supergarv.de>
528 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
529 $new_fields)
531 $last_id = -1;
533 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
534 $select_parts = array();
535 $row_fields = array();
536 foreach ($get_fields as $get_field) {
537 $select_parts[] = PMA_backquote($get_field);
538 $row_fields[$get_field] = 'cc';
541 $where_parts = array();
542 foreach ($where_fields as $_where => $_value) {
543 $where_parts[] = PMA_backquote($_where) . ' = \''
544 . PMA_sqlAddslashes($_value) . '\'';
547 $new_parts = array();
548 $new_value_parts = array();
549 foreach ($new_fields as $_where => $_value) {
550 $new_parts[] = PMA_backquote($_where);
551 $new_value_parts[] = PMA_sqlAddslashes($_value);
554 $table_copy_query = '
555 SELECT ' . implode(', ', $select_parts) . '
556 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
557 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
558 WHERE ' . implode(' AND ', $where_parts);
560 // must use PMA_DBI_QUERY_STORE here, since we execute another
561 // query inside the loop
562 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
563 PMA_DBI_QUERY_STORE);
565 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
566 $value_parts = array();
567 foreach ($table_copy_row as $_key => $_val) {
568 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
569 $value_parts[] = PMA_sqlAddslashes($_val);
573 $new_table_query = '
574 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
575 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
576 (' . implode(', ', $select_parts) . ',
577 ' . implode(', ', $new_parts) . ')
578 VALUES
579 (\'' . implode('\', \'', $value_parts) . '\',
580 \'' . implode('\', \'', $new_value_parts) . '\')';
582 PMA_query_as_controluser($new_table_query);
583 $last_id = PMA_DBI_insert_id();
584 } // end while
586 PMA_DBI_free_result($table_copy_rs);
588 return $last_id;
591 return true;
592 } // end of 'PMA_Table::duplicateInfo()' function
596 * Copies or renames table
597 * @todo use RENAME for move operations
598 * - would work only if the databases are on the same filesystem,
599 * how can we check that? try the operation and
600 * catch an error?
601 * - for views, only if MYSQL > 50013
602 * - still have to handle pmadb synch.
604 * @author Michal Cihar <michal@cihar.com>
606 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
608 global $err_url;
610 // set export settings we need
611 $GLOBALS['sql_backquotes'] = 1;
612 $GLOBALS['asfile'] = 1;
614 // Ensure the target is valid
615 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
616 if (! $GLOBALS['pma']->databases->exists($source_db)) {
617 $GLOBALS['message'] = PMA_Message::rawError('source database `'
618 . htmlspecialchars($source_db) . '` not found');
620 if (! $GLOBALS['pma']->databases->exists($target_db)) {
621 $GLOBALS['message'] = PMA_Message::rawError('target database `'
622 . htmlspecialchars($target_db) . '` not found');
624 return false;
627 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
628 if (! isset($target_db) || ! strlen($target_db)) {
629 $target_db = $source_db;
632 // Doing a select_db could avoid some problems with replicated databases,
633 // when moving table from replicated one to not replicated one
634 PMA_DBI_select_db($target_db);
636 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
638 // do not create the table if dataonly
639 if ($what != 'dataonly') {
640 require_once './libraries/export/sql.php';
642 $no_constraints_comments = true;
643 $GLOBALS['sql_constraints_query'] = '';
645 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
646 unset($no_constraints_comments);
647 $parsed_sql = PMA_SQP_parse($sql_structure);
648 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
649 $i = 0;
650 if (empty($analyzed_sql[0]['create_table_fields'])) {
651 // this is not a CREATE TABLE, so find the first VIEW
652 $target_for_view = PMA_backquote($target_db);
653 while (true) {
654 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
655 break;
657 $i++;
660 unset($analyzed_sql);
661 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
662 // ANSI_QUOTES might be a subset of sql_mode, for example
663 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
664 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
665 $table_delimiter = 'quote_double';
666 } else {
667 $table_delimiter = 'quote_backtick';
669 unset($server_sql_mode);
671 /* nijel: Find table name in query and replace it */
672 while ($parsed_sql[$i]['type'] != $table_delimiter) {
673 $i++;
676 /* no need to PMA_backquote() */
677 if (isset($target_for_view)) {
678 // this a view definition; we just found the first db name
679 // that follows DEFINER VIEW
680 // so change it for the new db name
681 $parsed_sql[$i]['data'] = $target_for_view;
682 // then we have to find all references to the source db
683 // and change them to the target db, ensuring we stay into
684 // the $parsed_sql limits
685 $last = $parsed_sql['len'] - 1;
686 $backquoted_source_db = PMA_backquote($source_db);
687 for (++$i; $i <= $last; $i++) {
688 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
689 $parsed_sql[$i]['data'] = $target_for_view;
692 unset($last,$backquoted_source_db);
693 } else {
694 $parsed_sql[$i]['data'] = $target;
697 /* Generate query back */
698 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
699 // If table exists, and 'add drop table' is selected: Drop it!
700 $drop_query = '';
701 if (isset($GLOBALS['drop_if_exists'])
702 && $GLOBALS['drop_if_exists'] == 'true') {
703 if (PMA_Table::_isView($target_db,$target_table)) {
704 $drop_query = 'DROP VIEW';
705 } else {
706 $drop_query = 'DROP TABLE';
708 $drop_query .= ' IF EXISTS '
709 . PMA_backquote($target_db) . '.'
710 . PMA_backquote($target_table);
711 PMA_DBI_query($drop_query);
713 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
715 // garvin: If an existing table gets deleted, maintain any
716 // entries for the PMA_* tables
717 $maintain_relations = true;
720 @PMA_DBI_query($sql_structure);
721 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
723 if (($move || isset($GLOBALS['add_constraints']))
724 && !empty($GLOBALS['sql_constraints_query'])) {
725 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
726 $i = 0;
728 // find the first $table_delimiter, it must be the source table name
729 while ($parsed_sql[$i]['type'] != $table_delimiter) {
730 $i++;
731 // maybe someday we should guard against going over limit
732 //if ($i == $parsed_sql['len']) {
733 // break;
737 // replace it by the target table name, no need to PMA_backquote()
738 $parsed_sql[$i]['data'] = $target;
740 // now we must remove all $table_delimiter that follow a CONSTRAINT
741 // keyword, because a constraint name must be unique in a db
743 $cnt = $parsed_sql['len'] - 1;
745 for ($j = $i; $j < $cnt; $j++) {
746 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
747 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
748 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
749 $parsed_sql[$j+1]['data'] = '';
754 // Generate query back
755 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
756 'query_only');
757 if ($mode == 'one_table') {
758 PMA_DBI_query($GLOBALS['sql_constraints_query']);
760 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
761 if ($mode == 'one_table') {
762 unset($GLOBALS['sql_constraints_query']);
765 } else {
766 $GLOBALS['sql_query'] = '';
769 // Copy the data unless this is a VIEW
770 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
771 $sql_insert_data =
772 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
773 PMA_DBI_query($sql_insert_data);
774 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
777 require_once './libraries/relation.lib.php';
778 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
780 // Drops old table if the user has requested to move it
781 if ($move) {
783 // This could avoid some problems with replicated databases, when
784 // moving table from replicated one to not replicated one
785 PMA_DBI_select_db($source_db);
787 if (PMA_Table::_isView($source_db,$source_table)) {
788 $sql_drop_query = 'DROP VIEW';
789 } else {
790 $sql_drop_query = 'DROP TABLE';
792 $sql_drop_query .= ' ' . $source;
793 PMA_DBI_query($sql_drop_query);
795 // garvin: Move old entries from PMA-DBs to new table
796 if ($GLOBALS['cfgRelation']['commwork']) {
797 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
798 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
799 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
800 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
801 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
802 PMA_query_as_controluser($remove_query);
803 unset($remove_query);
806 // garvin: updating bookmarks is not possible since only a single table is moved,
807 // and not the whole DB.
809 if ($GLOBALS['cfgRelation']['displaywork']) {
810 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
811 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
812 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
813 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
814 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
815 PMA_query_as_controluser($table_query);
816 unset($table_query);
819 if ($GLOBALS['cfgRelation']['relwork']) {
820 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
821 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
822 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
823 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
824 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
825 PMA_query_as_controluser($table_query);
826 unset($table_query);
828 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
829 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
830 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
831 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
832 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
833 PMA_query_as_controluser($table_query);
834 unset($table_query);
838 * @todo garvin: Can't get moving PDFs the right way. The page numbers
839 * always get screwed up independently from duplication because the
840 * numbers do not seem to be stored on a per-database basis. Would
841 * the author of pdf support please have a look at it?
844 if ($GLOBALS['cfgRelation']['pdfwork']) {
845 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
846 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
847 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
848 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
849 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
850 PMA_query_as_controluser($table_query);
851 unset($table_query);
853 $pdf_query = 'SELECT pdf_page_number '
854 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
855 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
856 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
857 $pdf_rs = PMA_query_as_controluser($pdf_query);
859 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
860 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
861 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
862 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
863 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
864 $tb_rs = PMA_query_as_controluser($table_query);
865 unset($table_query);
866 unset($tb_rs);
871 if ($GLOBALS['cfgRelation']['designerwork']) {
872 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
873 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
874 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
875 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
876 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
877 PMA_query_as_controluser($table_query);
878 unset($table_query);
881 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
882 // end if ($move)
883 } else {
884 // we are copying
885 // garvin: Create new entries as duplicates from old PMA DBs
886 if ($what != 'dataonly' && !isset($maintain_relations)) {
887 if ($GLOBALS['cfgRelation']['commwork']) {
888 // Get all comments and MIME-Types for current table
889 $comments_copy_query = 'SELECT
890 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
891 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
892 WHERE
893 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
894 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
895 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
897 // Write every comment as new copied entry. [MIME]
898 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
899 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
900 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
901 . ' VALUES('
902 . '\'' . PMA_sqlAddslashes($target_db) . '\','
903 . '\'' . PMA_sqlAddslashes($target_table) . '\','
904 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
905 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
906 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
907 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
908 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
909 . ')';
910 PMA_query_as_controluser($new_comment_query);
911 } // end while
912 PMA_DBI_free_result($comments_copy_rs);
913 unset($comments_copy_rs);
916 // duplicating the bookmarks must not be done here, but
917 // just once per db
919 $get_fields = array('display_field');
920 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
921 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
922 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
926 * @todo revise this code when we support cross-db relations
928 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
929 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
930 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
931 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
934 $get_fields = array('foreign_field', 'master_table', 'master_field');
935 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
936 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
937 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
940 $get_fields = array('x', 'y', 'v', 'h');
941 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
942 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
943 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
946 * @todo garvin: Can't get duplicating PDFs the right way. The
947 * page numbers always get screwed up independently from
948 * duplication because the numbers do not seem to be stored on a
949 * per-database basis. Would the author of pdf support please
950 * have a look at it?
952 $get_fields = array('page_descr');
953 $where_fields = array('db_name' => $source_db);
954 $new_fields = array('db_name' => $target_db);
955 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
957 if (isset($last_id) && $last_id >= 0) {
958 $get_fields = array('x', 'y');
959 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
960 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
961 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
966 return true;
970 * checks if given name is a valid table name,
971 * currently if not empty, trailing spaces, '.', '/' and '\'
973 * @todo add check for valid chars in filename on current system/os
974 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
975 * @param string $table_name name to check
976 * @return boolean whether the string is valid or not
978 function isValidName($table_name)
980 if ($table_name !== trim($table_name)) {
981 // trailing spaces
982 return false;
985 if (! strlen($table_name)) {
986 // zero length
987 return false;
990 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
991 // illegal char . / \
992 return false;
995 return true;
999 * renames table
1001 * @param string new table name
1002 * @param string new database name
1003 * @return boolean success
1005 function rename($new_name, $new_db = null)
1007 if (null !== $new_db && $new_db !== $this->getDbName()) {
1008 // Ensure the target is valid
1009 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1010 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
1011 return false;
1013 } else {
1014 $new_db = $this->getDbName();
1017 $new_table = new PMA_Table($new_name, $new_db);
1019 if ($this->getFullName() === $new_table->getFullName()) {
1020 return true;
1023 if (! PMA_Table::isValidName($new_name)) {
1024 $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
1025 return false;
1028 $GLOBALS['sql_query'] = '
1029 RENAME TABLE ' . $this->getFullName(true) . '
1030 TO ' . $new_table->getFullName(true) . ';';
1031 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1032 $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
1033 return false;
1036 $old_name = $this->getName();
1037 $old_db = $this->getDbName();
1038 $this->setName($new_name);
1039 $this->setDbName($new_db);
1042 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1044 // garvin: Move old entries from comments to new table
1045 require_once './libraries/relation.lib.php';
1046 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1047 if ($GLOBALS['cfgRelation']['commwork']) {
1048 $remove_query = '
1049 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1050 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1051 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1052 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1053 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1054 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1055 PMA_query_as_controluser($remove_query);
1056 unset($remove_query);
1059 if ($GLOBALS['cfgRelation']['displaywork']) {
1060 $table_query = '
1061 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1062 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1063 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1064 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1065 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1066 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1067 PMA_query_as_controluser($table_query);
1068 unset($table_query);
1071 if ($GLOBALS['cfgRelation']['relwork']) {
1072 $table_query = '
1073 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1074 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1075 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1076 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1077 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1078 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1079 PMA_query_as_controluser($table_query);
1081 $table_query = '
1082 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1083 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1084 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1085 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1086 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1087 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1088 PMA_query_as_controluser($table_query);
1089 unset($table_query);
1092 if ($GLOBALS['cfgRelation']['pdfwork']) {
1093 $table_query = '
1094 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1095 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1096 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1097 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1098 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1099 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1100 PMA_query_as_controluser($table_query);
1101 unset($table_query);
1104 if ($GLOBALS['cfgRelation']['designerwork']) {
1105 $table_query = '
1106 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1107 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1108 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1109 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1110 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1111 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1112 PMA_query_as_controluser($table_query);
1113 unset($table_query);
1116 $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
1117 htmlspecialchars($old_name), htmlspecialchars($new_name));
1118 return true;
1122 * Get all unique columns
1124 * returns an array with all columns with unqiue content, in fact these are
1125 * all columns being single indexed in PRIMARY or UNIQUE
1127 * f.e.
1128 * - PRIMARY(id) // id
1129 * - UNIQUE(name) // name
1130 * - PRIMARY(fk_id1, fk_id2) // NONE
1131 * - UNIQUE(x,y) // NONE
1134 * @param boolean whether to quote name with backticks ``
1135 * @return array
1137 public function getUniqueColumns($backquoted = true)
1139 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1140 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1142 $return = array();
1143 foreach ($uniques as $index) {
1144 if (count($index) > 1) {
1145 continue;
1147 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1150 return $return;
1154 * Get all indexed columns
1156 * returns an array with all columns make use of an index, in fact only
1157 * first columns in an index
1159 * f.e. index(col1, col2) would only return col1
1160 * @param boolean whether to quote name with backticks ``
1161 * @return array
1163 public function getIndexedColumns($backquoted = true)
1165 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1166 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1168 $return = array();
1169 foreach ($indexed as $column) {
1170 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1173 return $return;