2 /* vim: set expandtab sw=4 ts=4 sts=4: */
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
18 * Gets some core libraries
20 require_once './libraries/common.inc.php';
21 $GLOBALS['js_include'][] = 'tbl_relation.js';
23 require_once './libraries/tbl_common.php';
24 $url_query .= '&goto=tbl_sql.php';
28 * Gets tables informations
30 require_once './libraries/tbl_info.inc.php';
32 // Note: in libraries/tbl_links.inc.php we get and display the table comment.
33 // For InnoDB, this comment contains the REFER information but any update
34 // has not been done yet (will be done in tbl_relation.php later).
35 $avoid_show_comment = TRUE;
38 * Displays top menu links
40 require_once './libraries/tbl_links.inc.php';
42 require_once './libraries/relation.lib.php';
44 $options_array = array(
45 'CASCADE' => 'CASCADE',
46 'SET_NULL' => 'SET NULL',
47 'NO_ACTION' => 'NO ACTION',
48 'RESTRICT' => 'RESTRICT',
52 * Generate dropdown choices
54 * @param string Message to display
55 * @param string Name of the <select> field
56 * @param array Choices for dropdown
57 * @return string The existing value (for selected)
61 function PMA_generate_dropdown($dropdown_question, $select_name, $choices, $selected_value)
63 echo htmlspecialchars($dropdown_question) . ' ';
65 echo '<select name="' . htmlspecialchars($select_name) . '">' . "\n";
67 foreach ($choices as $one_value => $one_label) {
68 echo '<option value="' . htmlspecialchars($one_value) . '"';
69 if ($selected_value == $one_value) {
70 echo ' selected="selected" ';
72 echo '>' . htmlspecialchars($one_label) . '</option>' . "\n";
74 echo '</select>' . "\n";
78 * Split a string on backquote pairs
80 * @param string original string
81 * @return array containing the elements (and their surrounding backquotes)
85 function PMA_backquote_split($text)
88 $final_pos = strlen($text) - 1;
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) {
101 $elements[] = substr($text, $first_backquote, $second_backquote - $first_backquote +
1);
102 $pos = $second_backquote +
1;
108 * Gets the relation settings
110 $cfgRelation = PMA_getRelationsParam();
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:
128 isset($_REQUEST['fields_name'])
129 ?
$_REQUEST['fields_name']
132 // 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
133 if (isset($destination) && $cfgRelation['relwork']) {
135 foreach ($destination as $master_field_md5 => $foreign_string) {
138 // Map the fieldname's md5 back to its real name
139 $master_field = $me_fields_name[$master_field_md5];
141 if (! empty($foreign_string)) {
142 $foreign_string = trim($foreign_string, '`');
143 list($foreign_db, $foreign_table, $foreign_field) =
144 explode('.', $foreign_string);
145 if (! isset($existrel[$master_field])) {
146 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
147 . '(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)'
149 . '\'' . PMA_sqlAddslashes($db) . '\', '
150 . '\'' . PMA_sqlAddslashes($table) . '\', '
151 . '\'' . PMA_sqlAddslashes($master_field) . '\', '
152 . '\'' . PMA_sqlAddslashes($foreign_db) . '\', '
153 . '\'' . PMA_sqlAddslashes($foreign_table) . '\','
154 . '\'' . PMA_sqlAddslashes($foreign_field) . '\')';
155 } elseif ($existrel[$master_field]['foreign_db'] . '.' .$existrel[$master_field]['foreign_table'] . '.' . $existrel[$master_field]['foreign_field'] != $foreign_string) {
156 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation']) . ' SET'
157 . ' foreign_db = \'' . PMA_sqlAddslashes($foreign_db) . '\', '
158 . ' foreign_table = \'' . PMA_sqlAddslashes($foreign_table) . '\', '
159 . ' foreign_field = \'' . PMA_sqlAddslashes($foreign_field) . '\' '
160 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
161 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
162 . ' AND master_field = \'' . PMA_sqlAddslashes($master_field) . '\'';
163 } // end if... else....
164 } elseif (isset($existrel[$master_field])) {
165 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['relation'])
166 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
167 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
168 . ' AND master_field = \'' . PMA_sqlAddslashes($master_field) . '\'';
169 } // end if... else....
171 PMA_query_as_controluser($upd_query);
174 } // end if (updates for internal relations)
176 // u p d a t e s f o r f o r e i g n k e y s
177 // (for now, one index name only; we keep the definitions if the
178 // foreign db is not the same)
179 // I use $sql_query to be able to display directly the query via
182 if (isset($_REQUEST['destination_foreign'])) {
185 foreach ($_REQUEST['destination_foreign'] as $master_field_md5 => $foreign_string) {
187 // Map the fieldname's md5 back to it's real name
188 $master_field = $me_fields_name[$master_field_md5];
190 if (! empty($foreign_string)) {
191 list($foreign_db, $foreign_table, $foreign_field) = PMA_backquote_split($foreign_string);
192 if (!isset($existrel_foreign[$master_field])) {
193 // no key defined for this field
195 // The next few lines are repeated below, so they
196 // could be put in an include file
197 // Note: I tried to enclose the db and table name with
198 // backquotes but MySQL 4.0.16 did not like the syntax
199 // (for example: `base2`.`table1`)
201 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
202 . ' ADD FOREIGN KEY ('
203 . PMA_backquote($master_field) . ')'
206 . $foreign_table . '('
207 . $foreign_field . ')';
209 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
210 $sql_query .= ' ON DELETE ' . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
212 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
213 $sql_query .= ' ON UPDATE ' . $options_array[$_REQUEST['on_update'][$master_field_md5]];
216 $display_query .= $sql_query . "\n";
219 } elseif (PMA_backquote($existrel_foreign[$master_field]['foreign_db']) != $foreign_db
220 ||
PMA_backquote($existrel_foreign[$master_field]['foreign_table']) != $foreign_table
221 ||
PMA_backquote($existrel_foreign[$master_field]['foreign_field']) != $foreign_field
222 ||
($_REQUEST['on_delete'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_delete']) ?
$existrel_foreign[$master_field]['on_delete'] : ''))
223 ||
($_REQUEST['on_update'][$master_field_md5] != (!empty($existrel_foreign[$master_field]['on_update']) ?
$existrel_foreign[$master_field]['on_update'] : ''))
225 // another foreign key is already defined for this field
227 // an option has been changed for ON DELETE or ON UPDATE
229 // remove existing key
230 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
231 . ' DROP FOREIGN KEY '
232 . PMA_backquote($existrel_foreign[$master_field]['constraint']) . ';';
234 // I tried to send both in one query but it failed
235 PMA_DBI_query($sql_query);
236 $display_query .= $sql_query . "\n";
239 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
240 . ' ADD FOREIGN KEY ('
241 . PMA_backquote($master_field) . ')'
244 . $foreign_table . '('
245 . $foreign_field . ')';
247 if (! empty($_REQUEST['on_delete'][$master_field_md5])) {
248 $sql_query .= ' ON DELETE '
249 . $options_array[$_REQUEST['on_delete'][$master_field_md5]];
251 if (! empty($_REQUEST['on_update'][$master_field_md5])) {
252 $sql_query .= ' ON UPDATE '
253 . $options_array[$_REQUEST['on_update'][$master_field_md5]];
256 $display_query .= $sql_query . "\n";
258 } // end if... else....
259 } elseif (isset($existrel_foreign[$master_field])) {
260 $sql_query = 'ALTER TABLE ' . PMA_backquote($table)
261 . ' DROP FOREIGN KEY '
262 . PMA_backquote($existrel_foreign[$master_field]['constraint']);
264 $display_query .= $sql_query . "\n";
265 } // end if... else....
267 if (! empty($sql_query)) {
268 PMA_DBI_try_query($sql_query);
269 $tmp_error = PMA_DBI_getError();
270 if (! empty($tmp_error)) {
273 if (substr($tmp_error, 1, 4) == '1216'
274 ||
substr($tmp_error, 1, 4) == '1452') {
275 PMA_mysqlDie($tmp_error, $sql_query, FALSE, '', FALSE);
276 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
278 if (substr($tmp_error, 1, 4) == '1005') {
279 $message = PMA_Message
::warning('strForeignKeyError');
280 $message->addParam($master_field);
282 echo PMA_showMySQLDocu('manual_Table_types', 'InnoDB_foreign_key_constraints') . "\n";
288 if (!empty($display_query)) {
290 PMA_showMessage(__('Error'), null, 'error');
292 PMA_showMessage(__('Your SQL query has been executed successfully'), null, 'success');
295 } // end if isset($destination_foreign)
298 // U p d a t e s f o r d i s p l a y f i e l d
300 if ($cfgRelation['displaywork'] && isset($display_field)) {
303 if ($display_field != '') {
304 $upd_query = 'UPDATE ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
305 . ' SET display_field = \'' . PMA_sqlAddslashes($display_field) . '\''
306 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
307 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
309 $upd_query = 'DELETE FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
310 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
311 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\'';
313 } elseif ($display_field != '') {
314 $upd_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
315 . '(db_name, table_name, display_field) '
317 . '\'' . PMA_sqlAddslashes($db) . '\','
318 . '\'' . PMA_sqlAddslashes($table) . '\','
319 . '\'' . PMA_sqlAddslashes($display_field) . '\')';
323 PMA_query_as_controluser($upd_query);
327 // If we did an update, refresh our data
328 if (isset($destination) && $cfgRelation['relwork']) {
329 $existrel = PMA_getForeigners($db, $table, '', 'internal');
331 if (isset($destination_foreign) && PMA_foreignkey_supported($tbl_type)) {
332 $existrel_foreign = PMA_getForeigners($db, $table, '', 'foreign');
335 if ($cfgRelation['displaywork']) {
336 $disp = PMA_getDisplayField($db, $table);
345 echo '<form method="post" action="tbl_relation.php">' . "\n";
346 echo PMA_generate_common_hidden_inputs($db, $table);
351 if ($cfgRelation['relwork'] ||
PMA_foreignkey_supported($tbl_type)) {
352 // To choose relations we first need all tables names in current db
353 // and if the main table supports foreign keys
354 // we use SHOW TABLE STATUS because we need to find other tables of the
357 if (PMA_foreignkey_supported($tbl_type)) {
358 $tab_query = 'SHOW TABLE STATUS FROM ' . PMA_backquote($db);
359 // [0] of the row is the name
362 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($db);
363 // [0] of the row is the name
366 $tab_rs = PMA_DBI_query($tab_query, null, PMA_DBI_QUERY_STORE
);
367 $selectboxall[] = '';
368 $selectboxall_foreign[] = '';
370 while ($curr_table = PMA_DBI_fetch_row($tab_rs)) {
371 $current_table = new PMA_Table($curr_table[0], $db);
373 // explicitely ask for non-quoted list of indexed columns
374 $selectboxall = array_merge($selectboxall, $current_table->getUniqueColumns($backquoted = false));
376 // if foreign keys are supported, collect all keys from other
377 // tables of the same engine
378 if (PMA_foreignkey_supported($tbl_type)
379 && isset($curr_table[1])
380 && strtoupper($curr_table[1]) == $tbl_type) {
381 // explicitely ask for non-quoted list of indexed columns
382 // need to obtain backquoted values to support dots inside values
383 $selectboxall_foreign = array_merge($selectboxall_foreign, $current_table->getIndexedColumns($backquoted = true));
385 } // end while over tables
388 // Now find out the columns of our $table
389 // need to use PMA_DBI_QUERY_STORE with PMA_DBI_num_rows() in mysqli
390 $col_rs = PMA_DBI_try_query('SHOW COLUMNS FROM ' . PMA_backquote($table) . ';', null, PMA_DBI_QUERY_STORE
);
392 if ($col_rs && PMA_DBI_num_rows($col_rs) > 0) {
393 while ($row = PMA_DBI_fetch_assoc($col_rs)) {
396 $saved_row_cnt = count($save_row);
399 <legend
><?php
echo __('Relations'); ?
></legend
>
402 <tr
><th
><?php
echo __('Field'); ?
></th
>
404 if ($cfgRelation['relwork']) {
405 echo '<th>' . __('Internal relation');
406 if (PMA_foreignkey_supported($tbl_type)) {
407 echo PMA_showHint(__('An internal relation is not necessary when a corresponding FOREIGN KEY relation exists.'));
411 if (PMA_foreignkey_supported($tbl_type)) {
412 // this does not have to be translated, it's part of the MySQL syntax
413 echo '<th colspan="2">' . __('Foreign key constraint') . ' (' . $tbl_type . ')';
420 for ($i = 0; $i < $saved_row_cnt; $i++
) {
421 $myfield = $save_row[$i]['Field'];
422 // Use an md5 as array index to avoid having special characters in the name atttibure (see bug #1746964 )
423 $myfield_md5 = md5($myfield);
424 $myfield_html = htmlspecialchars($myfield);
426 <tr
class="<?php echo $odd_row ? 'odd' : 'even'; $odd_row = ! $odd_row; ?>">
428 <strong
><?php
echo $myfield_html; ?
></strong
>
429 <input type
="hidden" name
="fields_name[<?php echo $myfield_md5; ?>]" value
="<?php echo $myfield_html; ?>"/>
432 if ($cfgRelation['relwork']) {
434 <td
><select name
="destination[<?php echo $myfield_md5; ?>]">
436 // PMA internal relations
437 if (isset($existrel[$myfield])) {
438 $foreign_field = $existrel[$myfield]['foreign_db'] . '.'
439 . $existrel[$myfield]['foreign_table'] . '.'
440 . $existrel[$myfield]['foreign_field'];
442 $foreign_field = FALSE;
445 foreach ($selectboxall as $value) {
447 . '<option value="' . htmlspecialchars($value) . '"';
448 if ($foreign_field && $value == $foreign_field) {
449 echo ' selected="selected"';
452 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
455 // if the link defined in relationtable points to a foreign field
456 // that is not a key in the foreign table, we show the link
457 // (will not be shown with an arrow)
458 if ($foreign_field && !$seen_key) {
460 .'<option value="' . htmlspecialchars($foreign_field) . '"'
461 .' selected="selected"'
462 .'>' . $foreign_field . '</option>'. "\n";
468 } // end if (internal relations)
470 if (PMA_foreignkey_supported($tbl_type)) {
472 if (!empty($save_row[$i]['Key'])) {
474 <span
class="formelement">
475 <select name
="destination_foreign[<?php echo $myfield_md5; ?>]" class="referenced_column_dropdown">
477 if (isset($existrel_foreign[$myfield])) {
478 // need to backquote to support a dot character inside
480 $foreign_field = PMA_backquote($existrel_foreign[$myfield]['foreign_db']) . '.'
481 . PMA_backquote($existrel_foreign[$myfield]['foreign_table']) . '.'
482 . PMA_backquote($existrel_foreign[$myfield]['foreign_field']);
484 $foreign_field = FALSE;
487 $found_foreign_field = FALSE;
488 foreach ($selectboxall_foreign as $value) {
490 . '<option value="' . htmlspecialchars($value) . '"';
491 if ($foreign_field && $value == $foreign_field) {
492 echo ' selected="selected"';
493 $found_foreign_field = TRUE;
495 echo '>' . htmlspecialchars($value) . '</option>'. "\n";
498 // we did not find the foreign field in the tables of current db,
499 // must be defined in another db so show it to avoid erasing it
500 if (!$found_foreign_field && $foreign_field) {
502 . '<option value="' . htmlspecialchars($foreign_field) . '"';
503 echo ' selected="selected"';
504 echo '>' . $foreign_field . '</option>' . "\n";
510 <span
class="formelement">
512 // For ON DELETE and ON UPDATE, the default action
513 // is RESTRICT as per MySQL doc; however, a SHOW CREATE TABLE
514 // won't display the clause if it's set as RESTRICT.
515 PMA_generate_dropdown('ON DELETE',
516 'on_delete[' . $myfield_md5 . ']',
518 isset($existrel_foreign[$myfield]['on_delete']) ?
$existrel_foreign[$myfield]['on_delete']: 'RESTRICT');
520 echo '</span>' . "\n"
521 .'<span class="formelement">' . "\n";
523 PMA_generate_dropdown('ON UPDATE',
524 'on_update[' . $myfield_md5 . ']',
526 isset($existrel_foreign[$myfield]['on_update']) ?
$existrel_foreign[$myfield]['on_update']: 'RESTRICT');
527 echo '</span>' . "\n";
529 echo __('No index defined!');
530 } // end if (a key exists)
538 unset( $myfield, $myfield_md5, $myfield_html);
540 echo ' </table>' . "\n";
541 echo '</fieldset>' . "\n";
543 if ($cfgRelation['displaywork']) {
544 // Get "display_field" infos
545 $disp = PMA_getDisplayField($db, $table);
548 <label
><?php
echo __('Choose field to display') . ': '; ?
></label
>
549 <select name
="display_field" style
="vertical-align: middle">
550 <option value
="">---</option
>
552 foreach ($save_row AS $row) {
553 echo ' <option value="' . htmlspecialchars($row['Field']) . '"';
554 if (isset($disp) && $row['Field'] == $disp) {
555 echo ' selected="selected"';
557 echo '>' . htmlspecialchars($row['Field']) . '</option>'. "\n";
563 } // end if (displayworks)
565 <fieldset
class="tblFooters">
566 <input type
="submit" value
="<?php echo __('Save'); ?>" />
570 } // end if (we have columns in this table)
573 * Displays the footer
575 require_once './libraries/footer.inc.php';