in Synchronize, the connection problems detection no longer worked
[phpmyadmin/madhuracj.git] / libraries / Table.class.php
blob66cfeaa757a838ea52a3a90d837f778c11abea2b
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($quoted = false)
103 if ($quoted) {
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($quoted = false)
129 if ($quoted) {
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($quoted = false)
142 return $this->getDbName($quoted) . '.' . $this->getName($quoted);
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, 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';
241 static public function sGetToolTip($db, $table)
243 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
244 . ' (' . PMA_Table::countRecords($db, $table, true) . ')';
248 * Returns full table status info, or specific if $info provided
250 * this info is collected from information_schema
252 * @todo PMA_DBI_get_tables_full needs to be merged somehow into this class or at least better documented
253 * @param string $db
254 * @param string $table
255 * @param string $info
256 * @param boolean $force_read
257 * @return mixed
259 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false)
261 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
262 PMA_DBI_get_tables_full($db, $table);
265 if (! isset(PMA_Table::$cache[$db][$table])) {
266 // happens when we enter the table creation dialog
267 // or when we really did not get any status info, for example
268 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
269 return '';
272 if (null === $info) {
273 return PMA_Table::$cache[$db][$table];
276 if (! isset(PMA_Table::$cache[$db][$table][$info])) {
277 trigger_error('unkown table status: ' . $info, E_USER_WARNING);
278 return false;
281 return PMA_Table::$cache[$db][$table][$info];
285 * generates column/field specification for ALTER or CREATE TABLE syntax
287 * @todo move into class PMA_Column
288 * @todo on the interface, some js to clear the default value when the default
289 * current_timestamp is checked
290 * @static
291 * @param string $name name
292 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
293 * @param string $length length ('2', '5,2', '', ...)
294 * @param string $attribute
295 * @param string $collation
296 * @param string $null with 'NULL' or 'NOT NULL'
297 * @param string $default_type whether default is CURRENT_TIMESTAMP,
298 * NULL, NONE, USER_DEFINED
299 * @param boolean $default_value default value for USER_DEFINED default type
300 * @param string $extra 'AUTO_INCREMENT'
301 * @param string $comment field comment
302 * @param array &$field_primary list of fields for PRIMARY KEY
303 * @param string $index
304 * @return string field specification
306 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
307 $collation = '', $null = false, $default_type = 'USER_DEFINED',
308 $default_value = '', $extra = '', $comment = '',
309 &$field_primary, $index, $default_orig = false)
312 $is_timestamp = strpos(' ' . strtoupper($type), 'TIMESTAMP') == 1;
315 * @todo include db-name
317 $query = PMA_backquote($name) . ' ' . $type;
319 if ($length != ''
320 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT)$@i', $type)) {
321 $query .= '(' . $length . ')';
324 if ($attribute != '') {
325 $query .= ' ' . $attribute;
328 if (!empty($collation) && $collation != 'NULL'
329 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
330 $query .= PMA_generateCharsetQueryPart($collation);
333 if ($null !== false) {
334 if ($null == 'NULL') {
335 $query .= ' NULL';
336 } else {
337 $query .= ' NOT NULL';
341 switch ($default_type) {
342 case 'USER_DEFINED' :
343 if ($is_timestamp && $default_value === '0') {
344 // a TIMESTAMP does not accept DEFAULT '0'
345 // but DEFAULT 0 works
346 $query .= ' DEFAULT 0';
347 } elseif ($type == 'BIT') {
348 $query .= ' DEFAULT b\'' . preg_replace('/[^01]/', '0', $default_value) . '\'';
349 } else {
350 $query .= ' DEFAULT \'' . PMA_sqlAddslashes($default_value) . '\'';
352 break;
353 case 'NULL' :
354 case 'CURRENT_TIMESTAMP' :
355 $query .= ' DEFAULT ' . $default_type;
356 break;
357 case 'NONE' :
358 default :
359 break;
362 if (!empty($extra)) {
363 $query .= ' ' . $extra;
364 // Force an auto_increment field to be part of the primary key
365 // even if user did not tick the PK box;
366 if ($extra == 'AUTO_INCREMENT') {
367 $primary_cnt = count($field_primary);
368 if (1 == $primary_cnt) {
369 for ($j = 0; $j < $primary_cnt && $field_primary[$j] != $index; $j++) {
370 //void
372 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
373 $query .= ' PRIMARY KEY';
374 unset($field_primary[$j]);
376 // but the PK could contain other columns so do not append
377 // a PRIMARY KEY clause, just add a member to $field_primary
378 } else {
379 $found_in_pk = false;
380 for ($j = 0; $j < $primary_cnt; $j++) {
381 if ($field_primary[$j] == $index) {
382 $found_in_pk = true;
383 break;
385 } // end for
386 if (! $found_in_pk) {
387 $field_primary[] = $index;
390 } // end if (auto_increment)
392 if (!empty($comment)) {
393 $query .= " COMMENT '" . PMA_sqlAddslashes($comment) . "'";
395 return $query;
396 } // end function
399 * Counts and returns (or displays) the number of records in a table
401 * Revision 13 July 2001: Patch for limiting dump size from
402 * vinay@sanisoft.com & girish@sanisoft.com
404 * @param string the current database name
405 * @param string the current table name
406 * @param boolean whether to retain or to displays the result
407 * @param boolean whether to force an exact count
409 * @return mixed the number of records if "retain" param is true,
410 * otherwise true
412 * @access public
414 static public function countRecords($db, $table, $ret = false,
415 $force_exact = false, $is_view = null)
417 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
418 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
419 } else {
420 $row_count = false;
422 if (null === $is_view) {
423 $is_view = PMA_Table::isView($db, $table);
426 if (! $force_exact) {
427 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
428 PMA_Table::$cache[$db][$table] = PMA_DBI_fetch_single_row('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table, true) . '\'');
430 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
433 // for a VIEW, $row_count is always false at this point
434 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
435 if (! $is_view) {
436 $row_count = PMA_DBI_fetch_value(
437 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
438 . PMA_backquote($table));
439 } else {
440 // For complex views, even trying to get a partial record
441 // count could bring down a server, so we offer an
442 // alternative: setting MaxExactCountViews to 0 will bypass
443 // completely the record counting for views
445 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
446 $row_count = 0;
447 } else {
448 // Counting all rows of a VIEW could be too long, so use
449 // a LIMIT clause.
450 // Use try_query because it can fail (a VIEW is based on
451 // a table that no longer exists)
452 $result = PMA_DBI_try_query(
453 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
454 . PMA_backquote($table) . ' LIMIT '
455 . $GLOBALS['cfg']['MaxExactCountViews'],
456 null, PMA_DBI_QUERY_STORE);
457 if (!PMA_DBI_getError()) {
458 $row_count = PMA_DBI_num_rows($result);
459 PMA_DBI_free_result($result);
463 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
467 if ($ret) {
468 return $row_count;
472 * @deprecated at the moment nowhere is $return = false used
474 // Note: as of PMA 2.8.0, we no longer seem to be using
475 // PMA_Table::countRecords() in display mode.
476 echo PMA_formatNumber($row_count, 0);
477 if ($is_view) {
478 echo '&nbsp;'
479 . sprintf($GLOBALS['strViewHasAtLeast'],
480 $GLOBALS['cfg']['MaxExactCount'],
481 '[a@./Documentation.html#cfg_MaxExactCount@_blank]', '[/a]');
483 } // end of the 'PMA_Table::countRecords()' function
486 * @see PMA_Table::generateFieldSpec()
488 static public function generateAlter($oldcol, $newcol, $type, $length,
489 $attribute, $collation, $null, $default_type, $default_value,
490 $extra, $comment = '', &$field_primary, $index, $default_orig)
492 return PMA_backquote($oldcol) . ' '
493 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
494 $collation, $null, $default_type, $default_value, $extra,
495 $comment, $field_primary, $index, $default_orig);
496 } // end function
499 * Inserts existing entries in a PMA_* table by reading a value from an old entry
501 * @param string The array index, which Relation feature to check
502 * ('relwork', 'commwork', ...)
503 * @param string The array index, which PMA-table to update
504 * ('bookmark', 'relation', ...)
505 * @param array Which fields will be SELECT'ed from the old entry
506 * @param array Which fields will be used for the WHERE query
507 * (array('FIELDNAME' => 'FIELDVALUE'))
508 * @param array Which fields will be used as new VALUES. These are the important
509 * keys which differ from the old entry.
510 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
512 * @global string relation variable
514 * @author Garvin Hicking <me@supergarv.de>
516 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
517 $new_fields)
519 $last_id = -1;
521 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
522 $select_parts = array();
523 $row_fields = array();
524 foreach ($get_fields as $get_field) {
525 $select_parts[] = PMA_backquote($get_field);
526 $row_fields[$get_field] = 'cc';
529 $where_parts = array();
530 foreach ($where_fields as $_where => $_value) {
531 $where_parts[] = PMA_backquote($_where) . ' = \''
532 . PMA_sqlAddslashes($_value) . '\'';
535 $new_parts = array();
536 $new_value_parts = array();
537 foreach ($new_fields as $_where => $_value) {
538 $new_parts[] = PMA_backquote($_where);
539 $new_value_parts[] = PMA_sqlAddslashes($_value);
542 $table_copy_query = '
543 SELECT ' . implode(', ', $select_parts) . '
544 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
545 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
546 WHERE ' . implode(' AND ', $where_parts);
548 // must use PMA_DBI_QUERY_STORE here, since we execute another
549 // query inside the loop
550 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
551 PMA_DBI_QUERY_STORE);
553 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
554 $value_parts = array();
555 foreach ($table_copy_row as $_key => $_val) {
556 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
557 $value_parts[] = PMA_sqlAddslashes($_val);
561 $new_table_query = '
562 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
563 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
564 (' . implode(', ', $select_parts) . ',
565 ' . implode(', ', $new_parts) . ')
566 VALUES
567 (\'' . implode('\', \'', $value_parts) . '\',
568 \'' . implode('\', \'', $new_value_parts) . '\')';
570 PMA_query_as_controluser($new_table_query);
571 $last_id = PMA_DBI_insert_id();
572 } // end while
574 PMA_DBI_free_result($table_copy_rs);
576 return $last_id;
579 return true;
580 } // end of 'PMA_Table::duplicateInfo()' function
584 * Copies or renames table
585 * @todo use RENAME for move operations
586 * - would work only if the databases are on the same filesystem,
587 * how can we check that? try the operation and
588 * catch an error?
589 * - for views, only if MYSQL > 50013
590 * - still have to handle pmadb synch.
592 * @author Michal Cihar <michal@cihar.com>
594 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
596 global $err_url;
598 // set export settings we need
599 $GLOBALS['sql_backquotes'] = 1;
600 $GLOBALS['asfile'] = 1;
602 // Ensure the target is valid
603 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
604 if (! $GLOBALS['pma']->databases->exists($source_db)) {
605 $GLOBALS['message'] = PMA_Message::rawError('source database `'
606 . htmlspecialchars($source_db) . '` not found');
608 if (! $GLOBALS['pma']->databases->exists($target_db)) {
609 $GLOBALS['message'] = PMA_Message::rawError('target database `'
610 . htmlspecialchars($target_db) . '` not found');
612 return false;
615 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
616 if (! isset($target_db) || ! strlen($target_db)) {
617 $target_db = $source_db;
620 // Doing a select_db could avoid some problems with replicated databases,
621 // when moving table from replicated one to not replicated one
622 PMA_DBI_select_db($target_db);
624 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
626 // do not create the table if dataonly
627 if ($what != 'dataonly') {
628 require_once './libraries/export/sql.php';
630 $no_constraints_comments = true;
631 $GLOBALS['sql_constraints_query'] = '';
633 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
634 unset($no_constraints_comments);
635 $parsed_sql = PMA_SQP_parse($sql_structure);
636 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
637 $i = 0;
638 if (empty($analyzed_sql[0]['create_table_fields'])) {
639 // this is not a CREATE TABLE, so find the first VIEW
640 $target_for_view = PMA_backquote($target_db);
641 while (true) {
642 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
643 break;
645 $i++;
648 unset($analyzed_sql);
649 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
650 // ANSI_QUOTES might be a subset of sql_mode, for example
651 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
652 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
653 $table_delimiter = 'quote_double';
654 } else {
655 $table_delimiter = 'quote_backtick';
657 unset($server_sql_mode);
659 /* nijel: Find table name in query and replace it */
660 while ($parsed_sql[$i]['type'] != $table_delimiter) {
661 $i++;
664 /* no need to PMA_backquote() */
665 if (isset($target_for_view)) {
666 // this a view definition; we just found the first db name
667 // that follows DEFINER VIEW
668 // so change it for the new db name
669 $parsed_sql[$i]['data'] = $target_for_view;
670 // then we have to find all references to the source db
671 // and change them to the target db, ensuring we stay into
672 // the $parsed_sql limits
673 $last = $parsed_sql['len'] - 1;
674 $backquoted_source_db = PMA_backquote($source_db);
675 for (++$i; $i <= $last; $i++) {
676 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
677 $parsed_sql[$i]['data'] = $target_for_view;
680 unset($last,$backquoted_source_db);
681 } else {
682 $parsed_sql[$i]['data'] = $target;
685 /* Generate query back */
686 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
687 // If table exists, and 'add drop table' is selected: Drop it!
688 $drop_query = '';
689 if (isset($GLOBALS['drop_if_exists'])
690 && $GLOBALS['drop_if_exists'] == 'true') {
691 if (PMA_Table::_isView($target_db,$target_table)) {
692 $drop_query = 'DROP VIEW';
693 } else {
694 $drop_query = 'DROP TABLE';
696 $drop_query .= ' IF EXISTS '
697 . PMA_backquote($target_db) . '.'
698 . PMA_backquote($target_table);
699 PMA_DBI_query($drop_query);
701 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
703 // garvin: If an existing table gets deleted, maintain any
704 // entries for the PMA_* tables
705 $maintain_relations = true;
708 @PMA_DBI_query($sql_structure);
709 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
711 if (($move || isset($GLOBALS['add_constraints']))
712 && !empty($GLOBALS['sql_constraints_query'])) {
713 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
714 $i = 0;
716 // find the first $table_delimiter, it must be the source table name
717 while ($parsed_sql[$i]['type'] != $table_delimiter) {
718 $i++;
719 // maybe someday we should guard against going over limit
720 //if ($i == $parsed_sql['len']) {
721 // break;
725 // replace it by the target table name, no need to PMA_backquote()
726 $parsed_sql[$i]['data'] = $target;
728 // now we must remove all $table_delimiter that follow a CONSTRAINT
729 // keyword, because a constraint name must be unique in a db
731 $cnt = $parsed_sql['len'] - 1;
733 for ($j = $i; $j < $cnt; $j++) {
734 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
735 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
736 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
737 $parsed_sql[$j+1]['data'] = '';
742 // Generate query back
743 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
744 'query_only');
745 if ($mode == 'one_table') {
746 PMA_DBI_query($GLOBALS['sql_constraints_query']);
748 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
749 if ($mode == 'one_table') {
750 unset($GLOBALS['sql_constraints_query']);
753 } else {
754 $GLOBALS['sql_query'] = '';
757 // Copy the data unless this is a VIEW
758 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
759 $sql_insert_data =
760 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
761 PMA_DBI_query($sql_insert_data);
762 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
765 require_once './libraries/relation.lib.php';
766 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
768 // Drops old table if the user has requested to move it
769 if ($move) {
771 // This could avoid some problems with replicated databases, when
772 // moving table from replicated one to not replicated one
773 PMA_DBI_select_db($source_db);
775 if (PMA_Table::_isView($source_db,$source_table)) {
776 $sql_drop_query = 'DROP VIEW';
777 } else {
778 $sql_drop_query = 'DROP TABLE';
780 $sql_drop_query .= ' ' . $source;
781 PMA_DBI_query($sql_drop_query);
783 // garvin: Move old entries from PMA-DBs to new table
784 if ($GLOBALS['cfgRelation']['commwork']) {
785 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
786 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
787 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
788 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
789 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
790 PMA_query_as_controluser($remove_query);
791 unset($remove_query);
794 // garvin: updating bookmarks is not possible since only a single table is moved,
795 // and not the whole DB.
797 if ($GLOBALS['cfgRelation']['displaywork']) {
798 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
799 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
800 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
801 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
802 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
803 PMA_query_as_controluser($table_query);
804 unset($table_query);
807 if ($GLOBALS['cfgRelation']['relwork']) {
808 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
809 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
810 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
811 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
812 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
813 PMA_query_as_controluser($table_query);
814 unset($table_query);
816 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
817 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
818 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
819 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
820 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
821 PMA_query_as_controluser($table_query);
822 unset($table_query);
826 * @todo garvin: Can't get moving PDFs the right way. The page numbers
827 * always get screwed up independently from duplication because the
828 * numbers do not seem to be stored on a per-database basis. Would
829 * the author of pdf support please have a look at it?
832 if ($GLOBALS['cfgRelation']['pdfwork']) {
833 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
834 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
835 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
836 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
837 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
838 PMA_query_as_controluser($table_query);
839 unset($table_query);
841 $pdf_query = 'SELECT pdf_page_number '
842 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
843 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
844 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
845 $pdf_rs = PMA_query_as_controluser($pdf_query);
847 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
848 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
849 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
850 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
851 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
852 $tb_rs = PMA_query_as_controluser($table_query);
853 unset($table_query);
854 unset($tb_rs);
859 if ($GLOBALS['cfgRelation']['designerwork']) {
860 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
861 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
862 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
863 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
864 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
865 PMA_query_as_controluser($table_query);
866 unset($table_query);
869 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
870 // end if ($move)
871 } else {
872 // we are copying
873 // garvin: Create new entries as duplicates from old PMA DBs
874 if ($what != 'dataonly' && !isset($maintain_relations)) {
875 if ($GLOBALS['cfgRelation']['commwork']) {
876 // Get all comments and MIME-Types for current table
877 $comments_copy_query = 'SELECT
878 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
879 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
880 WHERE
881 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
882 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
883 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
885 // Write every comment as new copied entry. [MIME]
886 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
887 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
888 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
889 . ' VALUES('
890 . '\'' . PMA_sqlAddslashes($target_db) . '\','
891 . '\'' . PMA_sqlAddslashes($target_table) . '\','
892 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
893 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
894 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
895 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
896 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
897 . ')';
898 PMA_query_as_controluser($new_comment_query);
899 } // end while
900 PMA_DBI_free_result($comments_copy_rs);
901 unset($comments_copy_rs);
904 // duplicating the bookmarks must not be done here, but
905 // just once per db
907 $get_fields = array('display_field');
908 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
909 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
910 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
914 * @todo revise this code when we support cross-db relations
916 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
917 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
918 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
919 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
922 $get_fields = array('foreign_field', 'master_table', 'master_field');
923 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
924 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
925 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
928 $get_fields = array('x', 'y', 'v', 'h');
929 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
930 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
931 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
934 * @todo garvin: Can't get duplicating PDFs the right way. The
935 * page numbers always get screwed up independently from
936 * duplication because the numbers do not seem to be stored on a
937 * per-database basis. Would the author of pdf support please
938 * have a look at it?
940 $get_fields = array('page_descr');
941 $where_fields = array('db_name' => $source_db);
942 $new_fields = array('db_name' => $target_db);
943 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
945 if (isset($last_id) && $last_id >= 0) {
946 $get_fields = array('x', 'y');
947 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
948 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
949 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
954 return true;
958 * checks if given name is a valid table name,
959 * currently if not empty, trailing spaces, '.', '/' and '\'
961 * @todo add check for valid chars in filename on current system/os
962 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
963 * @param string $table_name name to check
964 * @return boolean whether the string is valid or not
966 function isValidName($table_name)
968 if ($table_name !== trim($table_name)) {
969 // trailing spaces
970 return false;
973 if (! strlen($table_name)) {
974 // zero length
975 return false;
978 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
979 // illegal char . / \
980 return false;
983 return true;
987 * renames table
989 * @param string new table name
990 * @param string new database name
991 * @return boolean success
993 function rename($new_name, $new_db = null)
995 if (null !== $new_db && $new_db !== $this->getDbName()) {
996 // Ensure the target is valid
997 if (! $GLOBALS['pma']->databases->exists($new_db)) {
998 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
999 return false;
1001 } else {
1002 $new_db = $this->getDbName();
1005 $new_table = new PMA_Table($new_name, $new_db);
1007 if ($this->getFullName() === $new_table->getFullName()) {
1008 return true;
1011 if (! PMA_Table::isValidName($new_name)) {
1012 $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
1013 return false;
1016 $GLOBALS['sql_query'] = '
1017 RENAME TABLE ' . $this->getFullName(true) . '
1018 TO ' . $new_table->getFullName(true) . ';';
1019 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1020 $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
1021 return false;
1024 $old_name = $this->getName();
1025 $old_db = $this->getDbName();
1026 $this->setName($new_name);
1027 $this->setDbName($new_db);
1030 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1032 // garvin: Move old entries from comments to new table
1033 require_once './libraries/relation.lib.php';
1034 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1035 if ($GLOBALS['cfgRelation']['commwork']) {
1036 $remove_query = '
1037 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1038 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1039 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1040 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1041 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1042 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1043 PMA_query_as_controluser($remove_query);
1044 unset($remove_query);
1047 if ($GLOBALS['cfgRelation']['displaywork']) {
1048 $table_query = '
1049 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1050 . PMA_backquote($GLOBALS['cfgRelation']['table_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($table_query);
1056 unset($table_query);
1059 if ($GLOBALS['cfgRelation']['relwork']) {
1060 $table_query = '
1061 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1062 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1063 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1064 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1065 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1066 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1067 PMA_query_as_controluser($table_query);
1069 $table_query = '
1070 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1071 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1072 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1073 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1074 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1075 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1076 PMA_query_as_controluser($table_query);
1077 unset($table_query);
1080 if ($GLOBALS['cfgRelation']['pdfwork']) {
1081 $table_query = '
1082 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1083 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1084 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1085 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1086 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1087 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1088 PMA_query_as_controluser($table_query);
1089 unset($table_query);
1092 if ($GLOBALS['cfgRelation']['designerwork']) {
1093 $table_query = '
1094 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1095 . PMA_backquote($GLOBALS['cfgRelation']['designer_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 $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
1105 htmlspecialchars($old_name), htmlspecialchars($new_name));
1106 return true;
1110 * Get all unique columns
1112 * returns an array with all columns with unqiue content, in fact these are
1113 * all columns being single indexed in PRIMARY or UNIQUE
1115 * f.e.
1116 * - PRIMARY(id) // id
1117 * - UNIQUE(name) // name
1118 * - PRIMARY(fk_id1, fk_id2) // NONE
1119 * - UNIQUE(x,y) // NONE
1122 * @param boolean whether to quote name with backticks ``
1123 * @return array
1125 public function getUniqueColumns($quoted = true)
1127 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1128 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1130 $return = array();
1131 foreach ($uniques as $index) {
1132 if (count($index) > 1) {
1133 continue;
1135 $return[] = $this->getFullName($quoted) . '.' . ($quoted ? PMA_backquote($index[0]) : $index[0]);
1138 return $return;
1142 * Get all indexed columns
1144 * returns an array with all columns make use of an index, in fact only
1145 * first columns in an index
1147 * f.e. index(col1, col2) would only return col1
1148 * @param boolean whether to quote name with backticks ``
1149 * @return array
1151 public function getIndexedColumns($quoted = true)
1153 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1154 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1156 $return = array();
1157 foreach ($indexed as $column) {
1158 $return[] = $this->getFullName($quoted) . '.' . ($quoted ? PMA_backquote($column) : $column);
1161 return $return;