2 /* vim: set expandtab sw=4 ts=4 sts=4: */
4 * Display table relations for viewing and editing
6 * includes phpMyAdmin relations and InnoDB relations
8 * @todo fix name handling: currently names with dots (.) are not properly handled
9 * for internal relations (but foreign keys relations are correct)
10 * @todo foreign key constraints require both fields being of equal type and size
11 * @todo check foreign fields to be from same type and size, all other makes no sense
12 * @todo add an link to create an index required for constraints,
13 * or an option to do automatically
14 * @todo if above todos are fullfilled we can add all fields meet requirements
15 * in the select dropdown
20 * Gets some core libraries
22 require_once 'libraries/common.inc.php';
23 require_once 'libraries/index.lib.php';
25 $response = PMA_Response
::getInstance();
26 $header = $response->getHeader();
27 $scripts = $header->getScripts();
28 $scripts->addFile('tbl_relation.js');
29 $scripts->addFile('indexes.js');
32 * Sets globals from $_POST
36 'destination_foreign',
43 foreach ($post_params as $one_post_param) {
44 if (isset($_POST[$one_post_param])) {
45 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
50 * Gets tables informations
52 require_once 'libraries/tbl_info.inc.php';
54 $options_array = array(
55 'CASCADE' => 'CASCADE',
56 'SET_NULL' => 'SET NULL',
57 'NO_ACTION' => 'NO ACTION',
58 'RESTRICT' => 'RESTRICT',
62 * Gets the relation settings
64 $cfgRelation = PMA_getRelationsParam();
69 if ($cfgRelation['relwork']) {
70 $existrel = PMA_getForeigners($db, $table, '', 'internal');
72 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)) {
73 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
75 if ($cfgRelation['displaywork']) {
76 $disp = PMA_getDisplayField($db, $table);
79 // will be used in the logic for internal relations and foreign keys:
80 $multi_edit_columns_name = isset($_REQUEST['fields_name'])
81 ?
$_REQUEST['fields_name']
86 // u p d a t e s f o r I n t e r n a l r e l a t i o n s
87 if (isset($destination) && $cfgRelation['relwork']) {
89 foreach ($destination as $master_field_md5 => $foreign_string) {
92 // Map the fieldname's md5 back to its real name
93 $master_field = $multi_edit_columns_name[$master_field_md5];
95 if (! empty($foreign_string)) {
96 $foreign_string = trim($foreign_string, '`');
97 list($foreign_db, $foreign_table, $foreign_field)
98 = explode('.', $foreign_string);
99 if (! isset($existrel[$master_field])) {
100 $upd_query = 'INSERT INTO '
101 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
102 . '.' . PMA_Util
::backquote($cfgRelation['relation'])
103 . '(master_db, master_table, master_field, foreign_db,'
104 . ' foreign_table, foreign_field)'
106 . '\'' . PMA_Util
::sqlAddSlashes($db) . '\', '
107 . '\'' . PMA_Util
::sqlAddSlashes($table) . '\', '
108 . '\'' . PMA_Util
::sqlAddSlashes($master_field) . '\', '
109 . '\'' . PMA_Util
::sqlAddSlashes($foreign_db) . '\', '
110 . '\'' . PMA_Util
::sqlAddSlashes($foreign_table) . '\','
111 . '\'' . PMA_Util
::sqlAddSlashes($foreign_field) . '\')';
112 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
113 $upd_query = 'UPDATE '
114 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
115 . '.' . PMA_Util
::backquote($cfgRelation['relation']) . ' SET'
117 . PMA_Util
::sqlAddSlashes($foreign_db) . '\', '
118 . ' foreign_table = \''
119 . PMA_Util
::sqlAddSlashes($foreign_table) . '\', '
120 . ' foreign_field = \''
121 . PMA_Util
::sqlAddSlashes($foreign_field) . '\' '
122 . ' WHERE master_db = \'' . PMA_Util
::sqlAddSlashes($db) . '\''
123 . ' AND master_table = \''
124 . PMA_Util
::sqlAddSlashes($table) . '\''
125 . ' AND master_field = \''
126 . PMA_Util
::sqlAddSlashes($master_field) . '\'';
127 } // end if... else....
128 } elseif (isset($existrel[$master_field])) {
129 $upd_query = 'DELETE FROM '
130 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
131 . '.' . PMA_Util
::backquote($cfgRelation['relation'])
132 . ' WHERE master_db = \'' . PMA_Util
::sqlAddSlashes($db) . '\''
133 . ' AND master_table = \'' . PMA_Util
::sqlAddSlashes($table) . '\''
134 . ' AND master_field = \'' . PMA_Util
::sqlAddSlashes($master_field)
136 } // end if... else....
138 PMA_queryAsControlUser($upd_query);
141 } // end if (updates for internal relations)
143 // u p d a t e s f o r f o r e i g n k e y s
144 // (for now, one index name only; we keep the definitions if the
145 // foreign db is not the same)
147 if (isset($_REQUEST['destination_foreign'])) {
150 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
154 // Map the fieldname's md5 back to it's real name
155 $master_field = $multi_edit_columns_name[$master_field_md5];
157 if (! empty($foreign_string)) {
158 list($foreign_db, $foreign_table, $foreign_field)
159 = PMA_backquoteSplit($foreign_string);
160 if (! isset($existrel_foreign[$master_field])) {
161 // no key defined for this field
163 } elseif (PMA_Util
::backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
164 || PMA_Util
::backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
165 || PMA_Util
::backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
166 ||
$_REQUEST['constraint_name'][$master_field_md5] != $existrel_foreign[$master_field]['constraint']
167 ||
($_REQUEST['on_delete'][$master_field_md5] != (! empty($existrel_foreign[$master_field]['on_delete']) ?
$existrel_foreign[$master_field]['on_delete'] : 'RESTRICT'))
168 ||
($_REQUEST['on_update'][$master_field_md5] != (! empty($existrel_foreign[$master_field]['on_update']) ?
$existrel_foreign[$master_field]['on_update'] : 'RESTRICT'))
170 // another foreign key is already defined for this field
171 // or an option has been changed for ON DELETE or ON UPDATE
174 } // end if... else....
175 } elseif (isset($existrel_foreign[$master_field])) {
177 } // end if... else....
179 $tmp_error_drop = false;
181 $drop_query = PMA_getSQLToDropForeignKey(
182 $table, $existrel_foreign[$master_field]['constraint']
184 $display_query .= $drop_query . "\n";
185 $GLOBALS['dbi']->tryQuery($drop_query);
186 $tmp_error_drop = $GLOBALS['dbi']->getError();
188 if (! empty($tmp_error_drop)) {
190 $html_output .= PMA_Util
::mysqlDie(
191 $tmp_error_drop, $drop_query, false, '', false
196 $tmp_error_create = false;
198 $create_query = PMA_getSQLToCreateForeignKey(
199 $table, $master_field, $foreign_db, $foreign_table, $foreign_field,
200 $_REQUEST['constraint_name'][$master_field_md5],
201 $options_array[$_REQUEST['on_delete'][$master_field_md5]],
202 $options_array[$_REQUEST['on_update'][$master_field_md5]]
205 $display_query .= $create_query . "\n";
206 $GLOBALS['dbi']->tryQuery($create_query);
207 $tmp_error_create = $GLOBALS['dbi']->getError();
208 if (! empty($tmp_error_create)) {
211 if (substr($tmp_error_create, 1, 4) == '1005') {
212 $message = PMA_Message
::error(
213 __('Error creating foreign key on %1$s (check data types)')
215 $message->addParam($master_field);
218 $html_output .= PMA_Util
::mysqlDie(
219 $tmp_error_create, $create_query, false, '', false
222 $html_output .= PMA_Util
::showMySQLDocu(
223 'manual_Table_types', 'InnoDB_foreign_key_constraints'
227 // this is an alteration and the old constraint has been dropped
228 // without creation of a new one
229 if ($drop && $create && empty($tmp_error_drop)
230 && ! empty($tmp_error_create)
232 // a rollback may be better here
233 $sql_query_recreate = '# Restoring the dropped constraint...' . "\n";
234 $sql_query_recreate .= PMA_getSQLToCreateForeignKey(
235 $table, $master_field,
236 PMA_Util
::backquote($existrel_foreign[$master_field]['foreign_db']),
237 PMA_Util
::backquote($existrel_foreign[$master_field]['foreign_table']),
238 PMA_Util
::backquote($existrel_foreign[$master_field]['foreign_field']),
239 $existrel_foreign[$master_field]['constraint'],
240 $options_array[$existrel_foreign[$master_field]['on_delete']],
241 $options_array[$existrel_foreign[$master_field]['on_update']]
243 $display_query .= $sql_query_recreate . "\n";
244 $GLOBALS['dbi']->tryQuery($sql_query_recreate);
248 if (! empty($display_query) && ! $seen_error) {
249 $html_output .= PMA_Util
::getMessage(
250 __('Your SQL query has been executed successfully'),
254 } // end if isset($destination_foreign)
257 // U p d a t e s f o r d i s p l a y f i e l d
259 if ($cfgRelation['displaywork'] && isset($display_field)) {
262 if ($display_field != '') {
263 $upd_query = 'UPDATE '
264 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
265 . '.' . PMA_Util
::backquote($cfgRelation['table_info'])
266 . ' SET display_field = \''
267 . PMA_Util
::sqlAddSlashes($display_field) . '\''
268 . ' WHERE db_name = \'' . PMA_Util
::sqlAddSlashes($db) . '\''
269 . ' AND table_name = \'' . PMA_Util
::sqlAddSlashes($table) . '\'';
271 $upd_query = 'DELETE FROM '
272 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
273 . '.' . PMA_Util
::backquote($cfgRelation['table_info'])
274 . ' WHERE db_name = \'' . PMA_Util
::sqlAddSlashes($db) . '\''
275 . ' AND table_name = \'' . PMA_Util
::sqlAddSlashes($table) . '\'';
277 } elseif ($display_field != '') {
278 $upd_query = 'INSERT INTO '
279 . PMA_Util
::backquote($GLOBALS['cfgRelation']['db'])
280 . '.' . PMA_Util
::backquote($cfgRelation['table_info'])
281 . '(db_name, table_name, display_field) VALUES('
282 . '\'' . PMA_Util
::sqlAddSlashes($db) . '\','
283 . '\'' . PMA_Util
::sqlAddSlashes($table) . '\','
284 . '\'' . PMA_Util
::sqlAddSlashes($display_field) . '\')';
288 PMA_queryAsControlUser($upd_query);
292 // If we did an update, refresh our data
293 if (isset($destination) && $cfgRelation['relwork']) {
294 $existrel = PMA_getForeigners($db, $table, '', 'internal');
296 if (isset($destination_foreign)
297 && PMA_Util
::isForeignKeySupported($tbl_storage_engine)
299 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
302 if ($cfgRelation['displaywork']) {
303 $disp = PMA_getDisplayField($db, $table);
312 $html_output .= '<form method="post" action="tbl_relation.php">' . "\n"
313 . PMA_generate_common_hidden_inputs($db, $table);
318 if ($cfgRelation['relwork']
319 || PMA_Util
::isForeignKeySupported($tbl_storage_engine)
321 // To choose relations we first need all tables names in current db
322 // and if the main table supports foreign keys
323 // we use SHOW TABLE STATUS because we need to find other tables of the
326 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)) {
327 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_Util
::backquote($db);
328 // [0] of the row is the name
331 $tab_query = 'SHOW TABLES FROM ' . PMA_Util
::backquote($db);
332 // [0] of the row is the name
335 $tab_rs = $GLOBALS['dbi']->query(
336 $tab_query, null, PMA_DatabaseInterface
::QUERY_STORE
338 $selectboxall[] = '';
339 $selectboxall_foreign[] = '';
341 while ($curr_table = $GLOBALS['dbi']->fetchRow($tab_rs)) {
342 $current_table = new PMA_Table($curr_table[0], $db);
344 // explicitely ask for non-quoted list of indexed columns
345 $selectboxall = array_merge(
347 $current_table->getUniqueColumns($backquoted = false)
350 // if foreign keys are supported, collect all keys from other
351 // tables of the same engine
352 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)
353 && isset($curr_table[1])
354 && strtoupper($curr_table[1]) == $tbl_storage_engine
356 // explicitely ask for non-quoted list of indexed columns
357 // need to obtain backquoted values to support dots inside values
358 $selectboxall_foreign = array_merge(
359 $selectboxall_foreign,
360 $current_table->getIndexedColumns($backquoted = true)
363 } // end while over tables
366 // Now find out the columns of our $table
367 // need to use PMA_DatabaseInterface::QUERY_STORE with $GLOBALS['dbi']->numRows() in mysqli
368 $columns = $GLOBALS['dbi']->getColumns($db, $table);
370 if (count($columns) > 0) {
372 foreach ($columns as $row) {
376 $saved_row_cnt = count($save_row);
377 $html_output .= '<fieldset>'
378 . '<legend>' . __('Relations'). '</legend>'
380 . '<tr><th>' . __('Column') . '</th>';
382 if ($cfgRelation['relwork']) {
383 $html_output .= '<th>' . __('Internal relation');
384 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)) {
385 $html_output .= PMA_Util
::showHint(
387 'An internal relation is not necessary when a corresponding'
388 . ' FOREIGN KEY relation exists.'
392 $html_output .= '</th>';
395 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)) {
396 // this does not have to be translated, it's part of the MySQL syntax
397 $html_output .= '<th colspan="2">' . __('Foreign key constraint')
398 . ' (' . $tbl_storage_engine . ')';
399 $html_output .= '</th>';
401 $html_output .= '</tr>';
404 for ($i = 0; $i < $saved_row_cnt; $i++
) {
405 $myfield = $save_row[$i]['Field'];
406 // Use an md5 as array index to avoid having special characters
407 // in the name atttibure (see bug #1746964 )
408 $myfield_md5 = md5($myfield);
409 $myfield_html = htmlspecialchars($myfield);
411 $html_output .= '<tr class="' . ($odd_row ?
'odd' : 'even') . '">'
412 . '<td class="center">'
413 . '<strong>' . $myfield_html . '</strong>'
414 . '<input type="hidden" name="fields_name[' . $myfield_md5 . ']"'
415 . ' value="' . $myfield_html . '"/>'
417 $odd_row = ! $odd_row;
419 if ($cfgRelation['relwork']) {
420 $html_output .= '<td><select name="destination[' . $myfield_md5 . ']">';
421 // PMA internal relations
422 if (isset($existrel[$myfield])) {
423 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
424 . $existrel[$myfield]['foreign_table'] . '.'
425 . $existrel[$myfield]['foreign_field'];
427 $foreign_field = false;
430 foreach ($selectboxall as $value) {
431 $html_output .= '<option value="' . htmlspecialchars($value) . '"';
432 if ($foreign_field && $value == $foreign_field) {
433 $html_output .= ' selected="selected"';
436 $html_output .= '>' . htmlspecialchars($value) . '</option>'. "\n";
439 // if the link defined in relationtable points to a foreign field
440 // that is not a key in the foreign table, we show the link
441 // (will not be shown with an arrow)
442 if ($foreign_field && !$seen_key) {
443 $html_output .= '<option value="' . htmlspecialchars($foreign_field)
445 . ' selected="selected">' . $foreign_field . '</option>'. "\n";
447 $html_output .= '</select>'
449 } // end if (internal relations)
451 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)) {
452 $html_output .= '<td>';
453 if (!empty($save_row[$i]['Key'])) {
454 $html_output .= '<span class="formelement">'
455 . '<select name="destination_foreign[' . $myfield_md5 . ']"'
456 . ' class="referenced_column_dropdown">';
457 if (isset($existrel_foreign[$myfield])) {
458 // need to PMA_Util::backquote to support a dot character inside
460 $foreign_field = PMA_Util
::backquote(
461 $existrel_foreign[$myfield]['foreign_db']
463 . '.' . PMA_Util
::backquote(
464 $existrel_foreign[$myfield]['foreign_table']
466 . '.' . PMA_Util
::backquote(
467 $existrel_foreign[$myfield]['foreign_field']
470 $foreign_field = false;
473 $found_foreign_field = false;
474 foreach ($selectboxall_foreign as $value) {
475 $html_output .= '<option value="'
476 . htmlspecialchars($value) . '"';
477 if ($foreign_field && $value == $foreign_field) {
478 $html_output .= ' selected="selected"';
479 $found_foreign_field = true;
481 $html_output .= '>' . htmlspecialchars($value)
485 // we did not find the foreign field in the tables of current db,
486 // must be defined in another db so show it to avoid erasing it
487 if (!$found_foreign_field && $foreign_field) {
488 $html_output .= '<option value="'
489 . htmlspecialchars($foreign_field) . '"'
490 . ' selected="selected"'
491 . '>' . $foreign_field . '</option>' . "\n";
493 $html_output .= '</select>'
496 // For constraint name
497 $html_output .= '<span class="formelement">';
498 $constraint_name = isset($existrel_foreign[$myfield]['constraint'])
499 ?
$existrel_foreign[$myfield]['constraint'] : '';
500 $html_output .= __('Constraint name');
501 $html_output .= '<input type="text" name="constraint_name['
502 . $myfield_md5 . ']"'
503 . ' value="' . $constraint_name . '"/>';
504 $html_output .= '</span>' . "\n";
506 $html_output .= '<span class="formelement">';
507 // For ON DELETE and ON UPDATE, the default action
508 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
509 // won't display the clause if it's set as RESTRICT.
510 $on_delete = isset($existrel_foreign[$myfield]['on_delete'])
511 ?
$existrel_foreign[$myfield]['on_delete'] : 'RESTRICT';
512 $html_output .= PMA_generateDropdown(
514 'on_delete[' . $myfield_md5 . ']',
518 $html_output .= '</span>' . "\n";
520 $html_output .= '<span class="formelement">' . "\n";
521 $on_update = isset($existrel_foreign[$myfield]['on_update'])
522 ?
$existrel_foreign[$myfield]['on_update'] : 'RESTRICT';
523 $html_output .= PMA_generateDropdown(
525 'on_update[' . $myfield_md5 . ']',
529 $html_output .= '</span>' . "\n";
531 $html_output .= __('No index defined! Create one below');
532 } // end if (a key exists)
533 $html_output .= '</td>';
535 $html_output .= '</tr>';
538 unset( $myfield, $myfield_md5, $myfield_html);
539 $html_output .= '</table>' . "\n"
540 . '</fieldset>' . "\n";
542 if ($cfgRelation['displaywork']) {
543 // Get "display_field" infos
544 $disp = PMA_getDisplayField($db, $table);
545 $html_output .= '<fieldset>'
546 . '<label>' . __('Choose column to display:') . '</label>'
547 . '<select name="display_field">'
548 . '<option value="">---</option>';
550 foreach ($save_row as $row) {
551 $html_output .= '<option value="'
552 . htmlspecialchars($row['Field']) . '"';
553 if (isset($disp) && $row['Field'] == $disp) {
554 $html_output .= ' selected="selected"';
556 $html_output .= '>' . htmlspecialchars($row['Field'])
560 $html_output .= '</select>'
562 } // end if (displayworks)
564 $html_output .= '<fieldset class="tblFooters">'
565 . '<input type="submit" value="' . __('Save') . '" />'
568 } // end if (we have columns in this table)
570 if (PMA_Util
::isForeignKeySupported($tbl_storage_engine)) {
571 $html_output .= '<div id="index_div" class="ajax" >'
572 . PMA_getHtmlForDisplayIndexes();
574 // Render HTML output
575 PMA_Response
::getInstance()->addHTML($html_output);
578 * Generate dropdown choices
580 * @param string $dropdown_question Message to display
581 * @param string $select_name Name of the <select> field
582 * @param array $choices Choices for dropdown
583 * @param string $selected_value Selected value
585 * @return string The html code for existing value (for selected)
589 function PMA_generateDropdown(
590 $dropdown_question, $select_name, $choices, $selected_value
592 $html_output = htmlspecialchars($dropdown_question) . ' '
593 . '<select name="' . htmlspecialchars($select_name) . '">' . "\n";
595 foreach ($choices as $one_value => $one_label) {
596 $html_output .= '<option value="' . htmlspecialchars($one_value) . '"';
597 if ($selected_value == $one_value) {
598 $html_output .= ' selected="selected" ';
600 $html_output .= '>' . htmlspecialchars($one_label) . '</option>' . "\n";
602 $html_output .= '</select>' . "\n";
608 * Split a string on backquote pairs
610 * @param string $text original string
612 * @return array containing the elements (and their surrounding backquotes)
616 function PMA_backquoteSplit($text)
619 $final_pos = strlen($text) - 1;
621 while ($pos <= $final_pos) {
622 $first_backquote = strpos($text, '`', $pos);
623 $second_backquote = strpos($text, '`', $first_backquote +
1);
624 // after the second one, there might be another one which means
625 // this is an escaped backquote
626 if ($second_backquote < $final_pos && '`' == $text[$second_backquote +
1]) {
627 $second_backquote = strpos($text, '`', $second_backquote +
2);
629 if (false === $first_backquote ||
false === $second_backquote) {
632 $elements[] = substr(
633 $text, $first_backquote, $second_backquote - $first_backquote +
1
635 $pos = $second_backquote +
1;
641 * Returns the DROP query for a foreign key constraint
643 * @param string $table table of the foreign key
644 * @param string $fk foreign key name
646 * @return string DROP query for the foreign key constraint
648 function PMA_getSQLToDropForeignKey($table, $fk)
650 return 'ALTER TABLE ' . PMA_Util
::backquote($table)
651 . ' DROP FOREIGN KEY ' . PMA_Util
::backquote($fk) . ';';
655 * Returns the SQL query for foreign key constraint creation
657 * @param string $table table name
658 * @param string $field field name
659 * @param string $foreignDb back-quoted foreign database name
660 * @param string $foreignTable back-quoted foreign table name
661 * @param string $foreignField back-quoted foreign field name
662 * @param string $name name of the constraint
663 * @param string $onDelete on delete action
664 * @param string $onUpdate on update action
666 * @return string SQL query for foreign key constraint creation
668 function PMA_getSQLToCreateForeignKey($table, $field, $foreignDb, $foreignTable,
669 $foreignField, $name = null, $onDelete = null, $onUpdate = null
671 $sql_query = 'ALTER TABLE ' . PMA_Util
::backquote($table) . ' ADD ';
672 // if user entered a constraint name
673 if (! empty($name)) {
674 $sql_query .= ' CONSTRAINT ' . PMA_Util
::backquote($name);
677 $sql_query .= ' FOREIGN KEY (' . PMA_Util
::backquote($field) . ')'
678 . ' REFERENCES ' . $foreignDb . '.' . $foreignTable
679 . '(' . $foreignField . ')';
681 if (! empty($onDelete)) {
682 $sql_query .= ' ON DELETE ' . $onDelete;
684 if (! empty($onUpdate)) {
685 $sql_query .= ' ON UPDATE ' . $onUpdate;