bug #2491017 [operations] ANSI mode not supported (db rename and table move)
[phpmyadmin/crack.git] / libraries / Table.class.php
blob6b164d27a819da2858cae2ce46b91e9d12252e92
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
5 * @version $Id$
6 */
8 /**
9 * @todo make use of PMA_Message and PMA_Error
11 class PMA_Table
14 static $cache = array();
16 /**
17 * @var string table name
19 var $name = '';
21 /**
22 * @var string database name
24 var $db_name = '';
26 /**
27 * @var string engine (innodb, myisam, bdb, ...)
29 var $engine = '';
31 /**
32 * @var string type (view, base table, system view)
34 var $type = '';
36 /**
37 * @var array settings
39 var $settings = array();
41 /**
42 * @var array errors occured
44 var $errors = array();
46 /**
47 * @var array messages
49 var $messages = array();
51 /**
52 * Constructor
54 * @param string $table_name table name
55 * @param string $db_name database name
57 function __construct($table_name, $db_name)
59 $this->setName($table_name);
60 $this->setDbName($db_name);
63 /**
64 * @see PMA_Table::getName()
66 function __toString()
68 return $this->getName();
71 function getLastError()
73 return end($this->errors);
76 function getLastMessage()
78 return end($this->messages);
81 /**
82 * sets table name
84 * @uses $this->name to set it
85 * @param string $table_name new table name
87 function setName($table_name)
89 $this->name = $table_name;
92 /**
93 * returns table name
95 * @uses $this->name as return value
96 * @param boolean whether to quote name with backticks ``
97 * @return string table name
99 function getName($quoted = false)
101 if ($quoted) {
102 return PMA_backquote($this->name);
104 return $this->name;
108 * sets database name for this table
110 * @uses $this->db_name to set it
111 * @param string $db_name
113 function setDbName($db_name)
115 $this->db_name = $db_name;
119 * returns database name for this table
121 * @uses $this->db_name as return value
122 * @param boolean whether to quote name with backticks ``
123 * @return string database name for this table
125 function getDbName($quoted = false)
127 if ($quoted) {
128 return PMA_backquote($this->db_name);
130 return $this->db_name;
134 * returns full name for table, including database name
136 * @param boolean whether to quote name with backticks ``
138 function getFullName($quoted = false)
140 return $this->getDbName($quoted) . '.' . $this->getName($quoted);
143 static public function isView($db = null, $table = null)
145 if (strlen($db) && strlen($table)) {
146 return PMA_Table::_isView($db, $table);
149 if (isset($this) && strpos($this->get('TABLE TYPE'), 'VIEW')) {
150 return true;
153 return false;
157 * sets given $value for given $param
159 * @uses $this->settings to add or change value
160 * @param string param name
161 * @param mixed param value
163 function set($param, $value)
165 $this->settings[$param] = $value;
169 * returns value for given setting/param
171 * @uses $this->settings to return value
172 * @param string name for value to return
173 * @return mixed value for $param
175 function get($param)
177 if (isset($this->settings[$param])) {
178 return $this->settings[$param];
181 return null;
185 * loads structure data
186 * (this function is work in progress? not yet used)
188 function loadStructure()
190 $table_info = PMA_DBI_get_tables_full($this->getDbName(), $this->getName());
192 if (false === $table_info) {
193 return false;
196 $this->settings = $table_info;
198 if ($this->get('TABLE_ROWS') === null) {
199 $this->set('TABLE_ROWS', PMA_Table::countRecords($this->getDbName(),
200 $this->getName(), true, true));
203 $create_options = explode(' ', $this->get('TABLE_ROWS'));
205 // export create options by its name as variables into gloabel namespace
206 // f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
207 foreach ($create_options as $each_create_option) {
208 $each_create_option = explode('=', $each_create_option);
209 if (isset($each_create_option[1])) {
210 $this->set($$each_create_option[0], $each_create_option[1]);
216 * Checks if this "table" is a view
218 * @deprecated
219 * @todo see what we could do with the possible existence of $table_is_view
220 * @param string the database name
221 * @param string the table name
223 * @return boolean whether this is a view
225 * @access public
227 static protected function _isView($db, $table)
229 // maybe we already know if the table is a view
230 if (isset($GLOBALS['tbl_is_view']) && $GLOBALS['tbl_is_view']) {
231 return true;
234 // This would be the correct way of doing the check but at least in
235 // MySQL 5.0.33 it's too slow when there are hundreds of databases
236 // and/or tables (more than 3 minutes for 400 tables)
237 /*if (false === PMA_DBI_fetch_value('SELECT TABLE_NAME FROM `information_schema`.`VIEWS` WHERE `TABLE_SCHEMA` = \'' . $db . '\' AND `TABLE_NAME` = \'' . $table . '\';')) {
238 return false;
239 } else {
240 return true;
241 } */
242 // A more complete verification would be to check if all columns
243 // from the result set are NULL except Name and Comment.
244 // MySQL from 5.0.0 to 5.0.12 returns 'view',
245 // from 5.0.13 returns 'VIEW'.
246 // use substr() because the comment might contain something like:
247 // (VIEW 'BASE2.VTEST' REFERENCES INVALID TABLE(S) OR COLUMN(S) OR FUNCTION)
248 $comment = strtoupper(PMA_Table::sGetStatusInfo($db, $table, 'Comment'));
249 return substr($comment, 0, 4) == 'VIEW';
252 static public function sGetToolTip($db, $table)
254 return PMA_Table::sGetStatusInfo($db, $table, 'Comment')
255 . ' (' . PMA_Table::countRecords($db, $table, true) . ')';
258 static public function sGetStatusInfo($db, $table, $info = null, $force_read = false)
260 if (! isset(PMA_Table::$cache[$db][$table]) || $force_read) {
261 PMA_Table::$cache[$db][$table] = PMA_DBI_fetch_single_row('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . $table . '\'');
264 if (null === $info) {
265 return PMA_Table::$cache[$db][$table];
268 if (! isset(PMA_Table::$cache[$db][$table][$info]) || $force_read) {
269 PMA_Table::$cache[$db][$table] = PMA_DBI_fetch_single_row('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . $table . '\'');
271 return PMA_Table::$cache[$db][$table][$info];
275 * generates column/field specification for ALTER or CREATE TABLE syntax
277 * @todo move into class PMA_Column
278 * @todo on the interface, some js to clear the default value when the default
279 * current_timestamp is checked
280 * @static
281 * @param string $name name
282 * @param string $type type ('INT', 'VARCHAR', 'BIT', ...)
283 * @param string $length length ('2', '5,2', '', ...)
284 * @param string $attribute
285 * @param string $collation
286 * @param string $null with 'NULL' or 'NOT NULL'
287 * @param string $default_type whether default is CURRENT_TIMESTAMP,
288 * NULL, NONE, USER_DEFINED
289 * @param boolean $default_value default value for USER_DEFINED default type
290 * @param string $extra 'AUTO_INCREMENT'
291 * @param string $comment field comment
292 * @param array &$field_primary list of fields for PRIMARY KEY
293 * @param string $index
294 * @return string field specification
296 static function generateFieldSpec($name, $type, $length = '', $attribute = '',
297 $collation = '', $null = false, $default_type = 'USER_DEFINED',
298 $default_value = '', $extra = '', $comment = '',
299 &$field_primary, $index, $default_orig = false)
302 $is_timestamp = strpos(' ' . strtoupper($type), 'TIMESTAMP') == 1;
305 * @todo include db-name
307 $query = PMA_backquote($name) . ' ' . $type;
309 if ($length != ''
310 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT)$@i', $type)) {
311 $query .= '(' . $length . ')';
314 if ($attribute != '') {
315 $query .= ' ' . $attribute;
318 if (!empty($collation) && $collation != 'NULL'
319 && preg_match('@^(TINYTEXT|TEXT|MEDIUMTEXT|LONGTEXT|VARCHAR|CHAR|ENUM|SET)$@i', $type)) {
320 $query .= PMA_generateCharsetQueryPart($collation);
323 if ($null !== false) {
324 if ($null == 'NULL') {
325 $query .= ' NULL';
326 } else {
327 $query .= ' NOT NULL';
331 switch ($default_type) {
332 case 'USER_DEFINED' :
333 if ($is_timestamp && $default_value === '0') {
334 // a TIMESTAMP does not accept DEFAULT '0'
335 // but DEFAULT 0 works
336 $query .= ' DEFAULT 0';
337 } elseif ($type == 'BIT') {
338 $query .= ' DEFAULT b\'' . preg_replace('/[^01]/', '0', $default_value) . '\'';
339 } else {
340 $query .= ' DEFAULT \'' . PMA_sqlAddslashes($default_value) . '\'';
342 break;
343 case 'NULL' :
344 case 'CURRENT_TIMESTAMP' :
345 $query .= ' DEFAULT ' . $default_type;
346 break;
347 case 'NONE' :
348 default :
349 break;
352 if (!empty($extra)) {
353 $query .= ' ' . $extra;
354 // Force an auto_increment field to be part of the primary key
355 // even if user did not tick the PK box;
356 if ($extra == 'AUTO_INCREMENT') {
357 $primary_cnt = count($field_primary);
358 if (1 == $primary_cnt) {
359 for ($j = 0; $j < $primary_cnt && $field_primary[$j] != $index; $j++) {
360 //void
362 if (isset($field_primary[$j]) && $field_primary[$j] == $index) {
363 $query .= ' PRIMARY KEY';
364 unset($field_primary[$j]);
366 // but the PK could contain other columns so do not append
367 // a PRIMARY KEY clause, just add a member to $field_primary
368 } else {
369 $found_in_pk = false;
370 for ($j = 0; $j < $primary_cnt; $j++) {
371 if ($field_primary[$j] == $index) {
372 $found_in_pk = true;
373 break;
375 } // end for
376 if (! $found_in_pk) {
377 $field_primary[] = $index;
380 } // end if (auto_increment)
382 if (!empty($comment)) {
383 $query .= " COMMENT '" . PMA_sqlAddslashes($comment) . "'";
385 return $query;
386 } // end function
389 * Counts and returns (or displays) the number of records in a table
391 * Revision 13 July 2001: Patch for limiting dump size from
392 * vinay@sanisoft.com & girish@sanisoft.com
394 * @param string the current database name
395 * @param string the current table name
396 * @param boolean whether to retain or to displays the result
397 * @param boolean whether to force an exact count
399 * @return mixed the number of records if "retain" param is true,
400 * otherwise true
402 * @access public
404 static public function countRecords($db, $table, $ret = false,
405 $force_exact = false, $is_view = null)
407 if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
408 $row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
409 } else {
410 $row_count = false;
412 if (null === $is_view) {
413 $is_view = PMA_Table::isView($db, $table);
416 if (! $force_exact) {
417 if (! isset(PMA_Table::$cache[$db][$table]['Rows']) && ! $is_view) {
418 PMA_Table::$cache[$db][$table] = PMA_DBI_fetch_single_row('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddslashes($table, true) . '\'');
420 $row_count = PMA_Table::$cache[$db][$table]['Rows'];
423 // for a VIEW, $row_count is always false at this point
424 if (false === $row_count || $row_count < $GLOBALS['cfg']['MaxExactCount']) {
425 if (! $is_view) {
426 $row_count = PMA_DBI_fetch_value(
427 'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
428 . PMA_backquote($table));
429 } else {
430 // For complex views, even trying to get a partial record
431 // count could bring down a server, so we offer an
432 // alternative: setting MaxExactCountViews to 0 will bypass
433 // completely the record counting for views
435 if ($GLOBALS['cfg']['MaxExactCountViews'] == 0) {
436 $row_count = 0;
437 } else {
438 // Counting all rows of a VIEW could be too long, so use
439 // a LIMIT clause.
440 // Use try_query because it can fail (a VIEW is based on
441 // a table that no longer exists)
442 $result = PMA_DBI_try_query(
443 'SELECT 1 FROM ' . PMA_backquote($db) . '.'
444 . PMA_backquote($table) . ' LIMIT '
445 . $GLOBALS['cfg']['MaxExactCountViews'],
446 null, PMA_DBI_QUERY_STORE);
447 if (!PMA_DBI_getError()) {
448 $row_count = PMA_DBI_num_rows($result);
449 PMA_DBI_free_result($result);
453 PMA_Table::$cache[$db][$table]['ExactRows'] = $row_count;
457 if ($ret) {
458 return $row_count;
462 * @deprecated at the moment nowhere is $return = false used
464 // Note: as of PMA 2.8.0, we no longer seem to be using
465 // PMA_Table::countRecords() in display mode.
466 echo PMA_formatNumber($row_count, 0);
467 if ($is_view) {
468 echo '&nbsp;'
469 . sprintf($GLOBALS['strViewHasAtLeast'],
470 $GLOBALS['cfg']['MaxExactCount'],
471 '[a@./Documentation.html#cfg_MaxExactCount@_blank]', '[/a]');
473 } // end of the 'PMA_Table::countRecords()' function
476 * @see PMA_Table::generateFieldSpec()
478 static public function generateAlter($oldcol, $newcol, $type, $length,
479 $attribute, $collation, $null, $default_type, $default_value,
480 $extra, $comment = '', &$field_primary, $index, $default_orig)
482 return PMA_backquote($oldcol) . ' '
483 . PMA_Table::generateFieldSpec($newcol, $type, $length, $attribute,
484 $collation, $null, $default_type, $default_value, $extra,
485 $comment, $field_primary, $index, $default_orig);
486 } // end function
489 * Inserts existing entries in a PMA_* table by reading a value from an old entry
491 * @param string The array index, which Relation feature to check
492 * ('relwork', 'commwork', ...)
493 * @param string The array index, which PMA-table to update
494 * ('bookmark', 'relation', ...)
495 * @param array Which fields will be SELECT'ed from the old entry
496 * @param array Which fields will be used for the WHERE query
497 * (array('FIELDNAME' => 'FIELDVALUE'))
498 * @param array Which fields will be used as new VALUES. These are the important
499 * keys which differ from the old entry.
500 * (array('FIELDNAME' => 'NEW FIELDVALUE'))
502 * @global string relation variable
504 * @author Garvin Hicking <me@supergarv.de>
506 static public function duplicateInfo($work, $pma_table, $get_fields, $where_fields,
507 $new_fields)
509 $last_id = -1;
511 if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
512 $select_parts = array();
513 $row_fields = array();
514 foreach ($get_fields as $get_field) {
515 $select_parts[] = PMA_backquote($get_field);
516 $row_fields[$get_field] = 'cc';
519 $where_parts = array();
520 foreach ($where_fields as $_where => $_value) {
521 $where_parts[] = PMA_backquote($_where) . ' = \''
522 . PMA_sqlAddslashes($_value) . '\'';
525 $new_parts = array();
526 $new_value_parts = array();
527 foreach ($new_fields as $_where => $_value) {
528 $new_parts[] = PMA_backquote($_where);
529 $new_value_parts[] = PMA_sqlAddslashes($_value);
532 $table_copy_query = '
533 SELECT ' . implode(', ', $select_parts) . '
534 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
535 . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
536 WHERE ' . implode(' AND ', $where_parts);
538 // must use PMA_DBI_QUERY_STORE here, since we execute another
539 // query inside the loop
540 $table_copy_rs = PMA_query_as_cu($table_copy_query, true,
541 PMA_DBI_QUERY_STORE);
543 while ($table_copy_row = @PMA_DBI_fetch_assoc($table_copy_rs)) {
544 $value_parts = array();
545 foreach ($table_copy_row as $_key => $_val) {
546 if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
547 $value_parts[] = PMA_sqlAddslashes($_val);
551 $new_table_query = '
552 INSERT IGNORE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
553 . '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
554 (' . implode(', ', $select_parts) . ',
555 ' . implode(', ', $new_parts) . ')
556 VALUES
557 (\'' . implode('\', \'', $value_parts) . '\',
558 \'' . implode('\', \'', $new_value_parts) . '\')';
560 PMA_query_as_cu($new_table_query);
561 $last_id = PMA_DBI_insert_id();
562 } // end while
564 PMA_DBI_free_result($table_copy_rs);
566 return $last_id;
569 return true;
570 } // end of 'PMA_Table::duplicateInfo()' function
574 * Copies or renames table
575 * @todo use RENAME for move operations
576 * - would work only if the databases are on the same filesystem,
577 * how can we check that? try the operation and
578 * catch an error?
579 * - for views, only if MYSQL > 50013
580 * - still have to handle pmadb synch.
582 * @author Michal Cihar <michal@cihar.com>
584 static public function moveCopy($source_db, $source_table, $target_db, $target_table, $what, $move, $mode)
586 global $err_url;
588 // set export settings we need
589 $GLOBALS['sql_backquotes'] = 1;
590 $GLOBALS['asfile'] = 1;
592 // Ensure the target is valid
593 if (! $GLOBALS['pma']->databases->exists($source_db, $target_db)) {
594 if (! $GLOBALS['pma']->databases->exists($source_db)) {
595 $GLOBALS['message'] = PMA_Message::rawError('source database `'
596 . htmlspecialchars($source_db) . '` not found');
598 if (! $GLOBALS['pma']->databases->exists($target_db)) {
599 $GLOBALS['message'] = PMA_Message::rawError('target database `'
600 . htmlspecialchars($target_db) . '` not found');
602 return false;
605 $source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
606 if (! isset($target_db) || ! strlen($target_db)) {
607 $target_db = $source_db;
610 // Doing a select_db could avoid some problems with replicated databases,
611 // when moving table from replicated one to not replicated one
612 PMA_DBI_select_db($target_db);
614 $target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
616 // do not create the table if dataonly
617 if ($what != 'dataonly') {
618 require_once './libraries/export/sql.php';
620 $no_constraints_comments = true;
621 $GLOBALS['sql_constraints_query'] = '';
623 $sql_structure = PMA_getTableDef($source_db, $source_table, "\n", $err_url, false, false);
624 unset($no_constraints_comments);
625 $parsed_sql = PMA_SQP_parse($sql_structure);
626 $analyzed_sql = PMA_SQP_analyze($parsed_sql);
627 $i = 0;
628 if (empty($analyzed_sql[0]['create_table_fields'])) {
629 // this is not a CREATE TABLE, so find the first VIEW
630 $target_for_view = PMA_backquote($target_db);
631 while (true) {
632 if ($parsed_sql[$i]['type'] == 'alpha_reservedWord' && $parsed_sql[$i]['data'] == 'VIEW') {
633 break;
635 $i++;
638 unset($analyzed_sql);
639 $server_sql_mode = PMA_DBI_fetch_value("SHOW VARIABLES LIKE 'sql_mode'", 0, 1);
640 // ANSI_QUOTES might be a subset of sql_mode, for example
641 // REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ANSI
642 if (false !== strpos($server_sql_mode, 'ANSI_QUOTES')) {
643 $table_delimiter = 'quote_double';
644 } else {
645 $table_delimiter = 'quote_backtick';
647 unset($server_sql_mode);
649 /* nijel: Find table name in query and replace it */
650 while ($parsed_sql[$i]['type'] != $table_delimiter) {
651 $i++;
654 /* no need to PMA_backquote() */
655 if (isset($target_for_view)) {
656 // this a view definition; we just found the first db name
657 // that follows DEFINER VIEW
658 // so change it for the new db name
659 $parsed_sql[$i]['data'] = $target_for_view;
660 // then we have to find all references to the source db
661 // and change them to the target db, ensuring we stay into
662 // the $parsed_sql limits
663 $last = $parsed_sql['len'] - 1;
664 $backquoted_source_db = PMA_backquote($source_db);
665 for (++$i; $i <= $last; $i++) {
666 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
667 $parsed_sql[$i]['data'] = $target_for_view;
670 unset($last,$backquoted_source_db);
671 } else {
672 $parsed_sql[$i]['data'] = $target;
675 /* Generate query back */
676 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
677 // If table exists, and 'add drop table' is selected: Drop it!
678 $drop_query = '';
679 if (isset($GLOBALS['drop_if_exists'])
680 && $GLOBALS['drop_if_exists'] == 'true') {
681 if (PMA_Table::_isView($target_db,$target_table)) {
682 $drop_query = 'DROP VIEW';
683 } else {
684 $drop_query = 'DROP TABLE';
686 $drop_query .= ' IF EXISTS '
687 . PMA_backquote($target_db) . '.'
688 . PMA_backquote($target_table);
689 PMA_DBI_query($drop_query);
691 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
693 // garvin: If an existing table gets deleted, maintain any
694 // entries for the PMA_* tables
695 $maintain_relations = true;
698 @PMA_DBI_query($sql_structure);
699 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
701 if (($move || isset($GLOBALS['add_constraints']))
702 && !empty($GLOBALS['sql_constraints_query'])) {
703 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
704 $i = 0;
706 // find the first $table_delimiter, it must be the source table name
707 while ($parsed_sql[$i]['type'] != $table_delimiter) {
708 $i++;
709 // maybe someday we should guard against going over limit
710 //if ($i == $parsed_sql['len']) {
711 // break;
715 // replace it by the target table name, no need to PMA_backquote()
716 $parsed_sql[$i]['data'] = $target;
718 // now we must remove all $table_delimiter that follow a CONSTRAINT
719 // keyword, because a constraint name must be unique in a db
721 $cnt = $parsed_sql['len'] - 1;
723 for ($j = $i; $j < $cnt; $j++) {
724 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
725 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
726 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
727 $parsed_sql[$j+1]['data'] = '';
732 // Generate query back
733 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
734 'query_only');
735 if ($mode == 'one_table') {
736 PMA_DBI_query($GLOBALS['sql_constraints_query']);
738 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
739 if ($mode == 'one_table') {
740 unset($GLOBALS['sql_constraints_query']);
743 } else {
744 $GLOBALS['sql_query'] = '';
747 // Copy the data unless this is a VIEW
748 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
749 $sql_insert_data =
750 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
751 PMA_DBI_query($sql_insert_data);
752 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
755 require_once './libraries/relation.lib.php';
756 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
758 // Drops old table if the user has requested to move it
759 if ($move) {
761 // This could avoid some problems with replicated databases, when
762 // moving table from replicated one to not replicated one
763 PMA_DBI_select_db($source_db);
765 if (PMA_Table::_isView($source_db,$source_table)) {
766 $sql_drop_query = 'DROP VIEW';
767 } else {
768 $sql_drop_query = 'DROP TABLE';
770 $sql_drop_query .= ' ' . $source;
771 PMA_DBI_query($sql_drop_query);
773 // garvin: Move old entries from PMA-DBs to new table
774 if ($GLOBALS['cfgRelation']['commwork']) {
775 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
776 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
777 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
778 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
779 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
780 PMA_query_as_cu($remove_query);
781 unset($remove_query);
784 // garvin: updating bookmarks is not possible since only a single table is moved,
785 // and not the whole DB.
787 if ($GLOBALS['cfgRelation']['displaywork']) {
788 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
789 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
790 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
791 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
792 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
793 PMA_query_as_cu($table_query);
794 unset($table_query);
797 if ($GLOBALS['cfgRelation']['relwork']) {
798 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
799 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
800 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
801 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
802 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
803 PMA_query_as_cu($table_query);
804 unset($table_query);
806 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
807 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
808 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
809 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
810 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
811 PMA_query_as_cu($table_query);
812 unset($table_query);
816 * @todo garvin: Can't get moving PDFs the right way. The page numbers
817 * always get screwed up independently from duplication because the
818 * numbers do not seem to be stored on a per-database basis. Would
819 * the author of pdf support please have a look at it?
822 if ($GLOBALS['cfgRelation']['pdfwork']) {
823 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
824 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
825 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
826 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
827 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
828 PMA_query_as_cu($table_query);
829 unset($table_query);
831 $pdf_query = 'SELECT pdf_page_number '
832 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
833 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
834 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
835 $pdf_rs = PMA_query_as_cu($pdf_query);
837 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
838 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
839 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
840 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
841 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
842 $tb_rs = PMA_query_as_cu($table_query);
843 unset($table_query);
844 unset($tb_rs);
849 if ($GLOBALS['cfgRelation']['designerwork']) {
850 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
851 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
852 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
853 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
854 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
855 PMA_query_as_cu($table_query);
856 unset($table_query);
859 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
860 // end if ($move)
861 } else {
862 // we are copying
863 // garvin: Create new entries as duplicates from old PMA DBs
864 if ($what != 'dataonly' && !isset($maintain_relations)) {
865 if ($GLOBALS['cfgRelation']['commwork']) {
866 // Get all comments and MIME-Types for current table
867 $comments_copy_query = 'SELECT
868 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
869 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
870 WHERE
871 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
872 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
873 $comments_copy_rs = PMA_query_as_cu($comments_copy_query);
875 // Write every comment as new copied entry. [MIME]
876 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
877 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
878 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
879 . ' VALUES('
880 . '\'' . PMA_sqlAddslashes($target_db) . '\','
881 . '\'' . PMA_sqlAddslashes($target_table) . '\','
882 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
883 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
884 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
885 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
886 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
887 . ')';
888 PMA_query_as_cu($new_comment_query);
889 } // end while
890 PMA_DBI_free_result($comments_copy_rs);
891 unset($comments_copy_rs);
894 // duplicating the bookmarks must not be done here, but
895 // just once per db
897 $get_fields = array('display_field');
898 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
899 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
900 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
904 * @todo revise this code when we support cross-db relations
906 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
907 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
908 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
909 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
912 $get_fields = array('foreign_field', 'master_table', 'master_field');
913 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
914 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
915 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
918 $get_fields = array('x', 'y', 'v', 'h');
919 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
920 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
921 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
924 * @todo garvin: Can't get duplicating PDFs the right way. The
925 * page numbers always get screwed up independently from
926 * duplication because the numbers do not seem to be stored on a
927 * per-database basis. Would the author of pdf support please
928 * have a look at it?
930 $get_fields = array('page_descr');
931 $where_fields = array('db_name' => $source_db);
932 $new_fields = array('db_name' => $target_db);
933 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
935 if (isset($last_id) && $last_id >= 0) {
936 $get_fields = array('x', 'y');
937 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
938 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
939 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
944 return true;
948 * checks if given name is a valid table name,
949 * currently if not empty, trailing spaces, '.', '/' and '\'
951 * @todo add check for valid chars in filename on current system/os
952 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
953 * @param string $table_name name to check
954 * @return boolean whether the string is valid or not
956 function isValidName($table_name)
958 if ($table_name !== trim($table_name)) {
959 // trailing spaces
960 return false;
963 if (! strlen($table_name)) {
964 // zero length
965 return false;
968 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
969 // illegal char . / \
970 return false;
973 return true;
977 * renames table
979 * @param string new table name
980 * @param string new database name
981 * @return boolean success
983 function rename($new_name, $new_db = null)
985 if (null !== $new_db && $new_db !== $this->getDbName()) {
986 // Ensure the target is valid
987 if (! $GLOBALS['pma']->databases->exists($new_db)) {
988 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
989 return false;
991 } else {
992 $new_db = $this->getDbName();
995 $new_table = new PMA_Table($new_name, $new_db);
997 if ($this->getFullName() === $new_table->getFullName()) {
998 return true;
1001 if (! PMA_Table::isValidName($new_name)) {
1002 $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
1003 return false;
1006 $GLOBALS['sql_query'] = '
1007 RENAME TABLE ' . $this->getFullName(true) . '
1008 TO ' . $new_table->getFullName(true) . ';';
1009 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1010 $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
1011 return false;
1014 $old_name = $this->getName();
1015 $old_db = $this->getDbName();
1016 $this->setName($new_name);
1017 $this->setDbName($new_db);
1020 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1022 // garvin: Move old entries from comments to new table
1023 require_once './libraries/relation.lib.php';
1024 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1025 if ($GLOBALS['cfgRelation']['commwork']) {
1026 $remove_query = '
1027 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1028 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1029 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1030 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1031 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1032 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1033 PMA_query_as_cu($remove_query);
1034 unset($remove_query);
1037 if ($GLOBALS['cfgRelation']['displaywork']) {
1038 $table_query = '
1039 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1040 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1041 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1042 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1043 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1044 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1045 PMA_query_as_cu($table_query);
1046 unset($table_query);
1049 if ($GLOBALS['cfgRelation']['relwork']) {
1050 $table_query = '
1051 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1052 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1053 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1054 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1055 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1056 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1057 PMA_query_as_cu($table_query);
1059 $table_query = '
1060 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1061 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1062 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1063 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1064 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1065 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1066 PMA_query_as_cu($table_query);
1067 unset($table_query);
1070 if ($GLOBALS['cfgRelation']['pdfwork']) {
1071 $table_query = '
1072 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1073 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1074 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1075 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1076 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1077 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1078 PMA_query_as_cu($table_query);
1079 unset($table_query);
1082 if ($GLOBALS['cfgRelation']['designerwork']) {
1083 $table_query = '
1084 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1085 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1086 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1087 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1088 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1089 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1090 PMA_query_as_cu($table_query);
1091 unset($table_query);
1094 $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
1095 htmlspecialchars($old_name), htmlspecialchars($new_name));
1096 return true;
1100 * Get all unique columns
1102 * returns an array with all columns with unqiue content, in fact these are
1103 * all columns being single indexed in PRIMARY or UNIQUE
1105 * f.e.
1106 * - PRIMARY(id) // id
1107 * - UNIQUE(name) // name
1108 * - PRIMARY(fk_id1, fk_id2) // NONE
1109 * - UNIQUE(x,y) // NONE
1112 * @param boolean whether to quote name with backticks ``
1113 * @return array
1115 public function getUniqueColumns($quoted = true)
1117 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1118 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1120 $return = array();
1121 foreach ($uniques as $index) {
1122 if (count($index) > 1) {
1123 continue;
1125 $return[] = $this->getFullName($quoted) . '.' . ($quoted ? PMA_backquote($index[0]) : $index[0]);
1128 return $return;
1132 * Get all indexed columns
1134 * returns an array with all columns make use of an index, in fact only
1135 * first columns in an index
1137 * f.e. index(col1, col2) would only return col1
1138 * @param boolean whether to quote name with backticks ``
1139 * @return array
1141 public function getIndexedColumns($quoted = true)
1143 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1144 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1146 $return = array();
1147 foreach ($indexed as $column) {
1148 $return[] = $this->getFullName($quoted) . '.' . ($quoted ? PMA_backquote($column) : $column);
1151 return $return;