Translation update done using Pootle.
[phpmyadmin.git] / tbl_relation.php
bloba5f6f17a145b5ca37d02dbd817ff3be8192b4aad
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 $dropdown_question Message to display
52 * @param string $select_name Name of the <select> field
53 * @param array $choices Choices for dropdown
54 * @param string $selected_value Selected value
56 * @return string The existing value (for selected)
58 * @access public
60 function PMA_generate_dropdown($dropdown_question, $select_name, $choices, $selected_value)
62 echo htmlspecialchars($dropdown_question) . '&nbsp;&nbsp;';
64 echo '<select name="' . htmlspecialchars($select_name) . '">' . "\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 $text 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 = 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) = explode('.', $foreign_string);
143 if (! isset($existrel[$master_field])) {
144 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
145 . '(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)'
146 . ' values('
147 . '\'' . PMA_sqlAddSlashes($db) . '\', '
148 . '\'' . PMA_sqlAddSlashes($table) . '\', '
149 . '\'' . PMA_sqlAddSlashes($master_field) . '\', '
150 . '\'' . PMA_sqlAddSlashes($foreign_db) . '\', '
151 . '\'' . PMA_sqlAddSlashes($foreign_table) . '\','
152 . '\'' . PMA_sqlAddSlashes($foreign_field) . '\')';
153 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
154 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' SET'
155 . ' foreign_db = \'' . PMA_sqlAddSlashes($foreign_db) . '\', '
156 . ' foreign_table = \'' . PMA_sqlAddSlashes($foreign_table) . '\', '
157 . ' foreign_field = \'' . PMA_sqlAddSlashes($foreign_field) . '\' '
158 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
159 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
160 . ' AND master_field = \'' . PMA_sqlAddSlashes($master_field) . '\'';
161 } // end if... else....
162 } elseif (isset($existrel[$master_field])) {
163 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
164 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
165 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
166 . ' AND master_field = \'' . PMA_sqlAddSlashes($master_field) . '\'';
167 } // end if... else....
168 if ($upd_query) {
169 PMA_query_as_controluser($upd_query);
171 } // end while
172 } // end if (updates for internal relations)
174 // u p d a t e s f o r f o r e i g n k e y s
175 // (for now, one index name only; we keep the definitions if the
176 // foreign db is not the same)
177 // I use $sql_query to be able to display directly the query via
178 // PMA_showMessage()
180 if (isset($_REQUEST['destination_foreign'])) {
181 $display_query = '';
182 $seen_error = false;
183 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
185 // Map the fieldname's md5 back to it's real name
186 $master_field = $me_fields_name[$master_field_md5];
188 if (! empty($foreign_string)) {
189 list($foreign_db, $foreign_table, $foreign_field) = PMA_backquote_split($foreign_string);
190 if (! isset($existrel_foreign[$master_field])) {
191 // no key defined for this field
193 // The next few lines are repeated below, so they
194 // could be put in an include file
195 // Note: I tried to enclose the db and table name with
196 // backquotes but MySQL 4.0.16 did not like the syntax
197 // (for example: `base2`.`table1`)
199 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
200 . ' ADD FOREIGN KEY ('
201 . PMA_backquote($master_field) . ')'
202 . ' REFERENCES '
203 . $foreign_db . '.'
204 . $foreign_table . '('
205 . $foreign_field . ')';
207 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
208 $sql_query .= ' ON DELETE ' . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
210 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
211 $sql_query .= ' ON UPDATE ' . $options_array[$_REQUEST['on_update'][$master_field_md5]];
213 $sql_query .= ';';
214 $display_query .= $sql_query . "\n";
215 // end repeated code
217 } elseif (PMA_backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
218 || PMA_backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
219 || PMA_backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
220 || ($_REQUEST['on_delete'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_delete']) ? $existrel_foreign[$master_field]['on_delete'] : 'RESTRICT'))
221 || ($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ? $existrel_foreign[$master_field]['on_update'] : 'RESTRICT'))
223 // another foreign key is already defined for this field
224 // or
225 // an option has been changed for ON DELETE or ON UPDATE
227 // remove existing key and add the new one
228 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
229 . ' DROP FOREIGN KEY '
230 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ', '
231 . 'ADD FOREIGN KEY ('
232 . PMA_backquote($master_field) . ')'
233 . ' REFERENCES '
234 . $foreign_db . '.'
235 . $foreign_table . '('
236 . $foreign_field . ')';
238 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
239 $sql_query .= ' ON DELETE '
240 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
242 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
243 $sql_query .= ' ON UPDATE '
244 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
246 $sql_query .= ';';
247 $display_query .= $sql_query . "\n";
249 } // end if... else....
250 } elseif (isset($existrel_foreign[$master_field])) {
251 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
252 . ' DROP FOREIGN KEY '
253 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
254 $sql_query .= ';';
255 $display_query .= $sql_query . "\n";
256 } // end if... else....
258 if (! empty($sql_query)) {
259 PMA_DBI_try_query($sql_query);
260 $tmp_error = PMA_DBI_getError();
261 if (! empty($tmp_error)) {
262 $seen_error = true;
264 if (substr($tmp_error, 1, 4) == '1216'
265 || substr($tmp_error, 1, 4) == '1452'
267 PMA_mysqlDie($tmp_error, $sql_query, false, '', false);
268 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
270 if (substr($tmp_error, 1, 4) == '1005') {
271 $message = PMA_Message::error(__('Error creating foreign key on %1$s (check data types)'));
272 $message->addParam($master_field);
273 $message->display();
274 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
276 unset($tmp_error);
277 $sql_query = '';
279 } // end foreach
280 if (!empty($display_query)) {
281 if ($seen_error) {
282 PMA_showMessage(__('Error'), null, 'error');
283 } else {
284 PMA_showMessage(__('Your SQL query has been executed successfully'), null, 'success');
287 } // end if isset($destination_foreign)
290 // U p d a t e s f o r d i s p l a y f i e l d
292 if ($cfgRelation['displaywork'] && isset($display_field)) {
293 $upd_query = false;
294 if ($disp) {
295 if ($display_field != '') {
296 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
297 . ' SET display_field = \'' . PMA_sqlAddSlashes($display_field) . '\''
298 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
299 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
300 } else {
301 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
302 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
303 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\'';
305 } elseif ($display_field != '') {
306 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
307 . '(db_name, table_name, display_field) '
308 . ' VALUES('
309 . '\'' . PMA_sqlAddSlashes($db) . '\','
310 . '\'' . PMA_sqlAddSlashes($table) . '\','
311 . '\'' . PMA_sqlAddSlashes($display_field) . '\')';
314 if ($upd_query) {
315 PMA_query_as_controluser($upd_query);
317 } // end if
319 // If we did an update, refresh our data
320 if (isset($destination) && $cfgRelation['relwork']) {
321 $existrel = PMA_getForeigners($db, $table, '', 'internal');
323 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_type)) {
324 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
327 if ($cfgRelation['displaywork']) {
328 $disp = PMA_getDisplayField($db, $table);
333 * Dialog
336 // common form
337 echo '<form method="post" action="tbl_relation.php">' . "\n";
338 echo PMA_generate_common_hidden_inputs($db, $table);
341 // relations
343 if ($cfgRelation['relwork'] || PMA_foreignkey_supported($tbl_type)) {
344 // To choose relations we first need all tables names in current db
345 // and if the main table supports foreign keys
346 // we use SHOW TABLE STATUS because we need to find other tables of the
347 // same engine.
349 if (PMA_foreignkey_supported($tbl_type)) {
350 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
351 // [0] of the row is the name
352 // [1] is the type
353 } else {
354 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
355 // [0] of the row is the name
358 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE);
359 $selectboxall[] = '';
360 $selectboxall_foreign[] = '';
362 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
363 $current_table = new PMA_Table($curr_table[0], $db);
365 // explicitely ask for non-quoted list of indexed columns
366 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
368 // if foreign keys are supported, collect all keys from other
369 // tables of the same engine
370 if (PMA_foreignkey_supported($tbl_type)
371 && isset($curr_table[1])
372 && strtoupper($curr_table[1]) == $tbl_type
374 // explicitely ask for non-quoted list of indexed columns
375 // need to obtain backquoted values to support dots inside values
376 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
378 } // end while over tables
379 } // end if
381 // Now find out the columns of our $table
382 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
383 $columns = PMA_DBI_get_columns($db, $table);
385 if (count($columns) > 0) {
386 foreach ($columns as $row) {
387 $save_row[] = $row;
389 $saved_row_cnt = count($save_row);
391 <fieldset>
392 <legend><?php echo __('Relations'); ?></legend>
394 <table>
395 <tr><th><?php echo __('Column'); ?></th>
396 <?php
397 if ($cfgRelation['relwork']) {
398 echo '<th>' . __('Internal relation');
399 if (PMA_foreignkey_supported($tbl_type)) {
400 echo PMA_showHint(__('An internal relation is not necessary when a corresponding FOREIGN KEY relation exists.'));
402 echo '</th>';
404 if (PMA_foreignkey_supported($tbl_type)) {
405 // this does not have to be translated, it's part of the MySQL syntax
406 echo '<th colspan="2">' . __('Foreign key constraint') . ' (' . $tbl_type . ')';
407 echo '</th>';
410 </tr>
411 <?php
412 $odd_row = true;
413 for ($i = 0; $i < $saved_row_cnt; $i++) {
414 $myfield = $save_row[$i]['Field'];
415 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
416 $myfield_md5 = md5($myfield);
417 $myfield_html = htmlspecialchars($myfield);
419 <tr class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
420 <td align="center">
421 <strong><?php echo $myfield_html; ?></strong>
422 <input type="hidden" name="fields_name[<?php echo $myfield_md5; ?>]" value="<?php echo $myfield_html; ?>"/>
423 </td>
424 <?php
425 if ($cfgRelation['relwork']) {
427 <td><select name="destination[<?php echo $myfield_md5; ?>]">
428 <?php
429 // PMA internal relations
430 if (isset($existrel[$myfield])) {
431 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
432 . $existrel[$myfield]['foreign_table'] . '.'
433 . $existrel[$myfield]['foreign_field'];
434 } else {
435 $foreign_field = false;
437 $seen_key = false;
438 foreach ($selectboxall as $value) {
439 echo ' '
440 . '<option value="' . htmlspecialchars($value) . '"';
441 if ($foreign_field && $value == $foreign_field) {
442 echo ' selected="selected"';
443 $seen_key = true;
445 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
446 } // end while
448 // if the link defined in relationtable points to a foreign field
449 // that is not a key in the foreign table, we show the link
450 // (will not be shown with an arrow)
451 if ($foreign_field && !$seen_key) {
452 echo ' '
453 .'<option value="' . htmlspecialchars($foreign_field) . '"'
454 .' selected="selected"'
455 .'>' . $foreign_field . '</option>'. "\n";
458 </select>
459 </td>
460 <?php
461 } // end if (internal relations)
463 if (PMA_foreignkey_supported($tbl_type)) {
464 echo '<td>';
465 if (!empty($save_row[$i]['Key'])) {
467 <span class="formelement">
468 <select name="destination_foreign[<?php echo $myfield_md5; ?>]" class="referenced_column_dropdown">
469 <?php
470 if (isset($existrel_foreign[$myfield])) {
471 // need to backquote to support a dot character inside
472 // an element
473 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
474 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
475 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
476 } else {
477 $foreign_field = false;
480 $found_foreign_field = false;
481 foreach ($selectboxall_foreign as $value) {
482 echo ' '
483 . '<option value="' . htmlspecialchars($value) . '"';
484 if ($foreign_field && $value == $foreign_field) {
485 echo ' selected="selected"';
486 $found_foreign_field = true;
488 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
489 } // end while
491 // we did not find the foreign field in the tables of current db,
492 // must be defined in another db so show it to avoid erasing it
493 if (!$found_foreign_field && $foreign_field) {
494 echo ' '
495 . '<option value="' . htmlspecialchars($foreign_field) . '"';
496 echo ' selected="selected"';
497 echo '>' . $foreign_field . '</option>' . "\n";
501 </select>
502 </span>
503 <span class="formelement">
504 <?php
505 // For ON DELETE and ON UPDATE, the default action
506 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
507 // won't display the clause if it's set as RESTRICT.
508 PMA_generate_dropdown('ON DELETE',
509 'on_delete[' . $myfield_md5 . ']',
510 $options_array,
511 isset($existrel_foreign[$myfield]['on_delete']) ? $existrel_foreign[$myfield]['on_delete']: 'RESTRICT');
513 echo '</span>' . "\n"
514 .'<span class="formelement">' . "\n";
516 PMA_generate_dropdown('ON UPDATE',
517 'on_update[' . $myfield_md5 . ']',
518 $options_array,
519 isset($existrel_foreign[$myfield]['on_update']) ? $existrel_foreign[$myfield]['on_update']: 'RESTRICT');
520 echo '</span>' . "\n";
521 } else {
522 echo __('No index defined!');
523 } // end if (a key exists)
524 echo ' </td>';
525 } // end if (InnoDB)
527 </tr>
528 <?php
529 } // end for
531 unset( $myfield, $myfield_md5, $myfield_html);
533 echo ' </table>' . "\n";
534 echo '</fieldset>' . "\n";
536 if ($cfgRelation['displaywork']) {
537 // Get "display_field" infos
538 $disp = PMA_getDisplayField($db, $table);
540 <fieldset>
541 <label><?php echo __('Choose column to display') . ': '; ?></label>
542 <select name="display_field">
543 <option value="">---</option>
544 <?php
545 foreach ($save_row AS $row) {
546 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
547 if (isset($disp) && $row['Field'] == $disp) {
548 echo ' selected="selected"';
550 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
551 } // end while
553 </select>
554 </fieldset>
555 <?php
556 } // end if (displayworks)
558 <fieldset class="tblFooters">
559 <input type="submit" value="<?php echo __('Save'); ?>" />
560 </fieldset>
561 </form>
562 <?php
563 } // end if (we have columns in this table)
566 * Displays the footer
568 require './libraries/footer.inc.php';