Translated using Weblate.
[phpmyadmin.git] / tbl_relation.php
blobd58a7b2001c0a903b14a512658bb98a7fb9d23bc
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';
25 /**
26 * Sets globals from $_POST
28 $post_params = array(
29 'destination',
30 'destination_foreign',
31 'display_field',
32 'fields_name',
33 'on_delete',
34 'on_update'
36 foreach ($post_params as $one_post_param) {
37 if (isset($_POST[$one_post_param])) {
38 $GLOBALS[$one_post_param] = $_POST[$one_post_param];
42 /**
43 * Gets tables informations
45 require_once 'libraries/tbl_info.inc.php';
47 // Note: in libraries/tbl_links.inc.php we get and display the table comment.
48 // For InnoDB, this comment contains the REFER information but any update
49 // has not been done yet (will be done in tbl_relation.php later).
50 $avoid_show_comment = true;
52 /**
53 * Displays top menu links
55 require_once 'libraries/tbl_links.inc.php';
57 $options_array = array(
58 'CASCADE' => 'CASCADE',
59 'SET_NULL' => 'SET NULL',
60 'NO_ACTION' => 'NO ACTION',
61 'RESTRICT' => 'RESTRICT',
64 /**
65 * Generate dropdown choices
67 * @param string $dropdown_question Message to display
68 * @param string $select_name Name of the <select> field
69 * @param array $choices Choices for dropdown
70 * @param string $selected_value Selected value
72 * @return string The existing value (for selected)
74 * @access public
76 function PMA_generate_dropdown($dropdown_question, $select_name, $choices, $selected_value)
78 echo htmlspecialchars($dropdown_question) . '&nbsp;&nbsp;';
80 echo '<select name="' . htmlspecialchars($select_name) . '">' . "\n";
82 foreach ($choices as $one_value => $one_label) {
83 echo '<option value="' . htmlspecialchars($one_value) . '"';
84 if ($selected_value == $one_value) {
85 echo ' selected="selected" ';
87 echo '>' . htmlspecialchars($one_label) . '</option>' . "\n";
89 echo '</select>' . "\n";
92 /**
93 * Split a string on backquote pairs
95 * @param string $text original string
97 * @return array containing the elements (and their surrounding backquotes)
99 * @access public
101 function PMA_backquote_split($text)
103 $elements = array();
104 $final_pos = strlen($text) - 1;
105 $pos = 0;
106 while ($pos <= $final_pos) {
107 $first_backquote = strpos($text, '`', $pos);
108 $second_backquote = strpos($text, '`', $first_backquote + 1);
109 // after the second one, there might be another one which means
110 // this is an escaped backquote
111 if ($second_backquote < $final_pos && '`' == $text[$second_backquote + 1]) {
112 $second_backquote = strpos($text, '`', $second_backquote + 2);
114 if (false === $first_backquote || false === $second_backquote) {
115 break;
117 $elements[] = substr($text, $first_backquote, $second_backquote - $first_backquote + 1);
118 $pos = $second_backquote + 1;
120 return($elements);
124 * Gets the relation settings
126 $cfgRelation = PMA_getRelationsParam();
130 * Updates
132 if ($cfgRelation['relwork']) {
133 $existrel = PMA_getForeigners($db, $table, '', 'internal');
135 if (PMA_foreignkey_supported($tbl_storage_engine)) {
136 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
138 if ($cfgRelation['displaywork']) {
139 $disp = PMA_getDisplayField($db, $table);
142 // will be used in the logic for internal relations and foreign keys:
143 $me_fields_name = isset($_REQUEST['fields_name'])
144 ? $_REQUEST['fields_name']
145 : null;
147 // 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
148 if (isset($destination) && $cfgRelation['relwork']) {
150 foreach ($destination as $master_field_md5 => $foreign_string) {
151 $upd_query = false;
153 // Map the fieldname's md5 back to its real name
154 $master_field = $me_fields_name[$master_field_md5];
156 if (! empty($foreign_string)) {
157 $foreign_string = trim($foreign_string, '`');
158 list($foreign_db, $foreign_table, $foreign_field) = explode('.', $foreign_string);
159 if (! isset($existrel[$master_field])) {
160 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
161 . '(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)'
162 . ' values('
163 . '\'' . PMA_sqlAddSlashes($db) . '\', '
164 . '\'' . PMA_sqlAddSlashes($table) . '\', '
165 . '\'' . PMA_sqlAddSlashes($master_field) . '\', '
166 . '\'' . PMA_sqlAddSlashes($foreign_db) . '\', '
167 . '\'' . PMA_sqlAddSlashes($foreign_table) . '\','
168 . '\'' . PMA_sqlAddSlashes($foreign_field) . '\')';
169 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
170 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' SET'
171 . ' foreign_db = \'' . PMA_sqlAddSlashes($foreign_db) . '\', '
172 . ' foreign_table = \'' . PMA_sqlAddSlashes($foreign_table) . '\', '
173 . ' foreign_field = \'' . PMA_sqlAddSlashes($foreign_field) . '\' '
174 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
175 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
176 . ' AND master_field = \'' . PMA_sqlAddSlashes($master_field) . '\'';
177 } // end if... else....
178 } elseif (isset($existrel[$master_field])) {
179 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
180 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
181 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
182 . ' AND master_field = \'' . PMA_sqlAddSlashes($master_field) . '\'';
183 } // end if... else....
184 if ($upd_query) {
185 PMA_query_as_controluser($upd_query);
187 } // end while
188 } // end if (updates for internal relations)
190 // u p d a t e s f o r f o r e i g n k e y s
191 // (for now, one index name only; we keep the definitions if the
192 // foreign db is not the same)
193 // I use $sql_query to be able to display directly the query via
194 // PMA_showMessage()
196 if (isset($_REQUEST['destination_foreign'])) {
197 $display_query = '';
198 $seen_error = false;
199 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
201 // Map the fieldname's md5 back to it's real name
202 $master_field = $me_fields_name[$master_field_md5];
204 if (! empty($foreign_string)) {
205 list($foreign_db, $foreign_table, $foreign_field) = PMA_backquote_split($foreign_string);
206 if (! isset($existrel_foreign[$master_field])) {
207 // no key defined for this field
209 // The next few lines are repeated below, so they
210 // could be put in an include file
211 // Note: I tried to enclose the db and table name with
212 // backquotes but MySQL 4.0.16 did not like the syntax
213 // (for example: `base2`.`table1`)
215 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
216 . ' ADD FOREIGN KEY ('
217 . PMA_backquote($master_field) . ')'
218 . ' REFERENCES '
219 . $foreign_db . '.'
220 . $foreign_table . '('
221 . $foreign_field . ')';
223 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
224 $sql_query .= ' ON DELETE ' . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
226 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
227 $sql_query .= ' ON UPDATE ' . $options_array[$_REQUEST['on_update'][$master_field_md5]];
229 $sql_query .= ';';
230 $display_query .= $sql_query . "\n";
231 // end repeated code
233 } elseif (PMA_backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
234 || PMA_backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
235 || PMA_backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
236 || ($_REQUEST['on_delete'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_delete']) ? $existrel_foreign[$master_field]['on_delete'] : 'RESTRICT'))
237 || ($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ? $existrel_foreign[$master_field]['on_update'] : 'RESTRICT'))
239 // another foreign key is already defined for this field
240 // or
241 // an option has been changed for ON DELETE or ON UPDATE
243 // remove existing key and add the new one
244 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
245 . ' DROP FOREIGN KEY '
246 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ', '
247 . 'ADD FOREIGN KEY ('
248 . PMA_backquote($master_field) . ')'
249 . ' REFERENCES '
250 . $foreign_db . '.'
251 . $foreign_table . '('
252 . $foreign_field . ')';
254 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
255 $sql_query .= ' ON DELETE '
256 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
258 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
259 $sql_query .= ' ON UPDATE '
260 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
262 $sql_query .= ';';
263 $display_query .= $sql_query . "\n";
265 } // end if... else....
266 } elseif (isset($existrel_foreign[$master_field])) {
267 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
268 . ' DROP FOREIGN KEY '
269 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
270 $sql_query .= ';';
271 $display_query .= $sql_query . "\n";
272 } // end if... else....
274 if (! empty($sql_query)) {
275 PMA_DBI_try_query($sql_query);
276 $tmp_error = PMA_DBI_getError();
277 if (! empty($tmp_error)) {
278 $seen_error = true;
280 if (substr($tmp_error, 1, 4) == '1216'
281 || substr($tmp_error, 1, 4) == '1452'
283 PMA_mysqlDie($tmp_error, $sql_query, false, '', false);
284 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
286 if (substr($tmp_error, 1, 4) == '1005') {
287 $message = PMA_Message::error(__('Error creating foreign key on %1$s (check data types)'));
288 $message->addParam($master_field);
289 $message->display();
290 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
292 unset($tmp_error);
293 $sql_query = '';
295 } // end foreach
296 if (!empty($display_query)) {
297 if ($seen_error) {
298 PMA_showMessage(__('Error'), null, 'error');
299 } else {
300 PMA_showMessage(__('Your SQL query has been executed successfully'), null, 'success');
303 } // end if isset($destination_foreign)
306 // U p d a t e s f o r d i s p l a y f i e l d
308 if ($cfgRelation['displaywork'] && isset($display_field)) {
309 $upd_query = false;
310 if ($disp) {
311 if ($display_field != '') {
312 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
313 . ' SET display_field = \'' . PMA_sqlAddSlashes($display_field) . '\''
314 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
315 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
316 } else {
317 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
318 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
319 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
321 } elseif ($display_field != '') {
322 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
323 . '(db_name, table_name, display_field) '
324 . ' VALUES('
325 . '\'' . PMA_sqlAddSlashes($db) . '\','
326 . '\'' . PMA_sqlAddSlashes($table) . '\','
327 . '\'' . PMA_sqlAddSlashes($display_field) . '\')';
330 if ($upd_query) {
331 PMA_query_as_controluser($upd_query);
333 } // end if
335 // If we did an update, refresh our data
336 if (isset($destination) && $cfgRelation['relwork']) {
337 $existrel = PMA_getForeigners($db, $table, '', 'internal');
339 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_storage_engine)) {
340 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
343 if ($cfgRelation['displaywork']) {
344 $disp = PMA_getDisplayField($db, $table);
349 * Dialog
352 // common form
353 echo '<form method="post" action="tbl_relation.php">' . "\n";
354 echo PMA_generate_common_hidden_inputs($db, $table);
357 // relations
359 if ($cfgRelation['relwork'] || PMA_foreignkey_supported($tbl_storage_engine)) {
360 // To choose relations we first need all tables names in current db
361 // and if the main table supports foreign keys
362 // we use SHOW TABLE STATUS because we need to find other tables of the
363 // same engine.
365 if (PMA_foreignkey_supported($tbl_storage_engine)) {
366 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
367 // [0] of the row is the name
368 // [1] is the type
369 } else {
370 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
371 // [0] of the row is the name
374 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE);
375 $selectboxall[] = '';
376 $selectboxall_foreign[] = '';
378 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
379 $current_table = new PMA_Table($curr_table[0], $db);
381 // explicitely ask for non-quoted list of indexed columns
382 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
384 // if foreign keys are supported, collect all keys from other
385 // tables of the same engine
386 if (PMA_foreignkey_supported($tbl_storage_engine)
387 && isset($curr_table[1])
388 && strtoupper($curr_table[1]) == $tbl_storage_engine
390 // explicitely ask for non-quoted list of indexed columns
391 // need to obtain backquoted values to support dots inside values
392 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
394 } // end while over tables
395 } // end if
397 // Now find out the columns of our $table
398 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
399 $columns = PMA_DBI_get_columns($db, $table);
401 if (count($columns) > 0) {
402 foreach ($columns as $row) {
403 $save_row[] = $row;
405 $saved_row_cnt = count($save_row);
407 <fieldset>
408 <legend><?php echo __('Relations'); ?></legend>
410 <table>
411 <tr><th><?php echo __('Column'); ?></th>
412 <?php
413 if ($cfgRelation['relwork']) {
414 echo '<th>' . __('Internal relation');
415 if (PMA_foreignkey_supported($tbl_storage_engine)) {
416 echo PMA_showHint(__('An internal relation is not necessary when a corresponding FOREIGN KEY relation exists.'));
418 echo '</th>';
420 if (PMA_foreignkey_supported($tbl_storage_engine)) {
421 // this does not have to be translated, it's part of the MySQL syntax
422 echo '<th colspan="2">' . __('Foreign key constraint') . ' (' . $tbl_storage_engine . ')';
423 echo '</th>';
426 </tr>
427 <?php
428 $odd_row = true;
429 for ($i = 0; $i < $saved_row_cnt; $i++) {
430 $myfield = $save_row[$i]['Field'];
431 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
432 $myfield_md5 = md5($myfield);
433 $myfield_html = htmlspecialchars($myfield);
435 <tr class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
436 <td class="center">
437 <strong><?php echo $myfield_html; ?></strong>
438 <input type="hidden" name="fields_name[<?php echo $myfield_md5; ?>]" value="<?php echo $myfield_html; ?>"/>
439 </td>
440 <?php
441 if ($cfgRelation['relwork']) {
443 <td><select name="destination[<?php echo $myfield_md5; ?>]">
444 <?php
445 // PMA internal relations
446 if (isset($existrel[$myfield])) {
447 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
448 . $existrel[$myfield]['foreign_table'] . '.'
449 . $existrel[$myfield]['foreign_field'];
450 } else {
451 $foreign_field = false;
453 $seen_key = false;
454 foreach ($selectboxall as $value) {
455 echo ' '
456 . '<option value="' . htmlspecialchars($value) . '"';
457 if ($foreign_field && $value == $foreign_field) {
458 echo ' selected="selected"';
459 $seen_key = true;
461 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
462 } // end while
464 // if the link defined in relationtable points to a foreign field
465 // that is not a key in the foreign table, we show the link
466 // (will not be shown with an arrow)
467 if ($foreign_field && !$seen_key) {
468 echo ' '
469 .'<option value="' . htmlspecialchars($foreign_field) . '"'
470 .' selected="selected"'
471 .'>' . $foreign_field . '</option>'. "\n";
474 </select>
475 </td>
476 <?php
477 } // end if (internal relations)
479 if (PMA_foreignkey_supported($tbl_storage_engine)) {
480 echo '<td>';
481 if (!empty($save_row[$i]['Key'])) {
483 <span class="formelement">
484 <select name="destination_foreign[<?php echo $myfield_md5; ?>]" class="referenced_column_dropdown">
485 <?php
486 if (isset($existrel_foreign[$myfield])) {
487 // need to backquote to support a dot character inside
488 // an element
489 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
490 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
491 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
492 } else {
493 $foreign_field = false;
496 $found_foreign_field = false;
497 foreach ($selectboxall_foreign as $value) {
498 echo ' '
499 . '<option value="' . htmlspecialchars($value) . '"';
500 if ($foreign_field && $value == $foreign_field) {
501 echo ' selected="selected"';
502 $found_foreign_field = true;
504 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
505 } // end while
507 // we did not find the foreign field in the tables of current db,
508 // must be defined in another db so show it to avoid erasing it
509 if (!$found_foreign_field && $foreign_field) {
510 echo ' '
511 . '<option value="' . htmlspecialchars($foreign_field) . '"';
512 echo ' selected="selected"';
513 echo '>' . $foreign_field . '</option>' . "\n";
517 </select>
518 </span>
519 <span class="formelement">
520 <?php
521 // For ON DELETE and ON UPDATE, the default action
522 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
523 // won't display the clause if it's set as RESTRICT.
524 PMA_generate_dropdown(
525 'ON DELETE',
526 'on_delete[' . $myfield_md5 . ']',
527 $options_array,
528 isset($existrel_foreign[$myfield]['on_delete']) ? $existrel_foreign[$myfield]['on_delete']: 'RESTRICT'
531 echo '</span>' . "\n"
532 .'<span class="formelement">' . "\n";
534 PMA_generate_dropdown(
535 'ON UPDATE',
536 'on_update[' . $myfield_md5 . ']',
537 $options_array,
538 isset($existrel_foreign[$myfield]['on_update']) ? $existrel_foreign[$myfield]['on_update']: 'RESTRICT'
540 echo '</span>' . "\n";
541 } else {
542 echo __('No index defined!');
543 } // end if (a key exists)
544 echo ' </td>';
545 } // end if (InnoDB)
547 </tr>
548 <?php
549 } // end for
551 unset( $myfield, $myfield_md5, $myfield_html);
553 echo ' </table>' . "\n";
554 echo '</fieldset>' . "\n";
556 if ($cfgRelation['displaywork']) {
557 // Get "display_field" infos
558 $disp = PMA_getDisplayField($db, $table);
560 <fieldset>
561 <label><?php echo __('Choose column to display') . ': '; ?></label>
562 <select name="display_field">
563 <option value="">---</option>
564 <?php
565 foreach ($save_row AS $row) {
566 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
567 if (isset($disp) && $row['Field'] == $disp) {
568 echo ' selected="selected"';
570 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
571 } // end while
573 </select>
574 </fieldset>
575 <?php
576 } // end if (displayworks)
578 <fieldset class="tblFooters">
579 <input type="submit" value="<?php echo __('Save'); ?>" />
580 </fieldset>
581 </form>
582 <?php
583 } // end if (we have columns in this table)
586 * Displays the footer
588 require 'libraries/footer.inc.php';