Merge branch 'QA_3_4'
[phpmyadmin.git] / tbl_relation.php
blob6bebd284ee0def1b94f9a20f97cd6f67728c27bf
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 * @package phpMyAdmin
16 /**
17 * Gets some core libraries
19 require_once './libraries/common.inc.php';
20 $GLOBALS['js_include'][] = 'tbl_relation.js';
22 require_once './libraries/tbl_common.php';
23 $url_query .= '&amp;goto=tbl_sql.php';
26 /**
27 * Gets tables informations
29 require_once './libraries/tbl_info.inc.php';
31 // Note: in libraries/tbl_links.inc.php we get and display the table comment.
32 // For InnoDB, this comment contains the REFER information but any update
33 // has not been done yet (will be done in tbl_relation.php later).
34 $avoid_show_comment = true;
36 /**
37 * Displays top menu links
39 require_once './libraries/tbl_links.inc.php';
41 $options_array = array(
42 'CASCADE' => 'CASCADE',
43 'SET_NULL' => 'SET NULL',
44 'NO_ACTION' => 'NO ACTION',
45 'RESTRICT' => 'RESTRICT',
48 /**
49 * Generate dropdown choices
51 * @param string Message to display
52 * @param string Name of the <select> field
53 * @param array Choices for dropdown
54 * @return string The existing value (for selected)
56 * @access public
58 function PMA_generate_dropdown($dropdown_question, $select_name, $choices, $selected_value)
60 echo htmlspecialchars($dropdown_question) . '&nbsp;&nbsp;';
62 echo '<select name="' . htmlspecialchars($select_name) . '">' . "\n";
64 foreach ($choices as $one_value => $one_label) {
65 echo '<option value="' . htmlspecialchars($one_value) . '"';
66 if ($selected_value == $one_value) {
67 echo ' selected="selected" ';
69 echo '>' . htmlspecialchars($one_label) . '</option>' . "\n";
71 echo '</select>' . "\n";
74 /**
75 * Split a string on backquote pairs
77 * @param string original string
78 * @return array containing the elements (and their surrounding backquotes)
80 * @access public
82 function PMA_backquote_split($text)
84 $elements = array();
85 $final_pos = strlen($text) - 1;
86 $pos = 0;
87 while ($pos <= $final_pos) {
88 $first_backquote = strpos($text, '`', $pos);
89 $second_backquote = strpos($text, '`', $first_backquote + 1);
90 // after the second one, there might be another one which means
91 // this is an escaped backquote
92 if ($second_backquote < $final_pos && '`' == $text[$second_backquote + 1]) {
93 $second_backquote = strpos($text, '`', $second_backquote + 2);
95 if (false === $first_backquote || false === $second_backquote) {
96 break;
98 $elements[] = substr($text, $first_backquote, $second_backquote - $first_backquote + 1);
99 $pos = $second_backquote + 1;
101 return($elements);
105 * Gets the relation settings
107 $cfgRelation = PMA_getRelationsParam();
111 * Updates
113 if ($cfgRelation['relwork']) {
114 $existrel = PMA_getForeigners($db, $table, '', 'internal');
116 if (PMA_foreignkey_supported($tbl_type)) {
117 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
119 if ($cfgRelation['displaywork']) {
120 $disp = PMA_getDisplayField($db, $table);
123 // will be used in the logic for internal relations and foreign keys:
124 $me_fields_name =
125 isset($_REQUEST['fields_name'])
126 ? $_REQUEST['fields_name']
127 : null;
129 // 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
130 if (isset($destination) && $cfgRelation['relwork']) {
132 foreach ($destination as $master_field_md5 => $foreign_string) {
133 $upd_query = false;
135 // Map the fieldname's md5 back to its real name
136 $master_field = $me_fields_name[$master_field_md5];
138 if (! empty($foreign_string)) {
139 $foreign_string = trim($foreign_string, '`');
140 list($foreign_db, $foreign_table, $foreign_field) =
141 explode('.', $foreign_string);
142 if (! isset($existrel[$master_field])) {
143 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
144 . '(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)'
145 . ' values('
146 . '\'' . PMA_sqlAddSlashes($db) . '\', '
147 . '\'' . PMA_sqlAddSlashes($table) . '\', '
148 . '\'' . PMA_sqlAddSlashes($master_field) . '\', '
149 . '\'' . PMA_sqlAddSlashes($foreign_db) . '\', '
150 . '\'' . PMA_sqlAddSlashes($foreign_table) . '\','
151 . '\'' . PMA_sqlAddSlashes($foreign_field) . '\')';
152 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
153 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' SET'
154 . ' foreign_db = \'' . PMA_sqlAddSlashes($foreign_db) . '\', '
155 . ' foreign_table = \'' . PMA_sqlAddSlashes($foreign_table) . '\', '
156 . ' foreign_field = \'' . PMA_sqlAddSlashes($foreign_field) . '\' '
157 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
158 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
159 . ' AND master_field = \'' . PMA_sqlAddSlashes($master_field) . '\'';
160 } // end if... else....
161 } elseif (isset($existrel[$master_field])) {
162 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
163 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
164 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
165 . ' AND master_field = \'' . PMA_sqlAddSlashes($master_field) . '\'';
166 } // end if... else....
167 if ($upd_query) {
168 PMA_query_as_controluser($upd_query);
170 } // end while
171 } // end if (updates for internal relations)
173 // u p d a t e s f o r f o r e i g n k e y s
174 // (for now, one index name only; we keep the definitions if the
175 // foreign db is not the same)
176 // I use $sql_query to be able to display directly the query via
177 // PMA_showMessage()
179 if (isset($_REQUEST['destination_foreign'])) {
180 $display_query = '';
181 $seen_error = false;
182 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
184 // Map the fieldname's md5 back to it's real name
185 $master_field = $me_fields_name[$master_field_md5];
187 if (! empty($foreign_string)) {
188 list($foreign_db, $foreign_table, $foreign_field) = PMA_backquote_split($foreign_string);
189 if (! isset($existrel_foreign[$master_field])) {
190 // no key defined for this field
192 // The next few lines are repeated below, so they
193 // could be put in an include file
194 // Note: I tried to enclose the db and table name with
195 // backquotes but MySQL 4.0.16 did not like the syntax
196 // (for example: `base2`.`table1`)
198 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
199 . ' ADD FOREIGN KEY ('
200 . PMA_backquote($master_field) . ')'
201 . ' REFERENCES '
202 . $foreign_db . '.'
203 . $foreign_table . '('
204 . $foreign_field . ')';
206 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
207 $sql_query .= ' ON DELETE ' . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
209 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
210 $sql_query .= ' ON UPDATE ' . $options_array[$_REQUEST['on_update'][$master_field_md5]];
212 $sql_query .= ';';
213 $display_query .= $sql_query . "\n";
214 // end repeated code
216 } elseif (PMA_backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
217 || PMA_backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
218 || PMA_backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
219 || ($_REQUEST['on_delete'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_delete']) ? $existrel_foreign[$master_field]['on_delete'] : ''))
220 || ($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ? $existrel_foreign[$master_field]['on_update'] : ''))
222 // another foreign key is already defined for this field
223 // or
224 // an option has been changed for ON DELETE or ON UPDATE
226 // remove existing key
227 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
228 . ' DROP FOREIGN KEY '
229 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ';';
231 // I tried to send both in one query but it failed
232 PMA_DBI_query($sql_query);
233 $display_query .= $sql_query . "\n";
235 // add another
236 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
237 . ' ADD FOREIGN KEY ('
238 . PMA_backquote($master_field) . ')'
239 . ' REFERENCES '
240 . $foreign_db . '.'
241 . $foreign_table . '('
242 . $foreign_field . ')';
244 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
245 $sql_query .= ' ON DELETE '
246 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
248 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
249 $sql_query .= ' ON UPDATE '
250 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
252 $sql_query .= ';';
253 $display_query .= $sql_query . "\n";
255 } // end if... else....
256 } elseif (isset($existrel_foreign[$master_field])) {
257 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
258 . ' DROP FOREIGN KEY '
259 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
260 $sql_query .= ';';
261 $display_query .= $sql_query . "\n";
262 } // end if... else....
264 if (! empty($sql_query)) {
265 PMA_DBI_try_query($sql_query);
266 $tmp_error = PMA_DBI_getError();
267 if (! empty($tmp_error)) {
268 $seen_error = true;
270 if (substr($tmp_error, 1, 4) == '1216'
271 || substr($tmp_error, 1, 4) == '1452') {
272 PMA_mysqlDie($tmp_error, $sql_query, false, '', false);
273 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
275 if (substr($tmp_error, 1, 4) == '1005') {
276 $message = PMA_Message::error( __('Error creating foreign key on %1$s (check data types)'));
277 $message->addParam($master_field);
278 $message->display();
279 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
281 unset($tmp_error);
282 $sql_query = '';
284 } // end foreach
285 if (!empty($display_query)) {
286 if ($seen_error) {
287 PMA_showMessage(__('Error'), null, 'error');
288 } else {
289 PMA_showMessage(__('Your SQL query has been executed successfully'), null, 'success');
292 } // end if isset($destination_foreign)
295 // U p d a t e s f o r d i s p l a y f i e l d
297 if ($cfgRelation['displaywork'] && isset($display_field)) {
298 $upd_query = false;
299 if ($disp) {
300 if ($display_field != '') {
301 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
302 . ' SET display_field = \'' . PMA_sqlAddSlashes($display_field) . '\''
303 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
304 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
305 } else {
306 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
307 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
308 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
310 } elseif ($display_field != '') {
311 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
312 . '(db_name, table_name, display_field) '
313 . ' VALUES('
314 . '\'' . PMA_sqlAddSlashes($db) . '\','
315 . '\'' . PMA_sqlAddSlashes($table) . '\','
316 . '\'' . PMA_sqlAddSlashes($display_field) . '\')';
319 if ($upd_query) {
320 PMA_query_as_controluser($upd_query);
322 } // end if
324 // If we did an update, refresh our data
325 if (isset($destination) && $cfgRelation['relwork']) {
326 $existrel = PMA_getForeigners($db, $table, '', 'internal');
328 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_type)) {
329 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
332 if ($cfgRelation['displaywork']) {
333 $disp = PMA_getDisplayField($db, $table);
338 * Dialog
341 // common form
342 echo '<form method="post" action="tbl_relation.php">' . "\n";
343 echo PMA_generate_common_hidden_inputs($db, $table);
346 // relations
348 if ($cfgRelation['relwork'] || PMA_foreignkey_supported($tbl_type)) {
349 // To choose relations we first need all tables names in current db
350 // and if the main table supports foreign keys
351 // we use SHOW TABLE STATUS because we need to find other tables of the
352 // same engine.
354 if (PMA_foreignkey_supported($tbl_type)) {
355 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
356 // [0] of the row is the name
357 // [1] is the type
358 } else {
359 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
360 // [0] of the row is the name
363 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE);
364 $selectboxall[] = '';
365 $selectboxall_foreign[] = '';
367 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
368 $current_table = new PMA_Table($curr_table[0], $db);
370 // explicitely ask for non-quoted list of indexed columns
371 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
373 // if foreign keys are supported, collect all keys from other
374 // tables of the same engine
375 if (PMA_foreignkey_supported($tbl_type)
376 && isset($curr_table[1])
377 && strtoupper($curr_table[1]) == $tbl_type) {
378 // explicitely ask for non-quoted list of indexed columns
379 // need to obtain backquoted values to support dots inside values
380 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
382 } // end while over tables
383 } // end if
385 // Now find out the columns of our $table
386 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
387 $columns = PMA_DBI_get_columns($db, $table);
389 if (count($columns) > 0) {
390 foreach ($columns as $row) {
391 $save_row[] = $row;
393 $saved_row_cnt = count($save_row);
395 <fieldset>
396 <legend><?php echo __('Relations'); ?></legend>
398 <table>
399 <tr><th><?php echo __('Column'); ?></th>
400 <?php
401 if ($cfgRelation['relwork']) {
402 echo '<th>' . __('Internal relation');
403 if (PMA_foreignkey_supported($tbl_type)) {
404 echo PMA_showHint(__('An internal relation is not necessary when a corresponding FOREIGN KEY relation exists.'));
406 echo '</th>';
408 if (PMA_foreignkey_supported($tbl_type)) {
409 // this does not have to be translated, it's part of the MySQL syntax
410 echo '<th colspan="2">' . __('Foreign key constraint') . ' (' . $tbl_type . ')';
411 echo '</th>';
414 </tr>
415 <?php
416 $odd_row = true;
417 for ($i = 0; $i < $saved_row_cnt; $i++) {
418 $myfield = $save_row[$i]['Field'];
419 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
420 $myfield_md5 = md5($myfield);
421 $myfield_html = htmlspecialchars($myfield);
423 <tr class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
424 <td align="center">
425 <strong><?php echo $myfield_html; ?></strong>
426 <input type="hidden" name="fields_name[<?php echo $myfield_md5; ?>]" value="<?php echo $myfield_html; ?>"/>
427 </td>
428 <?php
429 if ($cfgRelation['relwork']) {
431 <td><select name="destination[<?php echo $myfield_md5; ?>]">
432 <?php
433 // PMA internal relations
434 if (isset($existrel[$myfield])) {
435 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
436 . $existrel[$myfield]['foreign_table'] . '.'
437 . $existrel[$myfield]['foreign_field'];
438 } else {
439 $foreign_field = false;
441 $seen_key = false;
442 foreach ($selectboxall as $value) {
443 echo ' '
444 . '<option value="' . htmlspecialchars($value) . '"';
445 if ($foreign_field && $value == $foreign_field) {
446 echo ' selected="selected"';
447 $seen_key = true;
449 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
450 } // end while
452 // if the link defined in relationtable points to a foreign field
453 // that is not a key in the foreign table, we show the link
454 // (will not be shown with an arrow)
455 if ($foreign_field && !$seen_key) {
456 echo ' '
457 .'<option value="' . htmlspecialchars($foreign_field) . '"'
458 .' selected="selected"'
459 .'>' . $foreign_field . '</option>'. "\n";
462 </select>
463 </td>
464 <?php
465 } // end if (internal relations)
467 if (PMA_foreignkey_supported($tbl_type)) {
468 echo '<td>';
469 if (!empty($save_row[$i]['Key'])) {
471 <span class="formelement">
472 <select name="destination_foreign[<?php echo $myfield_md5; ?>]" class="referenced_column_dropdown">
473 <?php
474 if (isset($existrel_foreign[$myfield])) {
475 // need to backquote to support a dot character inside
476 // an element
477 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
478 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
479 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
480 } else {
481 $foreign_field = false;
484 $found_foreign_field = false;
485 foreach ($selectboxall_foreign as $value) {
486 echo ' '
487 . '<option value="' . htmlspecialchars($value) . '"';
488 if ($foreign_field && $value == $foreign_field) {
489 echo ' selected="selected"';
490 $found_foreign_field = true;
492 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
493 } // end while
495 // we did not find the foreign field in the tables of current db,
496 // must be defined in another db so show it to avoid erasing it
497 if (!$found_foreign_field && $foreign_field) {
498 echo ' '
499 . '<option value="' . htmlspecialchars($foreign_field) . '"';
500 echo ' selected="selected"';
501 echo '>' . $foreign_field . '</option>' . "\n";
505 </select>
506 </span>
507 <span class="formelement">
508 <?php
509 // For ON DELETE and ON UPDATE, the default action
510 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
511 // won't display the clause if it's set as RESTRICT.
512 PMA_generate_dropdown('ON DELETE',
513 'on_delete[' . $myfield_md5 . ']',
514 $options_array,
515 isset($existrel_foreign[$myfield]['on_delete']) ? $existrel_foreign[$myfield]['on_delete']: 'RESTRICT');
517 echo '</span>' . "\n"
518 .'<span class="formelement">' . "\n";
520 PMA_generate_dropdown('ON UPDATE',
521 'on_update[' . $myfield_md5 . ']',
522 $options_array,
523 isset($existrel_foreign[$myfield]['on_update']) ? $existrel_foreign[$myfield]['on_update']: 'RESTRICT');
524 echo '</span>' . "\n";
525 } else {
526 echo __('No index defined!');
527 } // end if (a key exists)
528 echo ' </td>';
529 } // end if (InnoDB)
531 </tr>
532 <?php
533 } // end for
535 unset( $myfield, $myfield_md5, $myfield_html);
537 echo ' </table>' . "\n";
538 echo '</fieldset>' . "\n";
540 if ($cfgRelation['displaywork']) {
541 // Get "display_field" infos
542 $disp = PMA_getDisplayField($db, $table);
544 <fieldset>
545 <label><?php echo __('Choose column to display') . ': '; ?></label>
546 <select name="display_field">
547 <option value="">---</option>
548 <?php
549 foreach ($save_row AS $row) {
550 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
551 if (isset($disp) && $row['Field'] == $disp) {
552 echo ' selected="selected"';
554 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
555 } // end while
557 </select>
558 </fieldset>
559 <?php
560 } // end if (displayworks)
562 <fieldset class="tblFooters">
563 <input type="submit" value="<?php echo __('Save'); ?>" />
564 </fieldset>
565 </form>
566 <?php
567 } // end if (we have columns in this table)
570 * Displays the footer
572 require './libraries/footer.inc.php';