Fix typo in translation.
[phpmyadmin/last10db.git] / libraries / Table.class.php
blobacb806761b63628c1cfb84f4015abac00f44d0df
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 if ('ANSI_QUOTES' == $server_sql_mode) {
641 $table_delimiter = 'quote_double';
642 } else {
643 $table_delimiter = 'quote_backtick';
645 unset($server_sql_mode);
647 /* nijel: Find table name in query and replace it */
648 while ($parsed_sql[$i]['type'] != $table_delimiter) {
649 $i++;
652 /* no need to PMA_backquote() */
653 if (isset($target_for_view)) {
654 // this a view definition; we just found the first db name
655 // that follows DEFINER VIEW
656 // so change it for the new db name
657 $parsed_sql[$i]['data'] = $target_for_view;
658 // then we have to find all references to the source db
659 // and change them to the target db, ensuring we stay into
660 // the $parsed_sql limits
661 $last = $parsed_sql['len'] - 1;
662 $backquoted_source_db = PMA_backquote($source_db);
663 for (++$i; $i <= $last; $i++) {
664 if ($parsed_sql[$i]['type'] == $table_delimiter && $parsed_sql[$i]['data'] == $backquoted_source_db) {
665 $parsed_sql[$i]['data'] = $target_for_view;
668 unset($last,$backquoted_source_db);
669 } else {
670 $parsed_sql[$i]['data'] = $target;
673 /* Generate query back */
674 $sql_structure = PMA_SQP_formatHtml($parsed_sql, 'query_only');
675 // If table exists, and 'add drop table' is selected: Drop it!
676 $drop_query = '';
677 if (isset($GLOBALS['drop_if_exists'])
678 && $GLOBALS['drop_if_exists'] == 'true') {
679 if (PMA_Table::_isView($target_db,$target_table)) {
680 $drop_query = 'DROP VIEW';
681 } else {
682 $drop_query = 'DROP TABLE';
684 $drop_query .= ' IF EXISTS '
685 . PMA_backquote($target_db) . '.'
686 . PMA_backquote($target_table);
687 PMA_DBI_query($drop_query);
689 $GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
691 // garvin: If an existing table gets deleted, maintain any
692 // entries for the PMA_* tables
693 $maintain_relations = true;
696 @PMA_DBI_query($sql_structure);
697 $GLOBALS['sql_query'] .= "\n" . $sql_structure . ';';
699 if (($move || isset($GLOBALS['add_constraints']))
700 && !empty($GLOBALS['sql_constraints_query'])) {
701 $parsed_sql = PMA_SQP_parse($GLOBALS['sql_constraints_query']);
702 $i = 0;
704 // find the first $table_delimiter, it must be the source table name
705 while ($parsed_sql[$i]['type'] != $table_delimiter) {
706 $i++;
707 // maybe someday we should guard against going over limit
708 //if ($i == $parsed_sql['len']) {
709 // break;
713 // replace it by the target table name, no need to PMA_backquote()
714 $parsed_sql[$i]['data'] = $target;
716 // now we must remove all $table_delimiter that follow a CONSTRAINT
717 // keyword, because a constraint name must be unique in a db
719 $cnt = $parsed_sql['len'] - 1;
721 for ($j = $i; $j < $cnt; $j++) {
722 if ($parsed_sql[$j]['type'] == 'alpha_reservedWord'
723 && strtoupper($parsed_sql[$j]['data']) == 'CONSTRAINT') {
724 if ($parsed_sql[$j+1]['type'] == $table_delimiter) {
725 $parsed_sql[$j+1]['data'] = '';
730 // Generate query back
731 $GLOBALS['sql_constraints_query'] = PMA_SQP_formatHtml($parsed_sql,
732 'query_only');
733 if ($mode == 'one_table') {
734 PMA_DBI_query($GLOBALS['sql_constraints_query']);
736 $GLOBALS['sql_query'] .= "\n" . $GLOBALS['sql_constraints_query'];
737 if ($mode == 'one_table') {
738 unset($GLOBALS['sql_constraints_query']);
741 } else {
742 $GLOBALS['sql_query'] = '';
745 // Copy the data unless this is a VIEW
746 if (($what == 'data' || $what == 'dataonly') && ! PMA_Table::_isView($target_db,$target_table)) {
747 $sql_insert_data =
748 'INSERT INTO ' . $target . ' SELECT * FROM ' . $source;
749 PMA_DBI_query($sql_insert_data);
750 $GLOBALS['sql_query'] .= "\n\n" . $sql_insert_data . ';';
753 require_once './libraries/relation.lib.php';
754 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
756 // Drops old table if the user has requested to move it
757 if ($move) {
759 // This could avoid some problems with replicated databases, when
760 // moving table from replicated one to not replicated one
761 PMA_DBI_select_db($source_db);
763 if (PMA_Table::_isView($source_db,$source_table)) {
764 $sql_drop_query = 'DROP VIEW';
765 } else {
766 $sql_drop_query = 'DROP TABLE';
768 $sql_drop_query .= ' ' . $source;
769 PMA_DBI_query($sql_drop_query);
771 // garvin: Move old entries from PMA-DBs to new table
772 if ($GLOBALS['cfgRelation']['commwork']) {
773 $remove_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
774 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\', '
775 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
776 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
777 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
778 PMA_query_as_cu($remove_query);
779 unset($remove_query);
782 // garvin: updating bookmarks is not possible since only a single table is moved,
783 // and not the whole DB.
785 if ($GLOBALS['cfgRelation']['displaywork']) {
786 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_info'])
787 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\', '
788 . ' table_name = \'' . PMA_sqlAddslashes($target_table) . '\''
789 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
790 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
791 PMA_query_as_cu($table_query);
792 unset($table_query);
795 if ($GLOBALS['cfgRelation']['relwork']) {
796 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
797 . ' SET foreign_table = \'' . PMA_sqlAddslashes($target_table) . '\','
798 . ' foreign_db = \'' . PMA_sqlAddslashes($target_db) . '\''
799 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($source_db) . '\''
800 . ' AND foreign_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
801 PMA_query_as_cu($table_query);
802 unset($table_query);
804 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
805 . ' SET master_table = \'' . PMA_sqlAddslashes($target_table) . '\','
806 . ' master_db = \'' . PMA_sqlAddslashes($target_db) . '\''
807 . ' WHERE master_db = \'' . PMA_sqlAddslashes($source_db) . '\''
808 . ' AND master_table = \'' . PMA_sqlAddslashes($source_table) . '\'';
809 PMA_query_as_cu($table_query);
810 unset($table_query);
814 * @todo garvin: Can't get moving PDFs the right way. The page numbers
815 * always get screwed up independently from duplication because the
816 * numbers do not seem to be stored on a per-database basis. Would
817 * the author of pdf support please have a look at it?
820 if ($GLOBALS['cfgRelation']['pdfwork']) {
821 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
822 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
823 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
824 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
825 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
826 PMA_query_as_cu($table_query);
827 unset($table_query);
829 $pdf_query = 'SELECT pdf_page_number '
830 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['table_coords'])
831 . ' WHERE db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
832 . ' AND table_name = \'' . PMA_sqlAddslashes($target_table) . '\'';
833 $pdf_rs = PMA_query_as_cu($pdf_query);
835 while ($pdf_copy_row = PMA_DBI_fetch_assoc($pdf_rs)) {
836 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['pdf_pages'])
837 . ' SET db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
838 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
839 . ' AND page_nr = \'' . PMA_sqlAddslashes($pdf_copy_row['pdf_page_number']) . '\'';
840 $tb_rs = PMA_query_as_cu($table_query);
841 unset($table_query);
842 unset($tb_rs);
847 if ($GLOBALS['cfgRelation']['designerwork']) {
848 $table_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['designer_coords'])
849 . ' SET table_name = \'' . PMA_sqlAddslashes($target_table) . '\','
850 . ' db_name = \'' . PMA_sqlAddslashes($target_db) . '\''
851 . ' WHERE db_name = \'' . PMA_sqlAddslashes($source_db) . '\''
852 . ' AND table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
853 PMA_query_as_cu($table_query);
854 unset($table_query);
857 $GLOBALS['sql_query'] .= "\n\n" . $sql_drop_query . ';';
858 // end if ($move)
859 } else {
860 // we are copying
861 // garvin: Create new entries as duplicates from old PMA DBs
862 if ($what != 'dataonly' && !isset($maintain_relations)) {
863 if ($GLOBALS['cfgRelation']['commwork']) {
864 // Get all comments and MIME-Types for current table
865 $comments_copy_query = 'SELECT
866 column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
867 FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
868 WHERE
869 db_name = \'' . PMA_sqlAddslashes($source_db) . '\' AND
870 table_name = \'' . PMA_sqlAddslashes($source_table) . '\'';
871 $comments_copy_rs = PMA_query_as_cu($comments_copy_query);
873 // Write every comment as new copied entry. [MIME]
874 while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
875 $new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
876 . ' (db_name, table_name, column_name, ' . PMA_backquote('comment') . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
877 . ' VALUES('
878 . '\'' . PMA_sqlAddslashes($target_db) . '\','
879 . '\'' . PMA_sqlAddslashes($target_table) . '\','
880 . '\'' . PMA_sqlAddslashes($comments_copy_row['column_name']) . '\''
881 . ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddslashes($comments_copy_row['comment']) . '\','
882 . '\'' . PMA_sqlAddslashes($comments_copy_row['mimetype']) . '\','
883 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation']) . '\','
884 . '\'' . PMA_sqlAddslashes($comments_copy_row['transformation_options']) . '\'' : '')
885 . ')';
886 PMA_query_as_cu($new_comment_query);
887 } // end while
888 PMA_DBI_free_result($comments_copy_rs);
889 unset($comments_copy_rs);
892 // duplicating the bookmarks must not be done here, but
893 // just once per db
895 $get_fields = array('display_field');
896 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
897 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
898 PMA_Table::duplicateInfo('displaywork', 'table_info', $get_fields, $where_fields, $new_fields);
902 * @todo revise this code when we support cross-db relations
904 $get_fields = array('master_field', 'foreign_table', 'foreign_field');
905 $where_fields = array('master_db' => $source_db, 'master_table' => $source_table);
906 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'master_table' => $target_table);
907 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
910 $get_fields = array('foreign_field', 'master_table', 'master_field');
911 $where_fields = array('foreign_db' => $source_db, 'foreign_table' => $source_table);
912 $new_fields = array('master_db' => $target_db, 'foreign_db' => $target_db, 'foreign_table' => $target_table);
913 PMA_Table::duplicateInfo('relwork', 'relation', $get_fields, $where_fields, $new_fields);
916 $get_fields = array('x', 'y', 'v', 'h');
917 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
918 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table);
919 PMA_Table::duplicateInfo('designerwork', 'designer_coords', $get_fields, $where_fields, $new_fields);
922 * @todo garvin: Can't get duplicating PDFs the right way. The
923 * page numbers always get screwed up independently from
924 * duplication because the numbers do not seem to be stored on a
925 * per-database basis. Would the author of pdf support please
926 * have a look at it?
928 $get_fields = array('page_descr');
929 $where_fields = array('db_name' => $source_db);
930 $new_fields = array('db_name' => $target_db);
931 $last_id = PMA_Table::duplicateInfo('pdfwork', 'pdf_pages', $get_fields, $where_fields, $new_fields);
933 if (isset($last_id) && $last_id >= 0) {
934 $get_fields = array('x', 'y');
935 $where_fields = array('db_name' => $source_db, 'table_name' => $source_table);
936 $new_fields = array('db_name' => $target_db, 'table_name' => $target_table, 'pdf_page_number' => $last_id);
937 PMA_Table::duplicateInfo('pdfwork', 'table_coords', $get_fields, $where_fields, $new_fields);
942 return true;
946 * checks if given name is a valid table name,
947 * currently if not empty, trailing spaces, '.', '/' and '\'
949 * @todo add check for valid chars in filename on current system/os
950 * @see http://dev.mysql.com/doc/refman/5.0/en/legal-names.html
951 * @param string $table_name name to check
952 * @return boolean whether the string is valid or not
954 function isValidName($table_name)
956 if ($table_name !== trim($table_name)) {
957 // trailing spaces
958 return false;
961 if (! strlen($table_name)) {
962 // zero length
963 return false;
966 if (preg_match('/[.\/\\\\]+/i', $table_name)) {
967 // illegal char . / \
968 return false;
971 return true;
975 * renames table
977 * @param string new table name
978 * @param string new database name
979 * @return boolean success
981 function rename($new_name, $new_db = null)
983 if (null !== $new_db && $new_db !== $this->getDbName()) {
984 // Ensure the target is valid
985 if (! $GLOBALS['pma']->databases->exists($new_db)) {
986 $this->errors[] = $GLOBALS['strInvalidDatabase'] . ': ' . $new_db;
987 return false;
989 } else {
990 $new_db = $this->getDbName();
993 $new_table = new PMA_Table($new_name, $new_db);
995 if ($this->getFullName() === $new_table->getFullName()) {
996 return true;
999 if (! PMA_Table::isValidName($new_name)) {
1000 $this->errors[] = $GLOBALS['strInvalidTableName'] . ': ' . $new_table->getFullName();
1001 return false;
1004 $GLOBALS['sql_query'] = '
1005 RENAME TABLE ' . $this->getFullName(true) . '
1006 TO ' . $new_table->getFullName(true) . ';';
1007 if (! PMA_DBI_query($GLOBALS['sql_query'])) {
1008 $this->errors[] = sprintf($GLOBALS['strErrorRenamingTable'], $this->getFullName(), $new_table->getFullName());
1009 return false;
1012 $old_name = $this->getName();
1013 $old_db = $this->getDbName();
1014 $this->setName($new_name);
1015 $this->setDbName($new_db);
1018 * @todo move into extra function PMA_Relation::renameTable($new_name, $old_name, $new_db, $old_db)
1020 // garvin: Move old entries from comments to new table
1021 require_once './libraries/relation.lib.php';
1022 $GLOBALS['cfgRelation'] = PMA_getRelationsParam();
1023 if ($GLOBALS['cfgRelation']['commwork']) {
1024 $remove_query = '
1025 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1026 . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
1027 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1028 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1029 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1030 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1031 PMA_query_as_cu($remove_query);
1032 unset($remove_query);
1035 if ($GLOBALS['cfgRelation']['displaywork']) {
1036 $table_query = '
1037 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1038 . PMA_backquote($GLOBALS['cfgRelation']['table_info']) . '
1039 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1040 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1041 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1042 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1043 PMA_query_as_cu($table_query);
1044 unset($table_query);
1047 if ($GLOBALS['cfgRelation']['relwork']) {
1048 $table_query = '
1049 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1050 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1051 SET `foreign_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1052 `foreign_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1053 WHERE `foreign_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1054 AND `foreign_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1055 PMA_query_as_cu($table_query);
1057 $table_query = '
1058 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1059 . PMA_backquote($GLOBALS['cfgRelation']['relation']) . '
1060 SET `master_db` = \'' . PMA_sqlAddslashes($new_db) . '\',
1061 `master_table` = \'' . PMA_sqlAddslashes($new_name) . '\'
1062 WHERE `master_db` = \'' . PMA_sqlAddslashes($old_db) . '\'
1063 AND `master_table` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1064 PMA_query_as_cu($table_query);
1065 unset($table_query);
1068 if ($GLOBALS['cfgRelation']['pdfwork']) {
1069 $table_query = '
1070 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1071 . PMA_backquote($GLOBALS['cfgRelation']['table_coords']) . '
1072 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1073 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1074 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1075 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1076 PMA_query_as_cu($table_query);
1077 unset($table_query);
1080 if ($GLOBALS['cfgRelation']['designerwork']) {
1081 $table_query = '
1082 UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
1083 . PMA_backquote($GLOBALS['cfgRelation']['designer_coords']) . '
1084 SET `db_name` = \'' . PMA_sqlAddslashes($new_db) . '\',
1085 `table_name` = \'' . PMA_sqlAddslashes($new_name) . '\'
1086 WHERE `db_name` = \'' . PMA_sqlAddslashes($old_db) . '\'
1087 AND `table_name` = \'' . PMA_sqlAddslashes($old_name) . '\'';
1088 PMA_query_as_cu($table_query);
1089 unset($table_query);
1092 $this->messages[] = sprintf($GLOBALS['strRenameTableOK'],
1093 htmlspecialchars($old_name), htmlspecialchars($new_name));
1094 return true;
1098 * Get all unique columns
1100 * returns an array with all columns with unqiue content, in fact these are
1101 * all columns being single indexed in PRIMARY or UNIQUE
1103 * f.e.
1104 * - PRIMARY(id) // id
1105 * - UNIQUE(name) // name
1106 * - PRIMARY(fk_id1, fk_id2) // NONE
1107 * - UNIQUE(x,y) // NONE
1110 * @param boolean whether to quote name with backticks ``
1111 * @return array
1113 public function getUniqueColumns($quoted = true)
1115 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Non_unique = 0';
1116 $uniques = PMA_DBI_fetch_result($sql, array('Key_name', null), 'Column_name');
1118 $return = array();
1119 foreach ($uniques as $index) {
1120 if (count($index) > 1) {
1121 continue;
1123 $return[] = $this->getFullName($quoted) . '.' . ($quoted ? PMA_backquote($index[0]) : $index[0]);
1126 return $return;
1130 * Get all indexed columns
1132 * returns an array with all columns make use of an index, in fact only
1133 * first columns in an index
1135 * f.e. index(col1, col2) would only return col1
1136 * @param boolean whether to quote name with backticks ``
1137 * @return array
1139 public function getIndexedColumns($quoted = true)
1141 $sql = 'SHOW INDEX FROM ' . $this->getFullName(true) . ' WHERE Seq_in_index = 1';
1142 $indexed = PMA_DBI_fetch_result($sql, 'Column_name', 'Column_name');
1144 $return = array();
1145 foreach ($indexed as $column) {
1146 $return[] = $this->getFullName($quoted) . '.' . ($quoted ? PMA_backquote($column) : $column);
1149 return $return;