Merge branch 'master' of ssh://phpmyadmin.git.sourceforge.net/gitroot/phpmyadmin...
[phpmyadmin.git] / tbl_relation.php
blob5ca5ed54ee4de740c0c9f794f84cd1b1705e099b
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
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 for internal relations (but foreign keys relations are correct)
9 * @todo foreign key constraints require both fields being of equal type and size
10 * @todo check foreign fields to be from same type and size, all other makes no sense
11 * @todo add an link to create an index required for constraints, or an option to do automatically
12 * @todo if above todos are fullfilled we can add all fields meet requirements in the select dropdown
13 * @version $Id$
14 * @package phpMyAdmin
17 /**
18 * Gets some core libraries
20 require_once './libraries/common.inc.php';
21 $GLOBALS['js_include'][] = 'tbl_relation.js';
23 require_once './libraries/tbl_common.php';
24 $url_query .= '&amp;goto=tbl_sql.php';
27 /**
28 * Gets tables informations
30 require_once './libraries/tbl_info.inc.php';
32 // Note: in libraries/tbl_links.inc.php we get and display the table comment.
33 // For InnoDB, this comment contains the REFER information but any update
34 // has not been done yet (will be done in tbl_relation.php later).
35 $avoid_show_comment = TRUE;
37 /**
38 * Displays top menu links
40 require_once './libraries/tbl_links.inc.php';
42 require_once './libraries/relation.lib.php';
44 $options_array = array(
45 'CASCADE' => 'CASCADE',
46 'SET_NULL' => 'SET NULL',
47 'NO_ACTION' => 'NO ACTION',
48 'RESTRICT' => 'RESTRICT',
51 /**
52 * Generate dropdown choices
54 * @param string Message to display
55 * @param string Name of the <select> field
56 * @param array Choices for dropdown
57 * @return string The existing value (for selected)
59 * @access public
61 function PMA_generate_dropdown($dropdown_question, $select_name, $choices, $selected_value)
63 echo htmlspecialchars($dropdown_question) . '&nbsp;&nbsp;';
65 echo '<select name="' . htmlspecialchars($select_name) . '">' . "\n";
67 foreach ($choices as $one_value => $one_label) {
68 echo '<option value="' . htmlspecialchars($one_value) . '"';
69 if ($selected_value == $one_value) {
70 echo ' selected="selected" ';
72 echo '>' . htmlspecialchars($one_label) . '</option>' . "\n";
74 echo '</select>' . "\n";
77 /**
78 * Split a string on backquote pairs
80 * @param string original string
81 * @return array containing the elements (and their surrounding backquotes)
83 * @access public
85 function PMA_backquote_split($text)
87 $elements = array();
88 $final_pos = strlen($text) - 1;
89 $pos = 0;
90 while ($pos <= $final_pos) {
91 $first_backquote = strpos($text, '`', $pos);
92 $second_backquote = strpos($text, '`', $first_backquote + 1);
93 // after the second one, there might be another one which means
94 // this is an escaped backquote
95 if ($second_backquote < $final_pos && '`' == $text[$second_backquote + 1]) {
96 $second_backquote = strpos($text, '`', $second_backquote + 2);
98 if (false === $first_backquote || false === $second_backquote) {
99 break;
101 $elements[] = substr($text, $first_backquote, $second_backquote - $first_backquote + 1);
102 $pos = $second_backquote + 1;
104 return($elements);
108 * Gets the relation settings
110 $cfgRelation = PMA_getRelationsParam();
114 * Updates
116 if ($cfgRelation['relwork']) {
117 $existrel = PMA_getForeigners($db, $table, '', 'internal');
119 if (PMA_foreignkey_supported($tbl_type)) {
120 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
122 if ($cfgRelation['displaywork']) {
123 $disp = PMA_getDisplayField($db, $table);
126 // will be used in the logic for internal relations and foreign keys:
127 $me_fields_name =
128 isset($_REQUEST['fields_name'])
129 ? $_REQUEST['fields_name']
130 : null;
132 // 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
133 if (isset($destination) && $cfgRelation['relwork']) {
135 foreach ($destination as $master_field_md5 => $foreign_string) {
136 $upd_query = false;
138 // Map the fieldname's md5 back to its real name
139 $master_field = $me_fields_name[$master_field_md5];
141 if (! empty($foreign_string)) {
142 $foreign_string = trim($foreign_string, '`');
143 list($foreign_db, $foreign_table, $foreign_field) =
144 explode('.', $foreign_string);
145 if (! isset($existrel[$master_field])) {
146 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
147 . '(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)'
148 . ' values('
149 . '\'' . PMA_sqlAddslashes($db) . '\', '
150 . '\'' . PMA_sqlAddslashes($table) . '\', '
151 . '\'' . PMA_sqlAddslashes($master_field) . '\', '
152 . '\'' . PMA_sqlAddslashes($foreign_db) . '\', '
153 . '\'' . PMA_sqlAddslashes($foreign_table) . '\','
154 . '\'' . PMA_sqlAddslashes($foreign_field) . '\')';
155 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
156 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' SET'
157 . ' foreign_db = \'' . PMA_sqlAddslashes($foreign_db) . '\', '
158 . ' foreign_table = \'' . PMA_sqlAddslashes($foreign_table) . '\', '
159 . ' foreign_field = \'' . PMA_sqlAddslashes($foreign_field) . '\' '
160 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
161 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
162 . ' AND master_field = \'' . PMA_sqlAddslashes($master_field) . '\'';
163 } // end if... else....
164 } elseif (isset($existrel[$master_field])) {
165 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
166 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
167 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
168 . ' AND master_field = \'' . PMA_sqlAddslashes($master_field) . '\'';
169 } // end if... else....
170 if ($upd_query) {
171 PMA_query_as_controluser($upd_query);
173 } // end while
174 } // end if (updates for internal relations)
176 // u p d a t e s f o r f o r e i g n k e y s
177 // (for now, one index name only; we keep the definitions if the
178 // foreign db is not the same)
179 // I use $sql_query to be able to display directly the query via
180 // PMA_showMessage()
182 if (isset($_REQUEST['destination_foreign'])) {
183 $display_query = '';
184 $seen_error = false;
185 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
187 // Map the fieldname's md5 back to it's real name
188 $master_field = $me_fields_name[$master_field_md5];
190 if (! empty($foreign_string)) {
191 list($foreign_db, $foreign_table, $foreign_field) = PMA_backquote_split($foreign_string);
192 if (!isset($existrel_foreign[$master_field])) {
193 // no key defined for this field
195 // The next few lines are repeated below, so they
196 // could be put in an include file
197 // Note: I tried to enclose the db and table name with
198 // backquotes but MySQL 4.0.16 did not like the syntax
199 // (for example: `base2`.`table1`)
201 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
202 . ' ADD FOREIGN KEY ('
203 . PMA_backquote($master_field) . ')'
204 . ' REFERENCES '
205 . $foreign_db . '.'
206 . $foreign_table . '('
207 . $foreign_field . ')';
209 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
210 $sql_query .= ' ON DELETE ' . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
212 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
213 $sql_query .= ' ON UPDATE ' . $options_array[$_REQUEST['on_update'][$master_field_md5]];
215 $sql_query .= ';';
216 $display_query .= $sql_query . "\n";
217 // end repeated code
219 } elseif (PMA_backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
220 || PMA_backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
221 || PMA_backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
222 || ($_REQUEST['on_delete'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_delete']) ? $existrel_foreign[$master_field]['on_delete'] : ''))
223 || ($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ? $existrel_foreign[$master_field]['on_update'] : ''))
225 // another foreign key is already defined for this field
226 // or
227 // an option has been changed for ON DELETE or ON UPDATE
229 // remove existing key
230 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
231 . ' DROP FOREIGN KEY '
232 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ';';
234 // I tried to send both in one query but it failed
235 PMA_DBI_query($sql_query);
236 $display_query .= $sql_query . "\n";
238 // add another
239 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
240 . ' ADD FOREIGN KEY ('
241 . PMA_backquote($master_field) . ')'
242 . ' REFERENCES '
243 . $foreign_db . '.'
244 . $foreign_table . '('
245 . $foreign_field . ')';
247 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
248 $sql_query .= ' ON DELETE '
249 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
251 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
252 $sql_query .= ' ON UPDATE '
253 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
255 $sql_query .= ';';
256 $display_query .= $sql_query . "\n";
258 } // end if... else....
259 } elseif (isset($existrel_foreign[$master_field])) {
260 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
261 . ' DROP FOREIGN KEY '
262 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
263 $sql_query .= ';';
264 $display_query .= $sql_query . "\n";
265 } // end if... else....
267 if (! empty($sql_query)) {
268 PMA_DBI_try_query($sql_query);
269 $tmp_error = PMA_DBI_getError();
270 if (! empty($tmp_error)) {
271 $seen_error = true;
273 if (substr($tmp_error, 1, 4) == '1216'
274 || substr($tmp_error, 1, 4) == '1452') {
275 PMA_mysqlDie($tmp_error, $sql_query, FALSE, '', FALSE);
276 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
278 if (substr($tmp_error, 1, 4) == '1005') {
279 $message = PMA_Message::warning( __('Error creating foreign key on %1$s (check data types)'));
280 $message->addParam($master_field);
281 $message->display();
282 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
284 unset($tmp_error);
285 $sql_query = '';
287 } // end foreach
288 if (!empty($display_query)) {
289 if ($seen_error) {
290 PMA_showMessage(__('Error'), null, 'error');
291 } else {
292 PMA_showMessage(__('Your SQL query has been executed successfully'), null, 'success');
295 } // end if isset($destination_foreign)
298 // U p d a t e s f o r d i s p l a y f i e l d
300 if ($cfgRelation['displaywork'] && isset($display_field)) {
301 $upd_query = false;
302 if ($disp) {
303 if ($display_field != '') {
304 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
305 . ' SET display_field = \'' . PMA_sqlAddslashes($display_field) . '\''
306 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
307 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
308 } else {
309 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
310 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
311 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
313 } elseif ($display_field != '') {
314 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
315 . '(db_name, table_name, display_field) '
316 . ' VALUES('
317 . '\'' . PMA_sqlAddslashes($db) . '\','
318 . '\'' . PMA_sqlAddslashes($table) . '\','
319 . '\'' . PMA_sqlAddslashes($display_field) . '\')';
322 if ($upd_query) {
323 PMA_query_as_controluser($upd_query);
325 } // end if
327 // If we did an update, refresh our data
328 if (isset($destination) && $cfgRelation['relwork']) {
329 $existrel = PMA_getForeigners($db, $table, '', 'internal');
331 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_type)) {
332 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
335 if ($cfgRelation['displaywork']) {
336 $disp = PMA_getDisplayField($db, $table);
341 * Dialog
344 // common form
345 echo '<form method="post" action="tbl_relation.php">' . "\n";
346 echo PMA_generate_common_hidden_inputs($db, $table);
349 // relations
351 if ($cfgRelation['relwork'] || PMA_foreignkey_supported($tbl_type)) {
352 // To choose relations we first need all tables names in current db
353 // and if the main table supports foreign keys
354 // we use SHOW TABLE STATUS because we need to find other tables of the
355 // same engine.
357 if (PMA_foreignkey_supported($tbl_type)) {
358 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
359 // [0] of the row is the name
360 // [1] is the type
361 } else {
362 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
363 // [0] of the row is the name
366 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE);
367 $selectboxall[] = '';
368 $selectboxall_foreign[] = '';
370 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
371 $current_table = new PMA_Table($curr_table[0], $db);
373 // explicitely ask for non-quoted list of indexed columns
374 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
376 // if foreign keys are supported, collect all keys from other
377 // tables of the same engine
378 if (PMA_foreignkey_supported($tbl_type)
379 && isset($curr_table[1])
380 && strtoupper($curr_table[1]) == $tbl_type) {
381 // explicitely ask for non-quoted list of indexed columns
382 // need to obtain backquoted values to support dots inside values
383 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
385 } // end while over tables
386 } // end if
388 // Now find out the columns of our $table
389 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
390 $col_rs = PMA_DBI_try_query('SHOW COLUMNS FROM ' . PMA_backquote($table) . ';', null, PMA_DBI_QUERY_STORE);
392 if ($col_rs && PMA_DBI_num_rows($col_rs) > 0) {
393 while ($row = PMA_DBI_fetch_assoc($col_rs)) {
394 $save_row[] = $row;
396 $saved_row_cnt = count($save_row);
398 <fieldset>
399 <legend><?php echo __('Relations'); ?></legend>
401 <table>
402 <tr><th><?php echo __('Column'); ?></th>
403 <?php
404 if ($cfgRelation['relwork']) {
405 echo '<th>' . __('Internal relation');
406 if (PMA_foreignkey_supported($tbl_type)) {
407 echo PMA_showHint(__('An internal relation is not necessary when a corresponding FOREIGN KEY relation exists.'));
409 echo '</th>';
411 if (PMA_foreignkey_supported($tbl_type)) {
412 // this does not have to be translated, it's part of the MySQL syntax
413 echo '<th colspan="2">' . __('Foreign key constraint') . ' (' . $tbl_type . ')';
414 echo '</th>';
417 </tr>
418 <?php
419 $odd_row = true;
420 for ($i = 0; $i < $saved_row_cnt; $i++) {
421 $myfield = $save_row[$i]['Field'];
422 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
423 $myfield_md5 = md5($myfield);
424 $myfield_html = htmlspecialchars($myfield);
426 <tr class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
427 <td align="center">
428 <strong><?php echo $myfield_html; ?></strong>
429 <input type="hidden" name="fields_name[<?php echo $myfield_md5; ?>]" value="<?php echo $myfield_html; ?>"/>
430 </td>
431 <?php
432 if ($cfgRelation['relwork']) {
434 <td><select name="destination[<?php echo $myfield_md5; ?>]">
435 <?php
436 // PMA internal relations
437 if (isset($existrel[$myfield])) {
438 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
439 . $existrel[$myfield]['foreign_table'] . '.'
440 . $existrel[$myfield]['foreign_field'];
441 } else {
442 $foreign_field = FALSE;
444 $seen_key = FALSE;
445 foreach ($selectboxall as $value) {
446 echo ' '
447 . '<option value="' . htmlspecialchars($value) . '"';
448 if ($foreign_field && $value == $foreign_field) {
449 echo ' selected="selected"';
450 $seen_key = TRUE;
452 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
453 } // end while
455 // if the link defined in relationtable points to a foreign field
456 // that is not a key in the foreign table, we show the link
457 // (will not be shown with an arrow)
458 if ($foreign_field && !$seen_key) {
459 echo ' '
460 .'<option value="' . htmlspecialchars($foreign_field) . '"'
461 .' selected="selected"'
462 .'>' . $foreign_field . '</option>'. "\n";
465 </select>
466 </td>
467 <?php
468 } // end if (internal relations)
470 if (PMA_foreignkey_supported($tbl_type)) {
471 echo '<td>';
472 if (!empty($save_row[$i]['Key'])) {
474 <span class="formelement">
475 <select name="destination_foreign[<?php echo $myfield_md5; ?>]" class="referenced_column_dropdown">
476 <?php
477 if (isset($existrel_foreign[$myfield])) {
478 // need to backquote to support a dot character inside
479 // an element
480 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
481 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
482 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
483 } else {
484 $foreign_field = FALSE;
487 $found_foreign_field = FALSE;
488 foreach ($selectboxall_foreign as $value) {
489 echo ' '
490 . '<option value="' . htmlspecialchars($value) . '"';
491 if ($foreign_field && $value == $foreign_field) {
492 echo ' selected="selected"';
493 $found_foreign_field = TRUE;
495 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
496 } // end while
498 // we did not find the foreign field in the tables of current db,
499 // must be defined in another db so show it to avoid erasing it
500 if (!$found_foreign_field && $foreign_field) {
501 echo ' '
502 . '<option value="' . htmlspecialchars($foreign_field) . '"';
503 echo ' selected="selected"';
504 echo '>' . $foreign_field . '</option>' . "\n";
508 </select>
509 </span>
510 <span class="formelement">
511 <?php
512 // For ON DELETE and ON UPDATE, the default action
513 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
514 // won't display the clause if it's set as RESTRICT.
515 PMA_generate_dropdown('ON DELETE',
516 'on_delete[' . $myfield_md5 . ']',
517 $options_array,
518 isset($existrel_foreign[$myfield]['on_delete']) ? $existrel_foreign[$myfield]['on_delete']: 'RESTRICT');
520 echo '</span>' . "\n"
521 .'<span class="formelement">' . "\n";
523 PMA_generate_dropdown('ON UPDATE',
524 'on_update[' . $myfield_md5 . ']',
525 $options_array,
526 isset($existrel_foreign[$myfield]['on_update']) ? $existrel_foreign[$myfield]['on_update']: 'RESTRICT');
527 echo '</span>' . "\n";
528 } else {
529 echo __('No index defined!');
530 } // end if (a key exists)
531 echo ' </td>';
532 } // end if (InnoDB)
534 </tr>
535 <?php
536 } // end for
538 unset( $myfield, $myfield_md5, $myfield_html);
540 echo ' </table>' . "\n";
541 echo '</fieldset>' . "\n";
543 if ($cfgRelation['displaywork']) {
544 // Get "display_field" infos
545 $disp = PMA_getDisplayField($db, $table);
547 <fieldset>
548 <label><?php echo __('Choose column to display') . ': '; ?></label>
549 <select name="display_field">
550 <option value="">---</option>
551 <?php
552 foreach ($save_row AS $row) {
553 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
554 if (isset($disp) && $row['Field'] == $disp) {
555 echo ' selected="selected"';
557 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
558 } // end while
560 </select>
561 </fieldset>
562 <?php
563 } // end if (displayworks)
565 <fieldset class="tblFooters">
566 <input type="submit" value="<?php echo __('Save'); ?>" />
567 </fieldset>
568 </form>
569 <?php
570 } // end if (we have columns in this table)
573 * Displays the footer
575 require_once './libraries/footer.inc.php';