3.4.9
[phpmyadmin/alexukf.git] / tbl_relation.php
blobe4dcc16df594b37a6bcfe34081dc50e250092b87
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'] : 'RESTRICT'))
220 || ($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ? $existrel_foreign[$master_field]['on_update'] : 'RESTRICT'))
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 and add the new one
227 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
228 . ' DROP FOREIGN KEY '
229 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ', '
230 . 'ADD FOREIGN KEY ('
231 . PMA_backquote($master_field) . ')'
232 . ' REFERENCES '
233 . $foreign_db . '.'
234 . $foreign_table . '('
235 . $foreign_field . ')';
237 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
238 $sql_query .= ' ON DELETE '
239 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
241 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
242 $sql_query .= ' ON UPDATE '
243 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
245 $sql_query .= ';';
246 $display_query .= $sql_query . "\n";
248 } // end if... else....
249 } elseif (isset($existrel_foreign[$master_field])) {
250 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
251 . ' DROP FOREIGN KEY '
252 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
253 $sql_query .= ';';
254 $display_query .= $sql_query . "\n";
255 } // end if... else....
257 if (! empty($sql_query)) {
258 PMA_DBI_try_query($sql_query);
259 $tmp_error = PMA_DBI_getError();
260 if (! empty($tmp_error)) {
261 $seen_error = true;
263 if (substr($tmp_error, 1, 4) == '1216'
264 || substr($tmp_error, 1, 4) == '1452') {
265 PMA_mysqlDie($tmp_error, $sql_query, FALSE, '', FALSE);
266 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
268 if (substr($tmp_error, 1, 4) == '1005') {
269 $message = PMA_Message::error( __('Error creating foreign key on %1$s (check data types)'));
270 $message->addParam($master_field);
271 $message->display();
272 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
274 unset($tmp_error);
275 $sql_query = '';
277 } // end foreach
278 if (!empty($display_query)) {
279 if ($seen_error) {
280 PMA_showMessage(__('Error'), null, 'error');
281 } else {
282 PMA_showMessage(__('Your SQL query has been executed successfully'), null, 'success');
285 } // end if isset($destination_foreign)
288 // U p d a t e s f o r d i s p l a y f i e l d
290 if ($cfgRelation['displaywork'] && isset($display_field)) {
291 $upd_query = false;
292 if ($disp) {
293 if ($display_field != '') {
294 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
295 . ' SET display_field = \'' . PMA_sqlAddslashes($display_field) . '\''
296 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
297 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
298 } else {
299 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
300 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
301 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
303 } elseif ($display_field != '') {
304 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
305 . '(db_name, table_name, display_field) '
306 . ' VALUES('
307 . '\'' . PMA_sqlAddslashes($db) . '\','
308 . '\'' . PMA_sqlAddslashes($table) . '\','
309 . '\'' . PMA_sqlAddslashes($display_field) . '\')';
312 if ($upd_query) {
313 PMA_query_as_controluser($upd_query);
315 } // end if
317 // If we did an update, refresh our data
318 if (isset($destination) && $cfgRelation['relwork']) {
319 $existrel = PMA_getForeigners($db, $table, '', 'internal');
321 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_type)) {
322 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
325 if ($cfgRelation['displaywork']) {
326 $disp = PMA_getDisplayField($db, $table);
331 * Dialog
334 // common form
335 echo '<form method="post" action="tbl_relation.php">' . "\n";
336 echo PMA_generate_common_hidden_inputs($db, $table);
339 // relations
341 if ($cfgRelation['relwork'] || PMA_foreignkey_supported($tbl_type)) {
342 // To choose relations we first need all tables names in current db
343 // and if the main table supports foreign keys
344 // we use SHOW TABLE STATUS because we need to find other tables of the
345 // same engine.
347 if (PMA_foreignkey_supported($tbl_type)) {
348 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
349 // [0] of the row is the name
350 // [1] is the type
351 } else {
352 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
353 // [0] of the row is the name
356 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE);
357 $selectboxall[] = '';
358 $selectboxall_foreign[] = '';
360 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
361 $current_table = new PMA_Table($curr_table[0], $db);
363 // explicitely ask for non-quoted list of indexed columns
364 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
366 // if foreign keys are supported, collect all keys from other
367 // tables of the same engine
368 if (PMA_foreignkey_supported($tbl_type)
369 && isset($curr_table[1])
370 && strtoupper($curr_table[1]) == $tbl_type) {
371 // explicitely ask for non-quoted list of indexed columns
372 // need to obtain backquoted values to support dots inside values
373 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
375 } // end while over tables
376 } // end if
378 // Now find out the columns of our $table
379 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
380 $col_rs = PMA_DBI_try_query('SHOW COLUMNS FROM ' . PMA_backquote($table) . ';', null, PMA_DBI_QUERY_STORE);
382 if ($col_rs && PMA_DBI_num_rows($col_rs) > 0) {
383 while ($row = PMA_DBI_fetch_assoc($col_rs)) {
384 $save_row[] = $row;
386 $saved_row_cnt = count($save_row);
388 <fieldset>
389 <legend><?php echo __('Relations'); ?></legend>
391 <table>
392 <tr><th><?php echo __('Column'); ?></th>
393 <?php
394 if ($cfgRelation['relwork']) {
395 echo '<th>' . __('Internal relation');
396 if (PMA_foreignkey_supported($tbl_type)) {
397 echo PMA_showHint(__('An internal relation is not necessary when a corresponding FOREIGN KEY relation exists.'));
399 echo '</th>';
401 if (PMA_foreignkey_supported($tbl_type)) {
402 // this does not have to be translated, it's part of the MySQL syntax
403 echo '<th colspan="2">' . __('Foreign key constraint') . ' (' . $tbl_type . ')';
404 echo '</th>';
407 </tr>
408 <?php
409 $odd_row = true;
410 for ($i = 0; $i < $saved_row_cnt; $i++) {
411 $myfield = $save_row[$i]['Field'];
412 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
413 $myfield_md5 = md5($myfield);
414 $myfield_html = htmlspecialchars($myfield);
416 <tr class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
417 <td align="center">
418 <strong><?php echo $myfield_html; ?></strong>
419 <input type="hidden" name="fields_name[<?php echo $myfield_md5; ?>]" value="<?php echo $myfield_html; ?>"/>
420 </td>
421 <?php
422 if ($cfgRelation['relwork']) {
424 <td><select name="destination[<?php echo $myfield_md5; ?>]">
425 <?php
426 // PMA internal relations
427 if (isset($existrel[$myfield])) {
428 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
429 . $existrel[$myfield]['foreign_table'] . '.'
430 . $existrel[$myfield]['foreign_field'];
431 } else {
432 $foreign_field = FALSE;
434 $seen_key = FALSE;
435 foreach ($selectboxall as $value) {
436 echo ' '
437 . '<option value="' . htmlspecialchars($value) . '"';
438 if ($foreign_field && $value == $foreign_field) {
439 echo ' selected="selected"';
440 $seen_key = TRUE;
442 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
443 } // end while
445 // if the link defined in relationtable points to a foreign field
446 // that is not a key in the foreign table, we show the link
447 // (will not be shown with an arrow)
448 if ($foreign_field && !$seen_key) {
449 echo ' '
450 .'<option value="' . htmlspecialchars($foreign_field) . '"'
451 .' selected="selected"'
452 .'>' . $foreign_field . '</option>'. "\n";
455 </select>
456 </td>
457 <?php
458 } // end if (internal relations)
460 if (PMA_foreignkey_supported($tbl_type)) {
461 echo '<td>';
462 if (!empty($save_row[$i]['Key'])) {
464 <span class="formelement">
465 <select name="destination_foreign[<?php echo $myfield_md5; ?>]" class="referenced_column_dropdown">
466 <?php
467 if (isset($existrel_foreign[$myfield])) {
468 // need to backquote to support a dot character inside
469 // an element
470 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
471 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
472 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
473 } else {
474 $foreign_field = FALSE;
477 $found_foreign_field = FALSE;
478 foreach ($selectboxall_foreign as $value) {
479 echo ' '
480 . '<option value="' . htmlspecialchars($value) . '"';
481 if ($foreign_field && $value == $foreign_field) {
482 echo ' selected="selected"';
483 $found_foreign_field = TRUE;
485 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
486 } // end while
488 // we did not find the foreign field in the tables of current db,
489 // must be defined in another db so show it to avoid erasing it
490 if (!$found_foreign_field && $foreign_field) {
491 echo ' '
492 . '<option value="' . htmlspecialchars($foreign_field) . '"';
493 echo ' selected="selected"';
494 echo '>' . $foreign_field . '</option>' . "\n";
498 </select>
499 </span>
500 <span class="formelement">
501 <?php
502 // For ON DELETE and ON UPDATE, the default action
503 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
504 // won't display the clause if it's set as RESTRICT.
505 PMA_generate_dropdown('ON DELETE',
506 'on_delete[' . $myfield_md5 . ']',
507 $options_array,
508 isset($existrel_foreign[$myfield]['on_delete']) ? $existrel_foreign[$myfield]['on_delete']: 'RESTRICT');
510 echo '</span>' . "\n"
511 .'<span class="formelement">' . "\n";
513 PMA_generate_dropdown('ON UPDATE',
514 'on_update[' . $myfield_md5 . ']',
515 $options_array,
516 isset($existrel_foreign[$myfield]['on_update']) ? $existrel_foreign[$myfield]['on_update']: 'RESTRICT');
517 echo '</span>' . "\n";
518 } else {
519 echo __('No index defined!');
520 } // end if (a key exists)
521 echo ' </td>';
522 } // end if (InnoDB)
524 </tr>
525 <?php
526 } // end for
528 unset( $myfield, $myfield_md5, $myfield_html);
530 echo ' </table>' . "\n";
531 echo '</fieldset>' . "\n";
533 if ($cfgRelation['displaywork']) {
534 // Get "display_field" infos
535 $disp = PMA_getDisplayField($db, $table);
537 <fieldset>
538 <label><?php echo __('Choose column to display') . ': '; ?></label>
539 <select name="display_field">
540 <option value="">---</option>
541 <?php
542 foreach ($save_row AS $row) {
543 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
544 if (isset($disp) && $row['Field'] == $disp) {
545 echo ' selected="selected"';
547 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
548 } // end while
550 </select>
551 </fieldset>
552 <?php
553 } // end if (displayworks)
555 <fieldset class="tblFooters">
556 <input type="submit" value="<?php echo __('Save'); ?>" />
557 </fieldset>
558 </form>
559 <?php
560 } // end if (we have columns in this table)
563 * Displays the footer
565 require './libraries/footer.inc.php';