bug #2042032 Cannot detect PmaAbsoluteUri correctly on Windows
[phpmyadmin/madhuracj.git] / libraries / Table.class.php
blob0f407e761c57331f183cdf317aca5744fda40ed6
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';
241 static public function sGetToolTip($db, $table)
243 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
244 . ' (' . PMA_Table::countRecords($db, $table) . ')';
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('unknown 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 force an exact count
408 * @return mixed the number of records if "retain" param is true,
409 * otherwise true
411 * @access public
413 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
415 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
416 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
417 } else {
418 $row_count = false;
420 if (null === $is_view) {
421 $is_view = PMA_Table::isView($db, $table);
424 if (! $force_exact) {
425 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
426 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
427 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
429 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
432 // for a VIEW, $row_count is always false at this point
433 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
434 if (! $is_view) {
435 $row_count = PMA_DBI_fetch_value(
436 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
437 . PMA_backquote($table));
438 } else {
439 // For complex views, even trying to get a partial record
440 // count could bring down a server, so we offer an
441 // alternative: setting MaxExactCountViews to 0 will bypass
442 // completely the record counting for views
444 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
445 $row_count = 0;
446 } else {
447 // Counting all rows of a VIEW could be too long, so use
448 // a LIMIT clause.
449 // Use try_query because it can fail (when a VIEW is
450 // based on a table that no longer exists)
451 $result = PMA_DBI_try_query(
452 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
453 . PMA_backquote($table) . ' LIMIT '
454 . $GLOBALS['cfg']['MaxExactCountViews'],
455 null, PMA_DBI_QUERY_STORE);
456 if (!PMA_DBI_getError()) {
457 $row_count = PMA_DBI_num_rows($result);
458 PMA_DBI_free_result($result);
462 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
466 return $row_count;
467 } // end of the 'PMA_Table::countRecords()' function
470 * @see PMA_Table::generateFieldSpec()
472 static public function generateAlter($oldcol, $newcol, $type, $length,
473 $attribute, $collation, $null, $default_type, $default_value,
474 $extra, $comment = '', &$field_primary, $index, $default_orig)
476 return PMA_backquote($oldcol) . ' '
477 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
478 $collation, $null, $default_type, $default_value, $extra,
479 $comment, $field_primary, $index, $default_orig);
480 } // end function
483 * Inserts existing entries in a PMA_* table by reading a value from an old entry
485 * @param string The array index, which Relation feature to check
486 * ('relwork', 'commwork', ...)
487 * @param string The array index, which PMA-table to update
488 * ('bookmark', 'relation', ...)
489 * @param array Which fields will be SELECT'ed from the old entry
490 * @param array Which fields will be used for the WHERE query
491 * (array('FIELDNAME' => 'FIELDVALUE'))
492 * @param array Which fields will be used as new VALUES. These are the important
493 * keys which differ from the old entry.
494 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
496 * @global string relation variable
498 * @author Garvin Hicking <me@supergarv.de>
500 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
501 $new_fields)
503 $last_id = -1;
505 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
506 $select_parts = array();
507 $row_fields = array();
508 foreach ($get_fields as $get_field) {
509 $select_parts[] = PMA_backquote($get_field);
510 $row_fields[$get_field] = 'cc';
513 $where_parts = array();
514 foreach ($where_fields as $_where => $_value) {
515 $where_parts[] = PMA_backquote($_where) . ' = \''
516 . PMA_sqlAddslashes($_value) . '\'';
519 $new_parts = array();
520 $new_value_parts = array();
521 foreach ($new_fields as $_where => $_value) {
522 $new_parts[] = PMA_backquote($_where);
523 $new_value_parts[] = PMA_sqlAddslashes($_value);
526 $table_copy_query = '
527 SELECT ' . implode(', ', $select_parts) . '
528 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
529 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
530 WHERE ' . implode(' AND ', $where_parts);
532 // must use PMA_DBI_QUERY_STORE here, since we execute another
533 // query inside the loop
534 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
535 PMA_DBI_QUERY_STORE);
537 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
538 $value_parts = array();
539 foreach ($table_copy_row as $_key => $_val) {
540 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
541 $value_parts[] = PMA_sqlAddslashes($_val);
545 $new_table_query = '
546 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
547 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
548 (' . implode(', ', $select_parts) . ',
549 ' . implode(', ', $new_parts) . ')
550 VALUES
551 (\'' . implode('\', \'', $value_parts) . '\',
552 \'' . implode('\', \'', $new_value_parts) . '\')';
554 PMA_query_as_controluser($new_table_query);
555 $last_id = PMA_DBI_insert_id();
556 } // end while
558 PMA_DBI_free_result($table_copy_rs);
560 return $last_id;
563 return true;
564 } // end of 'PMA_Table::duplicateInfo()' function
568 * Copies or renames table
569 * @todo use RENAME for move operations
570 * - would work only if the databases are on the same filesystem,
571 * how can we check that? try the operation and
572 * catch an error?
573 * - for views, only if MYSQL > 50013
574 * - still have to handle pmadb synch.
576 * @author Michal Cihar <michal@cihar.com>
578 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
580 global $err_url;
582 // set export settings we need
583 $GLOBALS['sql_backquotes'] = 1;
584 $GLOBALS['asfile'] = 1;
586 // Ensure the target is valid
587 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
588 if (! $GLOBALS['pma']->databases->exists($source_db)) {
589 $GLOBALS['message'] = PMA_Message::rawError('source database `'
590 . htmlspecialchars($source_db) . '` not found');
592 if (! $GLOBALS['pma']->databases->exists($target_db)) {
593 $GLOBALS['message'] = PMA_Message::rawError('target database `'
594 . htmlspecialchars($target_db) . '` not found');
596 return false;
599 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
600 if (! isset($target_db) || ! strlen($target_db)) {
601 $target_db = $source_db;
604 // Doing a select_db could avoid some problems with replicated databases,
605 // when moving table from replicated one to not replicated one
606 PMA_DBI_select_db($target_db);
608 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
610 // do not create the table if dataonly
611 if ($what != 'dataonly') {
612 require_once './libraries/export/sql.php';
614 $no_constraints_comments = true;
615 $GLOBALS['sql_constraints_query'] = '';
617 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
618 unset($no_constraints_comments);
619 $parsed_sql = PMA_SQP_parse($sql_structure);
620 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
621 $i = 0;
622 if (empty($analyzed_sql[0]['create_table_fields'])) {
623 // this is not a CREATE TABLE, so find the first VIEW
624 $target_for_view = PMA_backquote($target_db);
625 while (true) {
626 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
627 break;
629 $i++;
632 unset($analyzed_sql);
633 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
634 // ANSI_QUOTES might be a subset of sql_mode, for example
635 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
636 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
637 $table_delimiter = 'quote_double';
638 } else {
639 $table_delimiter = 'quote_backtick';
641 unset($server_sql_mode);
643 /* nijel: Find table name in query and replace it */
644 while ($parsed_sql[$i]['type'] != $table_delimiter) {
645 $i++;
648 /* no need to PMA_backquote() */
649 if (isset($target_for_view)) {
650 // this a view definition; we just found the first db name
651 // that follows DEFINER VIEW
652 // so change it for the new db name
653 $parsed_sql[$i]['data'] = $target_for_view;
654 // then we have to find all references to the source db
655 // and change them to the target db, ensuring we stay into
656 // the $parsed_sql limits
657 $last = $parsed_sql['len'] - 1;
658 $backquoted_source_db = PMA_backquote($source_db);
659 for (++$i; $i <= $last; $i++) {
660 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
661 $parsed_sql[$i]['data'] = $target_for_view;
664 unset($last,$backquoted_source_db);
665 } else {
666 $parsed_sql[$i]['data'] = $target;
669 /* Generate query back */
670 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
671 // If table exists, and 'add drop table' is selected: Drop it!
672 $drop_query = '';
673 if (isset($GLOBALS['drop_if_exists'])
674 && $GLOBALS['drop_if_exists'] == 'true') {
675 if (PMA_Table::_isView($target_db,$target_table)) {
676 $drop_query = 'DROP VIEW';
677 } else {
678 $drop_query = 'DROP TABLE';
680 $drop_query .= ' IF EXISTS '
681 . PMA_backquote($target_db) . '.'
682 . PMA_backquote($target_table);
683 PMA_DBI_query($drop_query);
685 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
687 // garvin: If an existing table gets deleted, maintain any
688 // entries for the PMA_* tables
689 $maintain_relations = true;
692 @PMA_DBI_query($sql_structure);
693 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
695 if (($move || isset($GLOBALS['add_constraints']))
696 && !empty($GLOBALS['sql_constraints_query'])) {
697 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
698 $i = 0;
700 // find the first $table_delimiter, it must be the source table name
701 while ($parsed_sql[$i]['type'] != $table_delimiter) {
702 $i++;
703 // maybe someday we should guard against going over limit
704 //if ($i == $parsed_sql['len']) {
705 // break;
709 // replace it by the target table name, no need to PMA_backquote()
710 $parsed_sql[$i]['data'] = $target;
712 // now we must remove all $table_delimiter that follow a CONSTRAINT
713 // keyword, because a constraint name must be unique in a db
715 $cnt = $parsed_sql['len'] - 1;
717 for ($j = $i; $j < $cnt; $j++) {
718 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
719 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
720 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
721 $parsed_sql[$j+1]['data'] = '';
726 // Generate query back
727 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
728 'query_only');
729 if ($mode == 'one_table') {
730 PMA_DBI_query($GLOBALS['sql_constraints_query']);
732 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
733 if ($mode == 'one_table') {
734 unset($GLOBALS['sql_constraints_query']);
737 } else {
738 $GLOBALS['sql_query'] = '';
741 // Copy the data unless this is a VIEW
742 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
743 $sql_insert_data =
744 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
745 PMA_DBI_query($sql_insert_data);
746 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
749 require_once './libraries/relation.lib.php';
750 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
752 // Drops old table if the user has requested to move it
753 if ($move) {
755 // This could avoid some problems with replicated databases, when
756 // moving table from replicated one to not replicated one
757 PMA_DBI_select_db($source_db);
759 if (PMA_Table::_isView($source_db,$source_table)) {
760 $sql_drop_query = 'DROP VIEW';
761 } else {
762 $sql_drop_query = 'DROP TABLE';
764 $sql_drop_query .= ' ' . $source;
765 PMA_DBI_query($sql_drop_query);
767 // garvin: Move old entries from PMA-DBs to new table
768 if ($GLOBALS['cfgRelation']['commwork']) {
769 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
770 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
771 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
772 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
773 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
774 PMA_query_as_controluser($remove_query);
775 unset($remove_query);
778 // garvin: updating bookmarks is not possible since only a single table is moved,
779 // and not the whole DB.
781 if ($GLOBALS['cfgRelation']['displaywork']) {
782 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
783 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
784 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
785 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
786 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
787 PMA_query_as_controluser($table_query);
788 unset($table_query);
791 if ($GLOBALS['cfgRelation']['relwork']) {
792 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
793 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
794 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
795 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
796 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
797 PMA_query_as_controluser($table_query);
798 unset($table_query);
800 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
801 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
802 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
803 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
804 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
805 PMA_query_as_controluser($table_query);
806 unset($table_query);
810 * @todo garvin: Can't get moving PDFs the right way. The page numbers
811 * always get screwed up independently from duplication because the
812 * numbers do not seem to be stored on a per-database basis. Would
813 * the author of pdf support please have a look at it?
816 if ($GLOBALS['cfgRelation']['pdfwork']) {
817 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
818 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
819 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
820 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
821 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
822 PMA_query_as_controluser($table_query);
823 unset($table_query);
825 $pdf_query = 'SELECT pdf_page_number '
826 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
827 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
828 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
829 $pdf_rs = PMA_query_as_controluser($pdf_query);
831 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
832 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
833 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
834 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
835 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
836 $tb_rs = PMA_query_as_controluser($table_query);
837 unset($table_query);
838 unset($tb_rs);
843 if ($GLOBALS['cfgRelation']['designerwork']) {
844 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
845 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
846 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
847 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
848 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
849 PMA_query_as_controluser($table_query);
850 unset($table_query);
853 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
854 // end if ($move)
855 } else {
856 // we are copying
857 // garvin: Create new entries as duplicates from old PMA DBs
858 if ($what != 'dataonly' && !isset($maintain_relations)) {
859 if ($GLOBALS['cfgRelation']['commwork']) {
860 // Get all comments and MIME-Types for current table
861 $comments_copy_query = 'SELECT
862 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
863 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
864 WHERE
865 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
866 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
867 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
869 // Write every comment as new copied entry. [MIME]
870 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
871 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
872 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
873 . ' VALUES('
874 . '\'' . PMA_sqlAddslashes($target_db) . '\','
875 . '\'' . PMA_sqlAddslashes($target_table) . '\','
876 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
877 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
878 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
879 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
880 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
881 . ')';
882 PMA_query_as_controluser($new_comment_query);
883 } // end while
884 PMA_DBI_free_result($comments_copy_rs);
885 unset($comments_copy_rs);
888 // duplicating the bookmarks must not be done here, but
889 // just once per db
891 $get_fields = array('display_field');
892 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
893 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
894 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
898 * @todo revise this code when we support cross-db relations
900 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
901 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
902 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
903 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
906 $get_fields = array('foreign_field', 'master_table', 'master_field');
907 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
908 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
909 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
912 $get_fields = array('x', 'y', 'v', 'h');
913 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
914 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
915 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
918 * @todo garvin: Can't get duplicating PDFs the right way. The
919 * page numbers always get screwed up independently from
920 * duplication because the numbers do not seem to be stored on a
921 * per-database basis. Would the author of pdf support please
922 * have a look at it?
924 $get_fields = array('page_descr');
925 $where_fields = array('db_name' => $source_db);
926 $new_fields = array('db_name' => $target_db);
927 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
929 if (isset($last_id) && $last_id >= 0) {
930 $get_fields = array('x', 'y');
931 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
932 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
933 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
938 return true;
942 * checks if given name is a valid table name,
943 * currently if not empty, trailing spaces, '.', '/' and '\'
945 * @todo add check for valid chars in filename on current system/os
946 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
947 * @param string $table_name name to check
948 * @return boolean whether the string is valid or not
950 function isValidName($table_name)
952 if ($table_name !== trim($table_name)) {
953 // trailing spaces
954 return false;
957 if (! strlen($table_name)) {
958 // zero length
959 return false;
962 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
963 // illegal char . / \
964 return false;
967 return true;
971 * renames table
973 * @param string new table name
974 * @param string new database name
975 * @return boolean success
977 function rename($new_name, $new_db = null)
979 if (null !== $new_db && $new_db !== $this->getDbName()) {
980 // Ensure the target is valid
981 if (! $GLOBALS['pma']->databases->exists($new_db)) {
982 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
983 return false;
985 } else {
986 $new_db = $this->getDbName();
989 $new_table = new PMA_Table($new_name, $new_db);
991 if ($this->getFullName() === $new_table->getFullName()) {
992 return true;
995 if (! PMA_Table::isValidName($new_name)) {
996 $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
997 return false;
1000 $GLOBALS['sql_query'] = '
1001 RENAME TABLE ' . $this->getFullName(true) . '
1002 TO ' . $new_table->getFullName(true) . ';';
1003 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1004 $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
1005 return false;
1008 $old_name = $this->getName();
1009 $old_db = $this->getDbName();
1010 $this->setName($new_name);
1011 $this->setDbName($new_db);
1014 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1016 // garvin: Move old entries from comments to new table
1017 require_once './libraries/relation.lib.php';
1018 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1019 if ($GLOBALS['cfgRelation']['commwork']) {
1020 $remove_query = '
1021 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1022 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1023 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1024 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1025 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1026 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1027 PMA_query_as_controluser($remove_query);
1028 unset($remove_query);
1031 if ($GLOBALS['cfgRelation']['displaywork']) {
1032 $table_query = '
1033 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1034 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1035 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1036 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1037 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1038 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1039 PMA_query_as_controluser($table_query);
1040 unset($table_query);
1043 if ($GLOBALS['cfgRelation']['relwork']) {
1044 $table_query = '
1045 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1046 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1047 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1048 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1049 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1050 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1051 PMA_query_as_controluser($table_query);
1053 $table_query = '
1054 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1055 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1056 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1057 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1058 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1059 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1060 PMA_query_as_controluser($table_query);
1061 unset($table_query);
1064 if ($GLOBALS['cfgRelation']['pdfwork']) {
1065 $table_query = '
1066 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1067 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1068 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1069 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1070 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1071 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1072 PMA_query_as_controluser($table_query);
1073 unset($table_query);
1076 if ($GLOBALS['cfgRelation']['designerwork']) {
1077 $table_query = '
1078 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1079 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1080 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1081 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1082 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1083 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1084 PMA_query_as_controluser($table_query);
1085 unset($table_query);
1088 $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
1089 htmlspecialchars($old_name), htmlspecialchars($new_name));
1090 return true;
1094 * Get all unique columns
1096 * returns an array with all columns with unqiue content, in fact these are
1097 * all columns being single indexed in PRIMARY or UNIQUE
1099 * f.e.
1100 * - PRIMARY(id) // id
1101 * - UNIQUE(name) // name
1102 * - PRIMARY(fk_id1, fk_id2) // NONE
1103 * - UNIQUE(x,y) // NONE
1106 * @param boolean whether to quote name with backticks ``
1107 * @return array
1109 public function getUniqueColumns($backquoted = true)
1111 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1112 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1114 $return = array();
1115 foreach ($uniques as $index) {
1116 if (count($index) > 1) {
1117 continue;
1119 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1122 return $return;
1126 * Get all indexed columns
1128 * returns an array with all columns make use of an index, in fact only
1129 * first columns in an index
1131 * f.e. index(col1, col2) would only return col1
1132 * @param boolean whether to quote name with backticks ``
1133 * @return array
1135 public function getIndexedColumns($backquoted = true)
1137 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1138 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1140 $return = array();
1141 foreach ($indexed as $column) {
1142 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1145 return $return;