Revert initial commit
[phpmyadmin/blinky.git] / libraries / Table.class.php
blobef522f96764a6079bc27ee398ba1983e3b41703a
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
5 * @version $Id$
6 * @package phpMyAdmin
7 */
9 /**
10 * @todo make use of PMA_Message and PMA_Error
11 * @package phpMyAdmin
13 class PMA_Table
16 static $cache = array();
18 /**
19 * @var string table name
21 var $name = '';
23 /**
24 * @var string database name
26 var $db_name = '';
28 /**
29 * @var string engine (innodb, myisam, bdb, ...)
31 var $engine = '';
33 /**
34 * @var string type (view, base table, system view)
36 var $type = '';
38 /**
39 * @var array settings
41 var $settings = array();
43 /**
44 * @var array errors occured
46 var $errors = array();
48 /**
49 * @var array messages
51 var $messages = array();
53 /**
54 * Constructor
56 * @param string $table_name table name
57 * @param string $db_name database name
59 function __construct($table_name, $db_name)
61 $this->setName($table_name);
62 $this->setDbName($db_name);
65 /**
66 * @see PMA_Table::getName()
68 function __toString()
70 return $this->getName();
73 function getLastError()
75 return end($this->errors);
78 function getLastMessage()
80 return end($this->messages);
83 /**
84 * sets table name
86 * @uses $this->name to set it
87 * @param string $table_name new table name
89 function setName($table_name)
91 $this->name = $table_name;
94 /**
95 * returns table name
97 * @uses $this->name as return value
98 * @param boolean whether to quote name with backticks ``
99 * @return string table name
101 function getName($backquoted = false)
103 if ($backquoted) {
104 return PMA_backquote($this->name);
106 return $this->name;
110 * sets database name for this table
112 * @uses $this->db_name to set it
113 * @param string $db_name
115 function setDbName($db_name)
117 $this->db_name = $db_name;
121 * returns database name for this table
123 * @uses $this->db_name as return value
124 * @param boolean whether to quote name with backticks ``
125 * @return string database name for this table
127 function getDbName($backquoted = false)
129 if ($backquoted) {
130 return PMA_backquote($this->db_name);
132 return $this->db_name;
136 * returns full name for table, including database name
138 * @param boolean whether to quote name with backticks ``
140 function getFullName($backquoted = false)
142 return $this->getDbName($backquoted) . '.' . $this->getName($backquoted);
145 static public function isView($db = null, $table = null)
147 if (strlen($db) && strlen($table)) {
148 return PMA_Table::_isView($db, $table);
151 if (isset($this) && strpos($this->get('TABLE TYPE'), 'VIEW')) {
152 return true;
155 return false;
159 * sets given $value for given $param
161 * @uses $this->settings to add or change value
162 * @param string param name
163 * @param mixed param value
165 function set($param, $value)
167 $this->settings[$param] = $value;
171 * returns value for given setting/param
173 * @uses $this->settings to return value
174 * @param string name for value to return
175 * @return mixed value for $param
177 function get($param)
179 if (isset($this->settings[$param])) {
180 return $this->settings[$param];
183 return null;
187 * loads structure data
188 * (this function is work in progress? not yet used)
190 function loadStructure()
192 $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
194 if (false === $table_info) {
195 return false;
198 $this->settings = $table_info;
200 if ($this->get('TABLE_ROWS') === null) {
201 $this->set('TABLE_ROWS', PMA_Table::countRecords($this->getDbName(),
202 $this->getName(), true));
205 $create_options = explode(' ', $this->get('TABLE_ROWS'));
207 // export create options by its name as variables into gloabel namespace
208 // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
209 foreach ($create_options as $each_create_option) {
210 $each_create_option = explode('=', $each_create_option);
211 if (isset($each_create_option[1])) {
212 $this->set($$each_create_option[0], $each_create_option[1]);
218 * Checks if this "table" is a view
220 * @deprecated
221 * @todo see what we could do with the possible existence of $table_is_view
222 * @param string the database name
223 * @param string the table name
225 * @return boolean whether this is a view
227 * @access public
229 static protected function _isView($db, $table)
231 // maybe we already know if the table is a view
232 if (isset($GLOBALS['tbl_is_view']) && $GLOBALS['tbl_is_view']) {
233 return true;
236 // Since phpMyAdmin 3.2 the field TABLE_TYPE is properly filled by PMA_DBI_get_tables_full()
237 $type = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_TYPE');
238 return $type == 'VIEW';
242 * Checks if this is a merge table
244 * If the ENGINE of the table is MERGE or MRG_MYISAM (alias), this is a merge table.
246 * @param string the database name
247 * @param string the table name
248 * @return boolean true if it is a merge table
249 * @access public
251 static public function isMerge($db = null, $table = null)
253 // if called static, with parameters
254 if (! empty($db) && ! empty($table)) {
255 $engine = PMA_Table::sGetStatusInfo($db, $table, 'ENGINE', null, true);
257 // if called as an object
258 // does not work yet, because $this->settings[] is not filled correctly
259 else if (! empty($this)) {
260 $engine = $this->get('ENGINE');
263 return (! empty($engine) && ((strtoupper($engine) == 'MERGE') || (strtoupper($engine) == 'MRG_MYISAM')));
266 static public function sGetToolTip($db, $table)
268 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
269 . ' (' . PMA_Table::countRecords($db, $table) . ')';
273 * Returns full table status info, or specific if $info provided
275 * this info is collected from information_schema
277 * @todo PMA_DBI_get_tables_full needs to be merged somehow into this class or at least better documented
278 * @param string $db
279 * @param string $table
280 * @param string $info
281 * @param boolean $force_read
282 * @param boolean if true, disables error message
283 * @return mixed
285 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false, $disable_error = false)
287 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
288 PMA_DBI_get_tables_full($db, $table);
291 if (! isset(PMA_Table::$cache[$db][$table])) {
292 // happens when we enter the table creation dialog
293 // or when we really did not get any status info, for example
294 // when $table == 'TABLE_NAMES' after the user tried SHOW TABLES
295 return '';
298 if (null === $info) {
299 return PMA_Table::$cache[$db][$table];
302 if (! isset(PMA_Table::$cache[$db][$table][$info])) {
303 if (! $disable_error) {
304 trigger_error('unknown table status: ' . $info, E_USER_WARNING);
306 return false;
309 return PMA_Table::$cache[$db][$table][$info];
313 * generates column/field specification for ALTER or CREATE TABLE syntax
315 * @todo move into class PMA_Column
316 * @todo on the interface, some js to clear the default value when the default
317 * current_timestamp is checked
318 * @static
319 * @param string $name name
320 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
321 * @param string $length length ('2', '5,2', '', ...)
322 * @param string $attribute
323 * @param string $collation
324 * @param string $null with 'NULL' or 'NOT NULL'
325 * @param string $default_type whether default is CURRENT_TIMESTAMP,
326 * NULL, NONE, USER_DEFINED
327 * @param boolean $default_value default value for USER_DEFINED default type
328 * @param string $extra 'AUTO_INCREMENT'
329 * @param string $comment field comment
330 * @param array &$field_primary list of fields for PRIMARY KEY
331 * @param string $index
332 * @return string field specification
334 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
335 $collation = '', $null = false, $default_type = 'USER_DEFINED',
336 $default_value = '', $extra = '', $comment = '',
337 &$field_primary, $index, $default_orig = false)
340 $is_timestamp = strpos(' ' . strtoupper($type), 'TIMESTAMP') == 1;
343 * @todo include db-name
345 $query = PMA_backquote($name) . ' ' . $type;
347 if ($length != ''
348 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT)$@i', $type)) {
349 $query .= '(' . $length . ')';
352 if ($attribute != '') {
353 $query .= ' ' . $attribute;
356 if (!empty($collation) && $collation != 'NULL'
357 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
358 $query .= PMA_generateCharsetQueryPart($collation);
361 if ($null !== false) {
362 if ($null == 'NULL') {
363 $query .= ' NULL';
364 } else {
365 $query .= ' NOT NULL';
369 switch ($default_type) {
370 case 'USER_DEFINED' :
371 if ($is_timestamp && $default_value === '0') {
372 // a TIMESTAMP does not accept DEFAULT '0'
373 // but DEFAULT 0 works
374 $query .= ' DEFAULT 0';
375 } elseif ($type == 'BIT') {
376 $query .= ' DEFAULT b\'' . preg_replace('/[^01]/', '0', $default_value) . '\'';
377 } else {
378 $query .= ' DEFAULT \'' . PMA_sqlAddslashes($default_value) . '\'';
380 break;
381 case 'NULL' :
382 case 'CURRENT_TIMESTAMP' :
383 $query .= ' DEFAULT ' . $default_type;
384 break;
385 case 'NONE' :
386 default :
387 break;
390 if (!empty($extra)) {
391 $query .= ' ' . $extra;
392 // Force an auto_increment field to be part of the primary key
393 // even if user did not tick the PK box;
394 if ($extra == 'AUTO_INCREMENT') {
395 $primary_cnt = count($field_primary);
396 if (1 == $primary_cnt) {
397 for ($j = 0; $j < $primary_cnt && $field_primary[$j] != $index; $j++) {
398 //void
400 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
401 $query .= ' PRIMARY KEY';
402 unset($field_primary[$j]);
404 // but the PK could contain other columns so do not append
405 // a PRIMARY KEY clause, just add a member to $field_primary
406 } else {
407 $found_in_pk = false;
408 for ($j = 0; $j < $primary_cnt; $j++) {
409 if ($field_primary[$j] == $index) {
410 $found_in_pk = true;
411 break;
413 } // end for
414 if (! $found_in_pk) {
415 $field_primary[] = $index;
418 } // end if (auto_increment)
420 if (!empty($comment)) {
421 $query .= " COMMENT '" . PMA_sqlAddslashes($comment) . "'";
423 return $query;
424 } // end function
427 * Counts and returns (or displays) the number of records in a table
429 * Revision 13 July 2001: Patch for limiting dump size from
430 * vinay@sanisoft.com & girish@sanisoft.com
432 * @param string the current database name
433 * @param string the current table name
434 * @param boolean whether to force an exact count
436 * @return mixed the number of records if "retain" param is true,
437 * otherwise true
439 * @access public
441 static public function countRecords($db, $table, $force_exact = false, $is_view = null)
443 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
444 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
445 } else {
446 $row_count = false;
448 if (null === $is_view) {
449 $is_view = PMA_Table::isView($db, $table);
452 if (! $force_exact) {
453 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
454 $tmp_tables = PMA_DBI_get_tables_full($db, $table);
455 if (isset($tmp_tables[$table])) {
456 PMA_Table::$cache[$db][$table] = $tmp_tables[$table];
459 if (isset(PMA_Table::$cache[$db][$table]['Rows'])) {
460 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
461 } else {
462 $row_count = false;
466 // for a VIEW, $row_count is always false at this point
467 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
468 if (! $is_view) {
469 $row_count = PMA_DBI_fetch_value(
470 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
471 . PMA_backquote($table));
472 } else {
473 // For complex views, even trying to get a partial record
474 // count could bring down a server, so we offer an
475 // alternative: setting MaxExactCountViews to 0 will bypass
476 // completely the record counting for views
478 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
479 $row_count = 0;
480 } else {
481 // Counting all rows of a VIEW could be too long, so use
482 // a LIMIT clause.
483 // Use try_query because it can fail (when a VIEW is
484 // based on a table that no longer exists)
485 $result = PMA_DBI_try_query(
486 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
487 . PMA_backquote($table) . ' LIMIT '
488 . $GLOBALS['cfg']['MaxExactCountViews'],
489 null, PMA_DBI_QUERY_STORE);
490 if (!PMA_DBI_getError()) {
491 $row_count = PMA_DBI_num_rows($result);
492 PMA_DBI_free_result($result);
496 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
500 return $row_count;
501 } // end of the 'PMA_Table::countRecords()' function
504 * @see PMA_Table::generateFieldSpec()
506 static public function generateAlter($oldcol, $newcol, $type, $length,
507 $attribute, $collation, $null, $default_type, $default_value,
508 $extra, $comment = '', &$field_primary, $index, $default_orig)
510 return PMA_backquote($oldcol) . ' '
511 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
512 $collation, $null, $default_type, $default_value, $extra,
513 $comment, $field_primary, $index, $default_orig);
514 } // end function
517 * Inserts existing entries in a PMA_* table by reading a value from an old entry
519 * @param string The array index, which Relation feature to check
520 * ('relwork', 'commwork', ...)
521 * @param string The array index, which PMA-table to update
522 * ('bookmark', 'relation', ...)
523 * @param array Which fields will be SELECT'ed from the old entry
524 * @param array Which fields will be used for the WHERE query
525 * (array('FIELDNAME' => 'FIELDVALUE'))
526 * @param array Which fields will be used as new VALUES. These are the important
527 * keys which differ from the old entry.
528 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
530 * @global string relation variable
533 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
534 $new_fields)
536 $last_id = -1;
538 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
539 $select_parts = array();
540 $row_fields = array();
541 foreach ($get_fields as $get_field) {
542 $select_parts[] = PMA_backquote($get_field);
543 $row_fields[$get_field] = 'cc';
546 $where_parts = array();
547 foreach ($where_fields as $_where => $_value) {
548 $where_parts[] = PMA_backquote($_where) . ' = \''
549 . PMA_sqlAddslashes($_value) . '\'';
552 $new_parts = array();
553 $new_value_parts = array();
554 foreach ($new_fields as $_where => $_value) {
555 $new_parts[] = PMA_backquote($_where);
556 $new_value_parts[] = PMA_sqlAddslashes($_value);
559 $table_copy_query = '
560 SELECT ' . implode(', ', $select_parts) . '
561 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
562 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
563 WHERE ' . implode(' AND ', $where_parts);
565 // must use PMA_DBI_QUERY_STORE here, since we execute another
566 // query inside the loop
567 $table_copy_rs = PMA_query_as_controluser($table_copy_query, true,
568 PMA_DBI_QUERY_STORE);
570 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
571 $value_parts = array();
572 foreach ($table_copy_row as $_key => $_val) {
573 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
574 $value_parts[] = PMA_sqlAddslashes($_val);
578 $new_table_query = '
579 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
580 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
581 (' . implode(', ', $select_parts) . ',
582 ' . implode(', ', $new_parts) . ')
583 VALUES
584 (\'' . implode('\', \'', $value_parts) . '\',
585 \'' . implode('\', \'', $new_value_parts) . '\')';
587 PMA_query_as_controluser($new_table_query);
588 $last_id = PMA_DBI_insert_id();
589 } // end while
591 PMA_DBI_free_result($table_copy_rs);
593 return $last_id;
596 return true;
597 } // end of 'PMA_Table::duplicateInfo()' function
601 * Copies or renames table
604 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
606 global $err_url;
608 /* Try moving table directly */
609 if ($move && $what == 'data') {
610 $tbl = new PMA_Table($source_table, $source_db);
611 $result = $tbl->rename($target_table, $target_db, PMA_Table::isView($source_db, $source_table));
612 if ($result) {
613 $GLOBALS['message'] = $tbl->getLastMessage();
614 return true;
618 // set export settings we need
619 $GLOBALS['sql_backquotes'] = 1;
620 $GLOBALS['asfile'] = 1;
622 // Ensure the target is valid
623 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
624 if (! $GLOBALS['pma']->databases->exists($source_db)) {
625 $GLOBALS['message'] = PMA_Message::rawError('source database `'
626 . htmlspecialchars($source_db) . '` not found');
628 if (! $GLOBALS['pma']->databases->exists($target_db)) {
629 $GLOBALS['message'] = PMA_Message::rawError('target database `'
630 . htmlspecialchars($target_db) . '` not found');
632 return false;
635 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
636 if (! isset($target_db) || ! strlen($target_db)) {
637 $target_db = $source_db;
640 // Doing a select_db could avoid some problems with replicated databases,
641 // when moving table from replicated one to not replicated one
642 PMA_DBI_select_db($target_db);
644 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
646 // do not create the table if dataonly
647 if ($what != 'dataonly') {
648 require_once './libraries/export/sql.php';
650 $no_constraints_comments = true;
651 $GLOBALS['sql_constraints_query'] = '';
653 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
654 unset($no_constraints_comments);
655 $parsed_sql = PMA_SQP_parse($sql_structure);
656 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
657 $i = 0;
658 if (empty($analyzed_sql[0]['create_table_fields'])) {
659 // this is not a CREATE TABLE, so find the first VIEW
660 $target_for_view = PMA_backquote($target_db);
661 while (true) {
662 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
663 break;
665 $i++;
668 unset($analyzed_sql);
669 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
670 // ANSI_QUOTES might be a subset of sql_mode, for example
671 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
672 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
673 $table_delimiter = 'quote_double';
674 } else {
675 $table_delimiter = 'quote_backtick';
677 unset($server_sql_mode);
679 /* Find table name in query and replace it */
680 while ($parsed_sql[$i]['type'] != $table_delimiter) {
681 $i++;
684 /* no need to PMA_backquote() */
685 if (isset($target_for_view)) {
686 // this a view definition; we just found the first db name
687 // that follows DEFINER VIEW
688 // so change it for the new db name
689 $parsed_sql[$i]['data'] = $target_for_view;
690 // then we have to find all references to the source db
691 // and change them to the target db, ensuring we stay into
692 // the $parsed_sql limits
693 $last = $parsed_sql['len'] - 1;
694 $backquoted_source_db = PMA_backquote($source_db);
695 for (++$i; $i <= $last; $i++) {
696 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
697 $parsed_sql[$i]['data'] = $target_for_view;
700 unset($last,$backquoted_source_db);
701 } else {
702 $parsed_sql[$i]['data'] = $target;
705 /* Generate query back */
706 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
707 // If table exists, and 'add drop table' is selected: Drop it!
708 $drop_query = '';
709 if (isset($GLOBALS['drop_if_exists'])
710 && $GLOBALS['drop_if_exists'] == 'true') {
711 if (PMA_Table::_isView($target_db,$target_table)) {
712 $drop_query = 'DROP VIEW';
713 } else {
714 $drop_query = 'DROP TABLE';
716 $drop_query .= ' IF EXISTS '
717 . PMA_backquote($target_db) . '.'
718 . PMA_backquote($target_table);
719 PMA_DBI_query($drop_query);
721 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
723 // If an existing table gets deleted, maintain any
724 // entries for the PMA_* tables
725 $maintain_relations = true;
728 @PMA_DBI_query($sql_structure);
729 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
731 if (($move || isset($GLOBALS['add_constraints']))
732 && !empty($GLOBALS['sql_constraints_query'])) {
733 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
734 $i = 0;
736 // find the first $table_delimiter, it must be the source table name
737 while ($parsed_sql[$i]['type'] != $table_delimiter) {
738 $i++;
739 // maybe someday we should guard against going over limit
740 //if ($i == $parsed_sql['len']) {
741 // break;
745 // replace it by the target table name, no need to PMA_backquote()
746 $parsed_sql[$i]['data'] = $target;
748 // now we must remove all $table_delimiter that follow a CONSTRAINT
749 // keyword, because a constraint name must be unique in a db
751 $cnt = $parsed_sql['len'] - 1;
753 for ($j = $i; $j < $cnt; $j++) {
754 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
755 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
756 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
757 $parsed_sql[$j+1]['data'] = '';
762 // Generate query back
763 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
764 'query_only');
765 if ($mode == 'one_table') {
766 PMA_DBI_query($GLOBALS['sql_constraints_query']);
768 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
769 if ($mode == 'one_table') {
770 unset($GLOBALS['sql_constraints_query']);
773 } else {
774 $GLOBALS['sql_query'] = '';
777 // Copy the data unless this is a VIEW
778 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
779 $sql_insert_data =
780 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
781 PMA_DBI_query($sql_insert_data);
782 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
785 require_once './libraries/relation.lib.php';
786 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
788 // Drops old table if the user has requested to move it
789 if ($move) {
791 // This could avoid some problems with replicated databases, when
792 // moving table from replicated one to not replicated one
793 PMA_DBI_select_db($source_db);
795 if (PMA_Table::_isView($source_db,$source_table)) {
796 $sql_drop_query = 'DROP VIEW';
797 } else {
798 $sql_drop_query = 'DROP TABLE';
800 $sql_drop_query .= ' ' . $source;
801 PMA_DBI_query($sql_drop_query);
803 // Move old entries from PMA-DBs to new table
804 if ($GLOBALS['cfgRelation']['commwork']) {
805 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
806 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
807 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
808 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
809 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
810 PMA_query_as_controluser($remove_query);
811 unset($remove_query);
814 // updating bookmarks is not possible since only a single table is moved,
815 // and not the whole DB.
817 if ($GLOBALS['cfgRelation']['displaywork']) {
818 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
819 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
820 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
821 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
822 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
823 PMA_query_as_controluser($table_query);
824 unset($table_query);
827 if ($GLOBALS['cfgRelation']['relwork']) {
828 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
829 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
830 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
831 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
832 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
833 PMA_query_as_controluser($table_query);
834 unset($table_query);
836 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
837 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
838 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
839 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
840 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
841 PMA_query_as_controluser($table_query);
842 unset($table_query);
846 * @todo Can't get moving PDFs the right way. The page numbers
847 * always get screwed up independently from duplication because the
848 * numbers do not seem to be stored on a per-database basis. Would
849 * the author of pdf support please have a look at it?
852 if ($GLOBALS['cfgRelation']['pdfwork']) {
853 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
854 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
855 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
856 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
857 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
858 PMA_query_as_controluser($table_query);
859 unset($table_query);
861 $pdf_query = 'SELECT pdf_page_number '
862 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
863 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
864 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
865 $pdf_rs = PMA_query_as_controluser($pdf_query);
867 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
868 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
869 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
870 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
871 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
872 $tb_rs = PMA_query_as_controluser($table_query);
873 unset($table_query);
874 unset($tb_rs);
879 if ($GLOBALS['cfgRelation']['designerwork']) {
880 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
881 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
882 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
883 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
884 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
885 PMA_query_as_controluser($table_query);
886 unset($table_query);
889 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
890 // end if ($move)
891 } else {
892 // we are copying
893 // Create new entries as duplicates from old PMA DBs
894 if ($what != 'dataonly' && !isset($maintain_relations)) {
895 if ($GLOBALS['cfgRelation']['commwork']) {
896 // Get all comments and MIME-Types for current table
897 $comments_copy_query = 'SELECT
898 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
899 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
900 WHERE
901 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
902 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
903 $comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
905 // Write every comment as new copied entry. [MIME]
906 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
907 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
908 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
909 . ' VALUES('
910 . '\'' . PMA_sqlAddslashes($target_db) . '\','
911 . '\'' . PMA_sqlAddslashes($target_table) . '\','
912 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
913 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
914 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
915 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
916 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
917 . ')';
918 PMA_query_as_controluser($new_comment_query);
919 } // end while
920 PMA_DBI_free_result($comments_copy_rs);
921 unset($comments_copy_rs);
924 // duplicating the bookmarks must not be done here, but
925 // just once per db
927 $get_fields = array('display_field');
928 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
929 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
930 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
934 * @todo revise this code when we support cross-db relations
936 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
937 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
938 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
939 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
942 $get_fields = array('foreign_field', 'master_table', 'master_field');
943 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
944 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
945 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
948 $get_fields = array('x', 'y', 'v', 'h');
949 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
950 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
951 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
954 * @todo Can't get duplicating PDFs the right way. The
955 * page numbers always get screwed up independently from
956 * duplication because the numbers do not seem to be stored on a
957 * per-database basis. Would the author of pdf support please
958 * have a look at it?
960 $get_fields = array('page_descr');
961 $where_fields = array('db_name' => $source_db);
962 $new_fields = array('db_name' => $target_db);
963 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
965 if (isset($last_id) && $last_id >= 0) {
966 $get_fields = array('x', 'y');
967 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
968 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
969 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
974 return true;
978 * checks if given name is a valid table name,
979 * currently if not empty, trailing spaces, '.', '/' and '\'
981 * @todo add check for valid chars in filename on current system/os
982 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
983 * @param string $table_name name to check
984 * @return boolean whether the string is valid or not
986 function isValidName($table_name)
988 if ($table_name !== trim($table_name)) {
989 // trailing spaces
990 return false;
993 if (! strlen($table_name)) {
994 // zero length
995 return false;
998 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
999 // illegal char . / \
1000 return false;
1003 return true;
1007 * renames table
1009 * @param string new table name
1010 * @param string new database name
1011 * @param boolean is this for a VIEW rename?
1012 * @return boolean success
1014 function rename($new_name, $new_db = null, $is_view = false)
1016 if (null !== $new_db && $new_db !== $this->getDbName()) {
1017 // Ensure the target is valid
1018 if (! $GLOBALS['pma']->databases->exists($new_db)) {
1019 $this->errors[] = __('Invalid database') . ': ' . $new_db;
1020 return false;
1022 } else {
1023 $new_db = $this->getDbName();
1026 $new_table = new PMA_Table($new_name, $new_db);
1028 if ($this->getFullName() === $new_table->getFullName()) {
1029 return true;
1032 if (! PMA_Table::isValidName($new_name)) {
1033 $this->errors[] = __('Invalid table name') . ': ' . $new_table->getFullName();
1034 return false;
1037 if (! $is_view) {
1038 $GLOBALS['sql_query'] = '
1039 RENAME TABLE ' . $this->getFullName(true) . '
1040 TO ' . $new_table->getFullName(true) . ';';
1041 } else {
1042 $GLOBALS['sql_query'] = '
1043 ALTER TABLE ' . $this->getFullName(true) . '
1044 RENAME ' . $new_table->getFullName(true) . ';';
1046 // I don't think a specific error message for views is necessary
1047 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1048 $this->errors[] = sprintf(__('Error renaming table %1$s to %2$s'), $this->getFullName(), $new_table->getFullName());
1049 return false;
1052 $old_name = $this->getName();
1053 $old_db = $this->getDbName();
1054 $this->setName($new_name);
1055 $this->setDbName($new_db);
1058 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1060 // Move old entries from comments to new table
1061 require_once './libraries/relation.lib.php';
1062 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1063 if ($GLOBALS['cfgRelation']['commwork']) {
1064 $remove_query = '
1065 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1066 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
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($remove_query);
1072 unset($remove_query);
1075 if ($GLOBALS['cfgRelation']['displaywork']) {
1076 $table_query = '
1077 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1078 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
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 if ($GLOBALS['cfgRelation']['relwork']) {
1088 $table_query = '
1089 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1090 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1091 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1092 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1093 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1094 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1095 PMA_query_as_controluser($table_query);
1097 $table_query = '
1098 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1099 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1100 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1101 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1102 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1103 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1104 PMA_query_as_controluser($table_query);
1105 unset($table_query);
1108 if ($GLOBALS['cfgRelation']['pdfwork']) {
1109 $table_query = '
1110 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1111 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1112 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1113 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1114 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1115 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1116 PMA_query_as_controluser($table_query);
1117 unset($table_query);
1120 if ($GLOBALS['cfgRelation']['designerwork']) {
1121 $table_query = '
1122 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1123 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1124 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1125 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1126 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1127 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1128 PMA_query_as_controluser($table_query);
1129 unset($table_query);
1132 $this->messages[] = sprintf(__('Table %s has been renamed to %s'),
1133 htmlspecialchars($old_name), htmlspecialchars($new_name));
1134 return true;
1138 * Get all unique columns
1140 * returns an array with all columns with unqiue content, in fact these are
1141 * all columns being single indexed in PRIMARY or UNIQUE
1143 * f.e.
1144 * - PRIMARY(id) // id
1145 * - UNIQUE(name) // name
1146 * - PRIMARY(fk_id1, fk_id2) // NONE
1147 * - UNIQUE(x,y) // NONE
1150 * @param boolean whether to quote name with backticks ``
1151 * @return array
1153 public function getUniqueColumns($backquoted = true)
1155 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1156 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1158 $return = array();
1159 foreach ($uniques as $index) {
1160 if (count($index) > 1) {
1161 continue;
1163 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($index[0]) : $index[0]);
1166 return $return;
1170 * Get all indexed columns
1172 * returns an array with all columns make use of an index, in fact only
1173 * first columns in an index
1175 * f.e. index(col1, col2) would only return col1
1176 * @param boolean whether to quote name with backticks ``
1177 * @return array
1179 public function getIndexedColumns($backquoted = true)
1181 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1182 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1184 $return = array();
1185 foreach ($indexed as $column) {
1186 $return[] = $this->getFullName($backquoted) . '.' . ($backquoted ? PMA_backquote($column) : $column);
1189 return $return;