3.3.0-rc2
[phpmyadmin/madhuracj.git] / libraries / Table.class.php
blobb1f01df75b8ebd6cd7b21f3aa3b70dd9066c752d
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 PMA_Table::$cache[$db][$table] = PMA_DBI_fetch_single_row('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table, true) . '\'');
428 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
431 // for a VIEW, $row_count is always false at this point
432 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
433 if (! $is_view) {
434 $row_count = PMA_DBI_fetch_value(
435 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
436 . PMA_backquote($table));
437 } else {
438 // For complex views, even trying to get a partial record
439 // count could bring down a server, so we offer an
440 // alternative: setting MaxExactCountViews to 0 will bypass
441 // completely the record counting for views
443 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
444 $row_count = 0;
445 } else {
446 // Counting all rows of a VIEW could be too long, so use
447 // a LIMIT clause.
448 // Use try_query because it can fail (when a VIEW is
449 // based on a table that no longer exists)
450 $result = PMA_DBI_try_query(
451 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
452 . PMA_backquote($table) . ' LIMIT '
453 . $GLOBALS['cfg']['MaxExactCountViews'],
454 null, PMA_DBI_QUERY_STORE);
455 if (!PMA_DBI_getError()) {
456 $row_count = PMA_DBI_num_rows($result);
457 PMA_DBI_free_result($result);
461 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
465 return $row_count;
466 } // end of the 'PMA_Table::countRecords()' function
469 * @see PMA_Table::generateFieldSpec()
471 static public function generateAlter($oldcol, $newcol, $type, $length,
472 $attribute, $collation, $null, $default_type, $default_value,
473 $extra, $comment = '', &$field_primary, $index, $default_orig)
475 return PMA_backquote($oldcol) . ' '
476 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
477 $collation, $null, $default_type, $default_value, $extra,
478 $comment, $field_primary, $index, $default_orig);
479 } // end function
482 * Inserts existing entries in a PMA_* table by reading a value from an old entry
484 * @param string The array index, which Relation feature to check
485 * ('relwork', 'commwork', ...)
486 * @param string The array index, which PMA-table to update
487 * ('bookmark', 'relation', ...)
488 * @param array Which fields will be SELECT'ed from the old entry
489 * @param array Which fields will be used for the WHERE query
490 * (array('FIELDNAME' => 'FIELDVALUE'))
491 * @param array Which fields will be used as new VALUES. These are the important
492 * keys which differ from the old entry.
493 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
495 * @global string relation variable
497 * @author Garvin Hicking <me@supergarv.de>
499 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
500 $new_fields)
502 $last_id = -1;
504 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
505 $select_parts = array();
506 $row_fields = array();
507 foreach ($get_fields as $get_field) {
508 $select_parts[] = PMA_backquote($get_field);
509 $row_fields[$get_field] = 'cc';
512 $where_parts = array();
513 foreach ($where_fields as $_where => $_value) {
514 $where_parts[] = PMA_backquote($_where) . ' = \''
515 . PMA_sqlAddslashes($_value) . '\'';
518 $new_parts = array();
519 $new_value_parts = array();
520 foreach ($new_fields as $_where => $_value) {
521 $new_parts[] = PMA_backquote($_where);
522 $new_value_parts[] = PMA_sqlAddslashes($_value);
525 $table_copy_query = '
526 SELECT ' . implode(', ', $select_parts) . '
527 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
528 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
529 WHERE ' . implode(' AND ', $where_parts);
531 // must use PMA_DBI_QUERY_STORE here, since we execute another
532 // query inside the loop
533 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
534 PMA_DBI_QUERY_STORE);
536 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
537 $value_parts = array();
538 foreach ($table_copy_row as $_key => $_val) {
539 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
540 $value_parts[] = PMA_sqlAddslashes($_val);
544 $new_table_query = '
545 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
546 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
547 (' . implode(', ', $select_parts) . ',
548 ' . implode(', ', $new_parts) . ')
549 VALUES
550 (\'' . implode('\', \'', $value_parts) . '\',
551 \'' . implode('\', \'', $new_value_parts) . '\')';
553 PMA_query_as_controluser($new_table_query);
554 $last_id = PMA_DBI_insert_id();
555 } // end while
557 PMA_DBI_free_result($table_copy_rs);
559 return $last_id;
562 return true;
563 } // end of 'PMA_Table::duplicateInfo()' function
567 * Copies or renames table
568 * @todo use RENAME for move operations
569 * - would work only if the databases are on the same filesystem,
570 * how can we check that? try the operation and
571 * catch an error?
572 * - for views, only if MYSQL > 50013
573 * - still have to handle pmadb synch.
575 * @author Michal Cihar <michal@cihar.com>
577 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
579 global $err_url;
581 // set export settings we need
582 $GLOBALS['sql_backquotes'] = 1;
583 $GLOBALS['asfile'] = 1;
585 // Ensure the target is valid
586 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
587 if (! $GLOBALS['pma']->databases->exists($source_db)) {
588 $GLOBALS['message'] = PMA_Message::rawError('source database `'
589 . htmlspecialchars($source_db) . '` not found');
591 if (! $GLOBALS['pma']->databases->exists($target_db)) {
592 $GLOBALS['message'] = PMA_Message::rawError('target database `'
593 . htmlspecialchars($target_db) . '` not found');
595 return false;
598 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
599 if (! isset($target_db) || ! strlen($target_db)) {
600 $target_db = $source_db;
603 // Doing a select_db could avoid some problems with replicated databases,
604 // when moving table from replicated one to not replicated one
605 PMA_DBI_select_db($target_db);
607 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
609 // do not create the table if dataonly
610 if ($what != 'dataonly') {
611 require_once './libraries/export/sql.php';
613 $no_constraints_comments = true;
614 $GLOBALS['sql_constraints_query'] = '';
616 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
617 unset($no_constraints_comments);
618 $parsed_sql = PMA_SQP_parse($sql_structure);
619 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
620 $i = 0;
621 if (empty($analyzed_sql[0]['create_table_fields'])) {
622 // this is not a CREATE TABLE, so find the first VIEW
623 $target_for_view = PMA_backquote($target_db);
624 while (true) {
625 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
626 break;
628 $i++;
631 unset($analyzed_sql);
632 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
633 // ANSI_QUOTES might be a subset of sql_mode, for example
634 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
635 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
636 $table_delimiter = 'quote_double';
637 } else {
638 $table_delimiter = 'quote_backtick';
640 unset($server_sql_mode);
642 /* nijel: Find table name in query and replace it */
643 while ($parsed_sql[$i]['type'] != $table_delimiter) {
644 $i++;
647 /* no need to PMA_backquote() */
648 if (isset($target_for_view)) {
649 // this a view definition; we just found the first db name
650 // that follows DEFINER VIEW
651 // so change it for the new db name
652 $parsed_sql[$i]['data'] = $target_for_view;
653 // then we have to find all references to the source db
654 // and change them to the target db, ensuring we stay into
655 // the $parsed_sql limits
656 $last = $parsed_sql['len'] - 1;
657 $backquoted_source_db = PMA_backquote($source_db);
658 for (++$i; $i <= $last; $i++) {
659 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
660 $parsed_sql[$i]['data'] = $target_for_view;
663 unset($last,$backquoted_source_db);
664 } else {
665 $parsed_sql[$i]['data'] = $target;
668 /* Generate query back */
669 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
670 // If table exists, and 'add drop table' is selected: Drop it!
671 $drop_query = '';
672 if (isset($GLOBALS['drop_if_exists'])
673 && $GLOBALS['drop_if_exists'] == 'true') {
674 if (PMA_Table::_isView($target_db,$target_table)) {
675 $drop_query = 'DROP VIEW';
676 } else {
677 $drop_query = 'DROP TABLE';
679 $drop_query .= ' IF EXISTS '
680 . PMA_backquote($target_db) . '.'
681 . PMA_backquote($target_table);
682 PMA_DBI_query($drop_query);
684 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
686 // garvin: If an existing table gets deleted, maintain any
687 // entries for the PMA_* tables
688 $maintain_relations = true;
691 @PMA_DBI_query($sql_structure);
692 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
694 if (($move || isset($GLOBALS['add_constraints']))
695 && !empty($GLOBALS['sql_constraints_query'])) {
696 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
697 $i = 0;
699 // find the first $table_delimiter, it must be the source table name
700 while ($parsed_sql[$i]['type'] != $table_delimiter) {
701 $i++;
702 // maybe someday we should guard against going over limit
703 //if ($i == $parsed_sql['len']) {
704 // break;
708 // replace it by the target table name, no need to PMA_backquote()
709 $parsed_sql[$i]['data'] = $target;
711 // now we must remove all $table_delimiter that follow a CONSTRAINT
712 // keyword, because a constraint name must be unique in a db
714 $cnt = $parsed_sql['len'] - 1;
716 for ($j = $i; $j < $cnt; $j++) {
717 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
718 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
719 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
720 $parsed_sql[$j+1]['data'] = '';
725 // Generate query back
726 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
727 'query_only');
728 if ($mode == 'one_table') {
729 PMA_DBI_query($GLOBALS['sql_constraints_query']);
731 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
732 if ($mode == 'one_table') {
733 unset($GLOBALS['sql_constraints_query']);
736 } else {
737 $GLOBALS['sql_query'] = '';
740 // Copy the data unless this is a VIEW
741 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
742 $sql_insert_data =
743 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
744 PMA_DBI_query($sql_insert_data);
745 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
748 require_once './libraries/relation.lib.php';
749 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
751 // Drops old table if the user has requested to move it
752 if ($move) {
754 // This could avoid some problems with replicated databases, when
755 // moving table from replicated one to not replicated one
756 PMA_DBI_select_db($source_db);
758 if (PMA_Table::_isView($source_db,$source_table)) {
759 $sql_drop_query = 'DROP VIEW';
760 } else {
761 $sql_drop_query = 'DROP TABLE';
763 $sql_drop_query .= ' ' . $source;
764 PMA_DBI_query($sql_drop_query);
766 // garvin: Move old entries from PMA-DBs to new table
767 if ($GLOBALS['cfgRelation']['commwork']) {
768 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
769 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
770 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
771 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
772 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
773 PMA_query_as_controluser($remove_query);
774 unset($remove_query);
777 // garvin: updating bookmarks is not possible since only a single table is moved,
778 // and not the whole DB.
780 if ($GLOBALS['cfgRelation']['displaywork']) {
781 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
782 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
783 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
784 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
785 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
786 PMA_query_as_controluser($table_query);
787 unset($table_query);
790 if ($GLOBALS['cfgRelation']['relwork']) {
791 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
792 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
793 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
794 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
795 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
796 PMA_query_as_controluser($table_query);
797 unset($table_query);
799 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
800 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
801 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
802 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
803 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
804 PMA_query_as_controluser($table_query);
805 unset($table_query);
809 * @todo garvin: Can't get moving PDFs the right way. The page numbers
810 * always get screwed up independently from duplication because the
811 * numbers do not seem to be stored on a per-database basis. Would
812 * the author of pdf support please have a look at it?
815 if ($GLOBALS['cfgRelation']['pdfwork']) {
816 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
817 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
818 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
819 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
820 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
821 PMA_query_as_controluser($table_query);
822 unset($table_query);
824 $pdf_query = 'SELECT pdf_page_number '
825 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
826 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
827 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
828 $pdf_rs = PMA_query_as_controluser($pdf_query);
830 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
831 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
832 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
833 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
834 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
835 $tb_rs = PMA_query_as_controluser($table_query);
836 unset($table_query);
837 unset($tb_rs);
842 if ($GLOBALS['cfgRelation']['designerwork']) {
843 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
844 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
845 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
846 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
847 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
848 PMA_query_as_controluser($table_query);
849 unset($table_query);
852 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
853 // end if ($move)
854 } else {
855 // we are copying
856 // garvin: Create new entries as duplicates from old PMA DBs
857 if ($what != 'dataonly' && !isset($maintain_relations)) {
858 if ($GLOBALS['cfgRelation']['commwork']) {
859 // Get all comments and MIME-Types for current table
860 $comments_copy_query = 'SELECT
861 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
862 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
863 WHERE
864 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
865 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
866 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
868 // Write every comment as new copied entry. [MIME]
869 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
870 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
871 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
872 . ' VALUES('
873 . '\'' . PMA_sqlAddslashes($target_db) . '\','
874 . '\'' . PMA_sqlAddslashes($target_table) . '\','
875 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
876 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
877 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
878 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
879 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
880 . ')';
881 PMA_query_as_controluser($new_comment_query);
882 } // end while
883 PMA_DBI_free_result($comments_copy_rs);
884 unset($comments_copy_rs);
887 // duplicating the bookmarks must not be done here, but
888 // just once per db
890 $get_fields = array('display_field');
891 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
892 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
893 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
897 * @todo revise this code when we support cross-db relations
899 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
900 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
901 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
902 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
905 $get_fields = array('foreign_field', 'master_table', 'master_field');
906 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
907 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
908 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
911 $get_fields = array('x', 'y', 'v', 'h');
912 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
913 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
914 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
917 * @todo garvin: Can't get duplicating PDFs the right way. The
918 * page numbers always get screwed up independently from
919 * duplication because the numbers do not seem to be stored on a
920 * per-database basis. Would the author of pdf support please
921 * have a look at it?
923 $get_fields = array('page_descr');
924 $where_fields = array('db_name' => $source_db);
925 $new_fields = array('db_name' => $target_db);
926 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
928 if (isset($last_id) && $last_id >= 0) {
929 $get_fields = array('x', 'y');
930 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
931 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
932 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
937 return true;
941 * checks if given name is a valid table name,
942 * currently if not empty, trailing spaces, '.', '/' and '\'
944 * @todo add check for valid chars in filename on current system/os
945 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
946 * @param string $table_name name to check
947 * @return boolean whether the string is valid or not
949 function isValidName($table_name)
951 if ($table_name !== trim($table_name)) {
952 // trailing spaces
953 return false;
956 if (! strlen($table_name)) {
957 // zero length
958 return false;
961 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
962 // illegal char . / \
963 return false;
966 return true;
970 * renames table
972 * @param string new table name
973 * @param string new database name
974 * @return boolean success
976 function rename($new_name, $new_db = null)
978 if (null !== $new_db && $new_db !== $this->getDbName()) {
979 // Ensure the target is valid
980 if (! $GLOBALS['pma']->databases->exists($new_db)) {
981 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
982 return false;
984 } else {
985 $new_db = $this->getDbName();
988 $new_table = new PMA_Table($new_name, $new_db);
990 if ($this->getFullName() === $new_table->getFullName()) {
991 return true;
994 if (! PMA_Table::isValidName($new_name)) {
995 $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
996 return false;
999 $GLOBALS['sql_query'] = '
1000 RENAME TABLE ' . $this->getFullName(true) . '
1001 TO ' . $new_table->getFullName(true) . ';';
1002 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1003 $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
1004 return false;
1007 $old_name = $this->getName();
1008 $old_db = $this->getDbName();
1009 $this->setName($new_name);
1010 $this->setDbName($new_db);
1013 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1015 // garvin: Move old entries from comments to new table
1016 require_once './libraries/relation.lib.php';
1017 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1018 if ($GLOBALS['cfgRelation']['commwork']) {
1019 $remove_query = '
1020 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1021 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1022 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1023 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1024 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1025 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1026 PMA_query_as_controluser($remove_query);
1027 unset($remove_query);
1030 if ($GLOBALS['cfgRelation']['displaywork']) {
1031 $table_query = '
1032 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1033 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1034 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1035 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1036 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1037 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1038 PMA_query_as_controluser($table_query);
1039 unset($table_query);
1042 if ($GLOBALS['cfgRelation']['relwork']) {
1043 $table_query = '
1044 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1045 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1046 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1047 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1048 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1049 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1050 PMA_query_as_controluser($table_query);
1052 $table_query = '
1053 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1054 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1055 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1056 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1057 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1058 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1059 PMA_query_as_controluser($table_query);
1060 unset($table_query);
1063 if ($GLOBALS['cfgRelation']['pdfwork']) {
1064 $table_query = '
1065 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1066 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1067 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1068 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1069 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1070 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1071 PMA_query_as_controluser($table_query);
1072 unset($table_query);
1075 if ($GLOBALS['cfgRelation']['designerwork']) {
1076 $table_query = '
1077 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1078 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1079 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1080 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1081 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1082 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1083 PMA_query_as_controluser($table_query);
1084 unset($table_query);
1087 $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
1088 htmlspecialchars($old_name), htmlspecialchars($new_name));
1089 return true;
1093 * Get all unique columns
1095 * returns an array with all columns with unqiue content, in fact these are
1096 * all columns being single indexed in PRIMARY or UNIQUE
1098 * f.e.
1099 * - PRIMARY(id) // id
1100 * - UNIQUE(name) // name
1101 * - PRIMARY(fk_id1, fk_id2) // NONE
1102 * - UNIQUE(x,y) // NONE
1105 * @param boolean whether to quote name with backticks ``
1106 * @return array
1108 public function getUniqueColumns($backquoted = true)
1110 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1111 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1113 $return = array();
1114 foreach ($uniques as $index) {
1115 if (count($index) > 1) {
1116 continue;
1118 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1121 return $return;
1125 * Get all indexed columns
1127 * returns an array with all columns make use of an index, in fact only
1128 * first columns in an index
1130 * f.e. index(col1, col2) would only return col1
1131 * @param boolean whether to quote name with backticks ``
1132 * @return array
1134 public function getIndexedColumns($backquoted = true)
1136 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1137 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1139 $return = array();
1140 foreach ($indexed as $column) {
1141 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1144 return $return;