typo
[phpmyadmin/last10db.git] / tbl_relation.php
blob997ef605dc686f045bef7d2f1094ee9c0ad95db0
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 require_once './libraries/tbl_common.php';
22 $url_query .= '&amp;goto=tbl_sql.php';
25 /**
26 * Gets tables informations
28 require_once './libraries/tbl_info.inc.php';
30 // Note: in libraries/tbl_links.inc.php we get and display the table comment.
31 // For InnoDB, this comment contains the REFER information but any update
32 // has not been done yet (will be done in tbl_relation.php later).
33 $avoid_show_comment = TRUE;
35 /**
36 * Displays top menu links
38 require_once './libraries/tbl_links.inc.php';
40 require_once './libraries/relation.lib.php';
42 $options_array = array(
43 'CASCADE' => 'CASCADE',
44 'SET_NULL' => 'SET NULL',
45 'NO_ACTION' => 'NO ACTION',
46 'RESTRICT' => 'RESTRICT',
49 /**
50 * Generate dropdown choices
52 * @param string Message to display
53 * @param string Name of the <select> field
54 * @param array Choices for dropdown
55 * @return string The existing value (for selected)
57 * @access public
59 function PMA_generate_dropdown($dropdown_question, $select_name, $choices, $selected_value)
61 echo htmlspecialchars($dropdown_question) . '&nbsp;&nbsp;';
63 echo '<select name="' . htmlspecialchars($select_name) . '">' . "\n";
64 echo '<option value=""></option>' . "\n";
66 foreach ($choices as $one_value => $one_label) {
67 echo '<option value="' . htmlspecialchars($one_value) . '"';
68 if ($selected_value == $one_value) {
69 echo ' selected="selected" ';
71 echo '>' . htmlspecialchars($one_label) . '</option>' . "\n";
73 echo '</select>' . "\n";
76 /**
77 * Split a string on backquote pairs
79 * @param string original string
80 * @return array containing the elements (and their surrounding backquotes)
82 * @access public
84 function PMA_backquote_split($text)
86 $elements = array();
87 $final_pos = strlen($text) - 1;
88 $pos = 0;
89 while ($pos <= $final_pos) {
90 $first_backquote = strpos($text, '`', $pos);
91 $second_backquote = strpos($text, '`', $first_backquote + 1);
92 // after the second one, there might be another one which means
93 // this is an escaped backquote
94 if ($second_backquote < $final_pos && '`' == $text[$second_backquote + 1]) {
95 $second_backquote = strpos($text, '`', $second_backquote + 2);
97 if (false === $first_backquote || false === $second_backquote) {
98 break;
100 $elements[] = substr($text, $first_backquote, $second_backquote - $first_backquote + 1);
101 $pos = $second_backquote + 1;
103 return($elements);
107 * Gets the relation settings
109 $cfgRelation = PMA_getRelationsParam();
113 * Updates
115 if ($cfgRelation['relwork']) {
116 $existrel = PMA_getForeigners($db, $table, '', 'internal');
118 if (PMA_foreignkey_supported($tbl_type)) {
119 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
121 if ($cfgRelation['displaywork']) {
122 $disp = PMA_getDisplayField($db, $table);
125 // will be used in the logic for internal relations and foreign keys:
126 $me_fields_name =
127 isset($_REQUEST['fields_name'])
128 ? $_REQUEST['fields_name']
129 : null;
131 // 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
132 if (isset($destination) && $cfgRelation['relwork']) {
134 foreach ($destination as $master_field_md5 => $foreign_string) {
135 $upd_query = false;
137 // Map the fieldname's md5 back to its real name
138 $master_field = $me_fields_name[$master_field_md5];
140 if (! empty($foreign_string)) {
141 $foreign_string = trim($foreign_string, '`');
142 list($foreign_db, $foreign_table, $foreign_field) =
143 explode('.', $foreign_string);
144 if (! isset($existrel[$master_field])) {
145 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
146 . '(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)'
147 . ' values('
148 . '\'' . PMA_sqlAddslashes($db) . '\', '
149 . '\'' . PMA_sqlAddslashes($table) . '\', '
150 . '\'' . PMA_sqlAddslashes($master_field) . '\', '
151 . '\'' . PMA_sqlAddslashes($foreign_db) . '\', '
152 . '\'' . PMA_sqlAddslashes($foreign_table) . '\','
153 . '\'' . PMA_sqlAddslashes($foreign_field) . '\')';
154 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
155 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' SET'
156 . ' foreign_db = \'' . PMA_sqlAddslashes($foreign_db) . '\', '
157 . ' foreign_table = \'' . PMA_sqlAddslashes($foreign_table) . '\', '
158 . ' foreign_field = \'' . PMA_sqlAddslashes($foreign_field) . '\' '
159 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
160 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
161 . ' AND master_field = \'' . PMA_sqlAddslashes($master_field) . '\'';
162 } // end if... else....
163 } elseif (isset($existrel[$master_field])) {
164 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
165 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
166 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
167 . ' AND master_field = \'' . PMA_sqlAddslashes($master_field) . '\'';
168 } // end if... else....
169 if ($upd_query) {
170 PMA_query_as_controluser($upd_query);
172 } // end while
173 } // end if (updates for internal relations)
175 // u p d a t e s f o r f o r e i g n k e y s
176 // (for now, one index name only; we keep the definitions if the
177 // foreign db is not the same)
178 // I use $sql_query to be able to display directly the query via
179 // PMA_showMessage()
181 if (isset($_REQUEST['destination_foreign'])) {
182 $display_query = '';
183 $seen_error = false;
184 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
186 // Map the fieldname's md5 back to it's real name
187 $master_field = $me_fields_name[$master_field_md5];
189 if (! empty($foreign_string)) {
190 list($foreign_db, $foreign_table, $foreign_field) = PMA_backquote_split($foreign_string);
191 if (!isset($existrel_foreign[$master_field])) {
192 // no key defined for this field
194 // The next few lines are repeated below, so they
195 // could be put in an include file
196 // Note: I tried to enclose the db and table name with
197 // backquotes but MySQL 4.0.16 did not like the syntax
198 // (for example: `base2`.`table1`)
200 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
201 . ' ADD FOREIGN KEY ('
202 . PMA_backquote($master_field) . ')'
203 . ' REFERENCES '
204 . $foreign_db . '.'
205 . $foreign_table . '('
206 . $foreign_field . ')';
208 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
209 $sql_query .= ' ON DELETE ' . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
211 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
212 $sql_query .= ' ON UPDATE ' . $options_array[$_REQUEST['on_update'][$master_field_md5]];
214 $sql_query .= ';';
215 $display_query .= $sql_query . "\n";
216 // end repeated code
218 } elseif (PMA_backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
219 || PMA_backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
220 || PMA_backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
221 || ($_REQUEST['on_delete'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_delete']) ? $existrel_foreign[$master_field]['on_delete'] : ''))
222 || ($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ? $existrel_foreign[$master_field]['on_update'] : ''))
224 // another foreign key is already defined for this field
225 // or
226 // an option has been changed for ON DELETE or ON UPDATE
228 // remove existing key
229 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
230 . ' DROP FOREIGN KEY '
231 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ';';
233 // I tried to send both in one query but it failed
234 PMA_DBI_query($sql_query);
235 $display_query .= $sql_query . "\n";
237 // add another
238 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
239 . ' ADD FOREIGN KEY ('
240 . PMA_backquote($master_field) . ')'
241 . ' REFERENCES '
242 . $foreign_db . '.'
243 . $foreign_table . '('
244 . $foreign_field . ')';
246 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
247 $sql_query .= ' ON DELETE '
248 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
250 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
251 $sql_query .= ' ON UPDATE '
252 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
254 $sql_query .= ';';
255 $display_query .= $sql_query . "\n";
257 } // end if... else....
258 } elseif (isset($existrel_foreign[$master_field])) {
259 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
260 . ' DROP FOREIGN KEY '
261 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
262 $sql_query .= ';';
263 $display_query .= $sql_query . "\n";
264 } // end if... else....
266 if (! empty($sql_query)) {
267 PMA_DBI_try_query($sql_query);
268 $tmp_error = PMA_DBI_getError();
269 if (! empty($tmp_error)) {
270 $seen_error = true;
272 if (substr($tmp_error, 1, 4) == '1216'
273 || substr($tmp_error, 1, 4) == '1452') {
274 PMA_mysqlDie($tmp_error, $sql_query, FALSE, '', FALSE);
275 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
277 if (substr($tmp_error, 1, 4) == '1005') {
278 $message = PMA_Message::warning('strForeignKeyError');
279 $message->addParam($master_field);
280 $message->display();
281 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
283 unset($tmp_error);
284 $sql_query = '';
286 } // end foreach
287 if (!empty($display_query)) {
288 if ($seen_error) {
289 PMA_showMessage($strError, null, 'error');
290 } else {
291 PMA_showMessage($strSuccess, null, 'success');
294 } // end if isset($destination_foreign)
297 // U p d a t e s f o r d i s p l a y f i e l d
299 if ($cfgRelation['displaywork'] && isset($display_field)) {
300 $upd_query = false;
301 if ($disp) {
302 if ($display_field != '') {
303 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
304 . ' SET display_field = \'' . PMA_sqlAddslashes($display_field) . '\''
305 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
306 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
307 } else {
308 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
309 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
310 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
312 } elseif ($display_field != '') {
313 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
314 . '(db_name, table_name, display_field) '
315 . ' VALUES('
316 . '\'' . PMA_sqlAddslashes($db) . '\','
317 . '\'' . PMA_sqlAddslashes($table) . '\','
318 . '\'' . PMA_sqlAddslashes($display_field) . '\')';
321 if ($upd_query) {
322 PMA_query_as_controluser($upd_query);
324 } // end if
326 // If we did an update, refresh our data
327 if (isset($destination) && $cfgRelation['relwork']) {
328 $existrel = PMA_getForeigners($db, $table, '', 'internal');
330 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_type)) {
331 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
334 if ($cfgRelation['displaywork']) {
335 $disp = PMA_getDisplayField($db, $table);
340 * Dialog
343 // common form
344 echo '<form method="post" action="tbl_relation.php">' . "\n";
345 echo PMA_generate_common_hidden_inputs($db, $table);
348 // relations
350 if ($cfgRelation['relwork'] || PMA_foreignkey_supported($tbl_type)) {
351 // To choose relations we first need all tables names in current db
352 // and if the main table supports foreign keys
353 // we use SHOW TABLE STATUS because we need to find other tables of the
354 // same engine.
356 if (PMA_foreignkey_supported($tbl_type)) {
357 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
358 // [0] of the row is the name
359 // [1] is the type
360 } else {
361 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
362 // [0] of the row is the name
365 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE);
366 $selectboxall[] = '';
367 $selectboxall_foreign[] = '';
369 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
370 $current_table = new PMA_Table($curr_table[0], $db);
372 // explicitely ask for non-quoted list of indexed columns
373 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
375 // if foreign keys are supported, collect all keys from other
376 // tables of the same engine
377 if (PMA_foreignkey_supported($tbl_type)
378 && isset($curr_table[1])
379 && strtoupper($curr_table[1]) == $tbl_type) {
380 // explicitely ask for non-quoted list of indexed columns
381 // need to obtain backquoted values to support dots inside values
382 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
384 } // end while over tables
385 } // end if
387 // Now find out the columns of our $table
388 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
389 $col_rs = PMA_DBI_try_query('SHOW COLUMNS FROM ' . PMA_backquote($table) . ';', null, PMA_DBI_QUERY_STORE);
391 if ($col_rs && PMA_DBI_num_rows($col_rs) > 0) {
392 while ($row = PMA_DBI_fetch_assoc($col_rs)) {
393 $save_row[] = $row;
395 $saved_row_cnt = count($save_row);
397 <fieldset>
398 <legend><?php echo $strLinksTo; ?></legend>
400 <table>
401 <tr><th></th>
402 <?php
403 if ($cfgRelation['relwork']) {
404 echo '<th>' . $strInternalRelations;
405 if (PMA_foreignkey_supported($tbl_type)) {
406 echo PMA_showHint($strInternalAndForeign);
408 echo '</th>';
410 if (PMA_foreignkey_supported($tbl_type)) {
411 // this does not have to be translated, it's part of the MySQL syntax
412 echo '<th colspan="2">FOREIGN KEY (' . $tbl_type . ')';
413 echo '</th>';
416 </tr>
417 <?php
418 $odd_row = true;
419 for ($i = 0; $i < $saved_row_cnt; $i++) {
420 $myfield = $save_row[$i]['Field'];
421 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
422 $myfield_md5 = md5($myfield);
423 $myfield_html = htmlspecialchars($myfield);
425 <tr class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
426 <td align="center">
427 <strong><?php echo $myfield_html; ?></strong>
428 <input type="hidden" name="fields_name[<?php echo $myfield_md5; ?>]" value="<?php echo $myfield_html; ?>"/>
429 </td>
430 <?php
431 if ($cfgRelation['relwork']) {
433 <td><select name="destination[<?php echo $myfield_md5; ?>]">
434 <?php
435 // PMA internal relations
436 if (isset($existrel[$myfield])) {
437 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
438 . $existrel[$myfield]['foreign_table'] . '.'
439 . $existrel[$myfield]['foreign_field'];
440 } else {
441 $foreign_field = FALSE;
443 $seen_key = FALSE;
444 foreach ($selectboxall as $value) {
445 echo ' '
446 . '<option value="' . htmlspecialchars($value) . '"';
447 if ($foreign_field && $value == $foreign_field) {
448 echo ' selected="selected"';
449 $seen_key = TRUE;
451 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
452 } // end while
454 // if the link defined in relationtable points to a foreign field
455 // that is not a key in the foreign table, we show the link
456 // (will not be shown with an arrow)
457 if ($foreign_field && !$seen_key) {
458 echo ' '
459 .'<option value="' . htmlspecialchars($foreign_field) . '"'
460 .' selected="selected"'
461 .'>' . $foreign_field . '</option>'. "\n";
464 </select>
465 </td>
466 <?php
467 } // end if (internal relations)
469 if (PMA_foreignkey_supported($tbl_type)) {
470 echo '<td>';
471 if (!empty($save_row[$i]['Key'])) {
473 <span class="formelement">
474 <select name="destination_foreign[<?php echo $myfield_md5; ?>]">
475 <?php
476 if (isset($existrel_foreign[$myfield])) {
477 // need to backquote to support a dot character inside
478 // an element
479 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
480 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
481 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
482 } else {
483 $foreign_field = FALSE;
486 $found_foreign_field = FALSE;
487 foreach ($selectboxall_foreign as $value) {
488 echo ' '
489 . '<option value="' . htmlspecialchars($value) . '"';
490 if ($foreign_field && $value == $foreign_field) {
491 echo ' selected="selected"';
492 $found_foreign_field = TRUE;
494 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
495 } // end while
497 // we did not find the foreign field in the tables of current db,
498 // must be defined in another db so show it to avoid erasing it
499 if (!$found_foreign_field && $foreign_field) {
500 echo ' '
501 . '<option value="' . htmlspecialchars($foreign_field) . '"';
502 echo ' selected="selected"';
503 echo '>' . $foreign_field . '</option>' . "\n";
507 </select>
508 </span>
509 <span class="formelement">
510 <?php
511 PMA_generate_dropdown('ON DELETE',
512 'on_delete[' . $myfield_md5 . ']',
513 $options_array,
514 isset($existrel_foreign[$myfield]['on_delete']) ? $existrel_foreign[$myfield]['on_delete']: '');
516 echo '</span>' . "\n"
517 .'<span class="formelement">' . "\n";
519 PMA_generate_dropdown('ON UPDATE',
520 'on_update[' . $myfield_md5 . ']',
521 $options_array,
522 isset($existrel_foreign[$myfield]['on_update']) ? $existrel_foreign[$myfield]['on_update']: '');
523 echo '</span>' . "\n";
524 } else {
525 echo $strNoIndex;
526 } // end if (a key exists)
527 echo ' </td>';
528 } // end if (InnoDB)
530 </tr>
531 <?php
532 } // end for
534 unset( $myfield, $myfield_md5, $myfield_html);
536 echo ' </table>' . "\n";
537 echo '</fieldset>' . "\n";
539 if ($cfgRelation['displaywork']) {
540 // Get "display_field" infos
541 $disp = PMA_getDisplayField($db, $table);
543 <fieldset>
544 <label><?php echo $strChangeDisplay . ': '; ?></label>
545 <select name="display_field" style="vertical-align: middle">
546 <option value="">---</option>
547 <?php
548 foreach ($save_row AS $row) {
549 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
550 if (isset($disp) && $row['Field'] == $disp) {
551 echo ' selected="selected"';
553 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
554 } // end while
556 </select>
557 </fieldset>
558 <?php
559 } // end if (displayworks)
561 <fieldset class="tblFooters">
562 <input type="submit" value="<?php echo $strSave; ?>" />
563 </fieldset>
564 </form>
565 <?php
566 } // end if (we have columns in this table)
569 * Displays the footer
571 require_once './libraries/footer.inc.php';