Translated using Weblate.
[phpmyadmin.git] / js / sql.js
blob6f00c75b0b67af6ba77853d894ffefe2eb3ef1a6
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used wherever an sql query form is used
4  *
5  * @requires    jQuery
6  * @requires    js/functions.js
7  *
8  */
10 var $data_a;
12 /**
13  * decode a string URL_encoded
14  *
15  * @param string str
16  * @return string the URL-decoded string
17  */
18 function PMA_urldecode(str)
20     return decodeURIComponent(str.replace(/\+/g, '%20'));
23 function PMA_urlencode(str)
25     return encodeURIComponent(str).replace(/\%20/g, '+');
28 /**
29  * Get the field name for the current field.  Required to construct the query
30  * for grid editing
31  *
32  * @param   $this_field  jQuery object that points to the current field's tr
33  */
34 function getFieldName($this_field)
37     var this_field_index = $this_field.index();
38     // ltr or rtl direction does not impact how the DOM was generated
39     // check if the action column in the left exist
40     var left_action_exist = !$('#table_results').find('th:first').hasClass('draggable');
41     // number of column span for checkbox and Actions
42     var left_action_skip = left_action_exist ? $('#table_results').find('th:first').attr('colspan') - 1 : 0;
43     var field_name = $('#table_results').find('thead').find('th:eq('+ (this_field_index - left_action_skip) + ') a').text();
44     // happens when just one row (headings contain no a)
45     if ("" == field_name) {
46         field_name = $('#table_results').find('thead').find('th:eq('+ (this_field_index - left_action_skip) + ')').text();
47     }
49     field_name = $.trim(field_name);
51     return field_name;
55 /**#@+
56  * @namespace   jQuery
57  */
59 /**
60  * @description <p>Ajax scripts for sql and browse pages</p>
61  *
62  * Actions ajaxified here:
63  * <ul>
64  * <li>Retrieve results of an SQL query</li>
65  * <li>Paginate the results table</li>
66  * <li>Sort the results table</li>
67  * <li>Change table according to display options</li>
68  * <li>Grid editing of data</li>
69  * </ul>
70  *
71  * @name        document.ready
72  * @memberOf    jQuery
73  */
74 $(document).ready(function() {
75     /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
76     $('input#bkm_label').keyup(function() {
77         $('input#id_bkm_all_users, input#id_bkm_replace')
78             .parent()
79             .toggle($(this).attr('value').length > 0);
80     }).trigger('keyup');
82     /**
83      * Attach the {@link makegrid} function to a custom event, which will be
84      * triggered manually everytime the table of results is reloaded
85      * @memberOf    jQuery
86      */
87     $("#sqlqueryresults").live('makegrid', function() {
88         PMA_makegrid($('#table_results')[0]);
89     });
91     /**
92      * Append the "Show/Hide query box" message to the query input form
93      *
94      * @memberOf jQuery
95      * @name    appendToggleSpan
96      */
97     // do not add this link more than once
98     if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
99         $('<a id="togglequerybox"></a>')
100         .html(PMA_messages['strHideQueryBox'])
101         .appendTo("#sqlqueryform")
102         // initially hidden because at this point, nothing else
103         // appears under the link
104         .hide();
106         // Attach the toggling of the query box visibility to a click
107         $("#togglequerybox").bind('click', function() {
108             var $link = $(this);
109             $link.siblings().slideToggle("fast");
110             if ($link.text() == PMA_messages['strHideQueryBox']) {
111                 $link.text(PMA_messages['strShowQueryBox']);
112                 // cheap trick to add a spacer between the menu tabs
113                 // and "Show query box"; feel free to improve!
114                 $('#togglequerybox_spacer').remove();
115                 $link.before('<br id="togglequerybox_spacer" />');
116             } else {
117                 $link.text(PMA_messages['strHideQueryBox']);
118             }
119             // avoid default click action
120             return false;
121         });
122     }
125     /**
126      * Event handler for sqlqueryform.ajax button_submit_query 
127      *
128      * @memberOf    jQuery
129      */
130     $("#button_submit_query").live('click', function(event) {
131         var $form = $(this).closest("form");
132         // the Go button related to query submission was clicked,
133         // instead of the one related to Bookmarks, so empty the
134         // id_bookmark selector to avoid misinterpretation in 
135         // import.php about what needs to be done
136         $form.find("select[name=id_bookmark]").attr("value","");
137         // let normal event propagation happen
138     });
139   
140     /**
141      * Event handler for hitting enter on sqlqueryform bookmark_variable
142      * (the Variable textfield in Bookmarked SQL query section)
143      *
144      * @memberOf    jQuery
145      */
146     $("input[name=bookmark_variable]").bind("keypress", function(event) {
147         // force the 'Enter Key' to implicitly click the #button_submit_bookmark
148         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
149         if (keycode == 13) { // keycode for enter key
150             // When you press enter in the sqlqueryform, which
151             // has 2 submit buttons, the default is to run the
152             // #button_submit_query, because of the tabindex 
153             // attribute. 
154             // This submits #button_submit_bookmark instead,
155             // because when you are in the Bookmarked SQL query
156             // section and hit enter, you expect it to do the
157             // same action as the Go button in that section.
158             $("#button_submit_bookmark").click();
159            return false;
160         } else  {
161            return true;
162         }
163     });
165     /**
166      * Ajax Event handler for 'SQL Query Submit'
167      *
168      * @see         PMA_ajaxShowMessage()
169      * @see         $cfg['AjaxEnable']
170      * @memberOf    jQuery
171      * @name        sqlqueryform_submit
172      */
173     $("#sqlqueryform.ajax").live('submit', function(event) {
174         event.preventDefault();
176         var $form = $(this);
177         if (! checkSqlQuery($form[0])) {
178             return false;
179         }
181         // remove any div containing a previous error message
182         $('.error').remove();
184         var $msgbox = PMA_ajaxShowMessage();
185         var $sqlqueryresults = $('#sqlqueryresults');
187         PMA_prepareForAjaxRequest($form);
189         $.post($form.attr('action'), $form.serialize() , function(data) {
190             if (data.success == true) {
191                 // success happens if the query returns rows or not
192                 //
193                 // fade out previous messages, if any
194                 $('.success').fadeOut();
195                 $('.sqlquery_message').fadeOut();
196                 // show a message that stays on screen
197                 if (typeof data.action_bookmark != 'undefined') {
198                     // view only
199                     if ('1' == data.action_bookmark) {
200                         $('#sqlquery').text(data.sql_query);
201                         // send to codemirror if possible
202                         setQuery(data.sql_query);
203                     }
204                     // delete
205                     if ('2' == data.action_bookmark) {
206                         $("#id_bookmark option[value='" + data.id_bookmark + "']").remove();
207                     }
208                     $('#sqlqueryform').before(data.message);
209                 } else if (typeof data.sql_query != 'undefined') {
210                     $('<div class="sqlquery_message"></div>')
211                      .html(data.sql_query)
212                      .insertBefore('#sqlqueryform');
213                     // unnecessary div that came from data.sql_query
214                     $('.notice').remove();
215                 } else {
216                     $('#sqlqueryform').before(data.message);
217                 }
218                 $sqlqueryresults.show();
219                 // this happens if a USE command was typed
220                 if (typeof data.reload != 'undefined') {
221                     // Unbind the submit event before reloading. See bug #3295529
222                     $("#sqlqueryform.ajax").die('submit');
223                     $form.find('input[name=db]').val(data.db);
224                     // need to regenerate the whole upper part
225                     $form.find('input[name=ajax_request]').remove();
226                     $form.append('<input type="hidden" name="reload" value="true" />');
227                     $.post('db_sql.php', $form.serialize(), function(data) {
228                         $('body').html(data);
229                     }); // end inner post
230                 }
231             } else if (data.success == false ) {
232                 // show an error message that stays on screen
233                 $('#sqlqueryform').before(data.error);
234                 $sqlqueryresults.hide();
235             }  else {
236                 // real results are returned
237                 // fade out previous messages, if any
238                 $('.success').fadeOut();
239                 $('.sqlquery_message').fadeOut();
240                 var $received_data = $(data);
241                 var $zero_row_results = $received_data.find('textarea[name="sql_query"]');
242                 // if zero rows are returned from the query execution
243                 if ($zero_row_results.length > 0) {
244                     $('#sqlquery').val($zero_row_results.val());
245                     setQuery($('#sqlquery').val());
246                 } else {
247                     $sqlqueryresults
248                      .show()
249                      .html(data)
250                      .trigger('makegrid');
251                     $('#togglequerybox').show();
252                     if( $('#sqlqueryform input[name="retain_query_box"]').is(':checked') != true ) {
253                         if ($("#togglequerybox").siblings(":visible").length > 0) {
254                             $("#togglequerybox").trigger('click');
255                         }
256                     }
257                     PMA_init_slider();
258                 }
259             }
260             PMA_ajaxRemoveMessage($msgbox);
261         }); // end $.post()
262     }); // end SQL Query submit
264     /**
265      * Ajax Event handlers for Paginating the results table
266      */
268     /**
269      * Paginate when we click any of the navigation buttons
270      * (only if the element has the ajax class, see $cfg['AjaxEnable'])
271      * @memberOf    jQuery
272      * @name        paginate_nav_button_click
273      * @uses        PMA_ajaxShowMessage()
274      * @see         $cfg['AjaxEnable']
275      */
276     $("input[name=navig].ajax").live('click', function(event) {
277         /** @lends jQuery */
278         event.preventDefault();
280         var $msgbox = PMA_ajaxShowMessage();
282         /**
283          * @var $form    Object referring to the form element that paginates the results table
284          */
285         var $form = $(this).parent("form");
287         PMA_prepareForAjaxRequest($form);
289         $.post($form.attr('action'), $form.serialize(), function(data) {
290             $("#sqlqueryresults")
291              .html(data)
292              .trigger('makegrid');
293             PMA_init_slider();
295             PMA_ajaxRemoveMessage($msgbox);
296         }); // end $.post()
297     }); // end Paginate results table
299     /**
300      * Paginate results with Page Selector dropdown
301      * @memberOf    jQuery
302      * @name        paginate_dropdown_change
303      * @see         $cfg['AjaxEnable']
304      */
305     $("#pageselector").live('change', function(event) {
306         var $form = $(this).parent("form");
308         if ($(this).hasClass('ajax')) {
309             event.preventDefault();
311             var $msgbox = PMA_ajaxShowMessage();
313             $.post($form.attr('action'), $form.serialize() + '&ajax_request=true', function(data) {
314                 $("#sqlqueryresults")
315                  .html(data)
316                  .trigger('makegrid');
317                 PMA_init_slider();
318                 PMA_ajaxRemoveMessage($msgbox);
319             }); // end $.post()
320         } else {
321             $form.submit();
322         }
324     }); // end Paginate results with Page Selector
326     /**
327      * Ajax Event handler for sorting the results table
328      * @memberOf    jQuery
329      * @name        table_results_sort_click
330      * @see         $cfg['AjaxEnable']
331      */
332     $("#table_results.ajax").find("a[title=Sort]").live('click', function(event) {
333         event.preventDefault();
335         var $msgbox = PMA_ajaxShowMessage();
337         $anchor = $(this);
339         $.get($anchor.attr('href'), $anchor.serialize() + '&ajax_request=true', function(data) {
340             $("#sqlqueryresults")
341              .html(data)
342              .trigger('makegrid');
343             PMA_ajaxRemoveMessage($msgbox);
344         }); // end $.get()
345     }); //end Sort results table
347     /**
348      * Ajax Event handler for the display options
349      * @memberOf    jQuery
350      * @name        displayOptionsForm_submit
351      * @see         $cfg['AjaxEnable']
352      */
353     $("#displayOptionsForm.ajax").live('submit', function(event) {
354         event.preventDefault();
356         $form = $(this);
358         $.post($form.attr('action'), $form.serialize() + '&ajax_request=true' , function(data) {
359             $("#sqlqueryresults")
360              .html(data)
361              .trigger('makegrid');
362             PMA_init_slider();
363         }); // end $.post()
364     }); //end displayOptionsForm handler
367  * Ajax Event for table row change
368  * */
369     $("#resultsForm.ajax .mult_submit[value=edit]").live('click', function(event){
370         event.preventDefault();
372         /*Check whether atleast one row is selected for change*/
373         if ($("#table_results tbody tr, #table_results tbody tr td").hasClass("marked")) {
374             var div = $('<div id="change_row_dialog"></div>');
376             /**
377              *  @var    button_options  Object that stores the options passed to jQueryUI
378              *                          dialog
379              */
380             var button_options = {};
381             // in the following function we need to use $(this)
382             button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();};
384             var button_options_error = {};
385             button_options_error[PMA_messages['strOK']] = function() {$(this).dialog('close').remove();};
386             var $form = $("#resultsForm");
387             var $msgbox = PMA_ajaxShowMessage();
389             $.get( $form.attr('action'), $form.serialize()+"&ajax_request=true&submit_mult=row_edit", function(data) {
390                 //in the case of an error, show the error message returned.
391                 if (data.success != undefined && data.success == false) {
392                     div
393                     .append(data.error)
394                     .dialog({
395                         title: PMA_messages['strChangeTbl'],
396                         height: 230,
397                         width: 900,
398                         open: PMA_verifyColumnsProperties,
399                         close: function(event, ui) {
400                             $('#change_row_dialog').remove();
401                         },
402                         buttons : button_options_error
403                     }); // end dialog options
404                 } else {
405                     div
406                     .append(data)
407                     .dialog({
408                         title: PMA_messages['strChangeTbl'],
409                         height: 600,
410                         width: 900,
411                         open: PMA_verifyColumnsProperties,
412                         close: function(event, ui) {
413                             $('#change_row_dialog').remove();
414                         },
415                         buttons : button_options
416                     })
417                     //Remove the top menu container from the dialog
418                     .find("#topmenucontainer").hide()
419                     ; // end dialog options
420                     $(".insertRowTable").addClass("ajax");
421                     $("#buttonYes").addClass("ajax");
422                 }
423                 PMA_ajaxRemoveMessage($msgbox);
424             }); // end $.get()
425         } else {
426             PMA_ajaxShowMessage(PMA_messages['strNoRowSelected']);
427         }
428     });
431  * Click action for "Go" button in ajax dialog insertForm -> insertRowTable
432  */
433     $("#insertForm .insertRowTable.ajax input[type=submit]").live('click', function(event) {
434         event.preventDefault();
435         /**
436          *  @var    the_form    object referring to the insert form
437          */
438         var $form = $("#insertForm");
439         PMA_prepareForAjaxRequest($form);
440         //User wants to submit the form
441         $.post($form.attr('action'), $form.serialize(), function(data) {
442             if (data.success == true) {
443                 PMA_ajaxShowMessage(data.message);
444                 if ($("#pageselector").length != 0) {
445                     $("#pageselector").trigger('change');
446                 } else {
447                     $("input[name=navig].ajax").trigger('click');
448                 }
450             } else {
451                 PMA_ajaxShowMessage(data.error, false);
452                 $("#table_results tbody tr.marked .multi_checkbox " +
453                         ", #table_results tbody tr td.marked .multi_checkbox").prop("checked", false);
454                 $("#table_results tbody tr.marked .multi_checkbox " +
455                         ", #table_results tbody tr td.marked .multi_checkbox").removeClass("last_clicked");
456                 $("#table_results tbody tr" +
457                         ", #table_results tbody tr td").removeClass("marked");
458             }
459             if ($("#change_row_dialog").length > 0) {
460                 $("#change_row_dialog").dialog("close").remove();
461             }
462             /**Update the row count at the tableForm*/
463             $("#result_query").remove();
464             $("#sqlqueryresults").prepend(data.sql_query);
465             $("#result_query .notice").remove();
466             $("#result_query").prepend((data.message));
467         }); // end $.post()
468     }); // end insert table button "Go"
470 /**$("#buttonYes.ajax").live('click'
471  * Click action for #buttonYes button in ajax dialog insertForm
472  */
473     $("#buttonYes.ajax").live('click', function(event){
474         event.preventDefault();
475         /**
476          *  @var    the_form    object referring to the insert form
477          */
478         var $form = $("#insertForm");
479         /**Get the submit type and the after insert type in the form*/
480         var selected_submit_type = $("#insertForm").find("#actions_panel .control_at_footer option:selected").attr('value');
481         var selected_after_insert = $("#insertForm").find("#actions_panel select[name=after_insert] option:selected").attr('value');
482         $("#result_query").remove();
483         PMA_prepareForAjaxRequest($form);
484         //User wants to submit the form
485         $.post($form.attr('action'), $form.serialize() , function(data) {
486             if (data.success == true) {
487                 PMA_ajaxShowMessage(data.message);
488                 if (selected_submit_type == "showinsert") {
489                     $("#sqlqueryresults").prepend(data.sql_query);
490                     $("#result_query .notice").remove();
491                     $("#result_query").prepend(data.message);
492                     $("#table_results tbody tr.marked .multi_checkbox " +
493                         ", #table_results tbody tr td.marked .multi_checkbox").prop("checked", false);
494                     $("#table_results tbody tr.marked .multi_checkbox " +
495                         ", #table_results tbody tr td.marked .multi_checkbox").removeClass("last_clicked");
496                     $("#table_results tbody tr" +
497                         ", #table_results tbody tr td").removeClass("marked");
498                 } else {
499                     if ($("#pageselector").length != 0) {
500                         $("#pageselector").trigger('change');
501                     } else {
502                         $("input[name=navig].ajax").trigger('click');
503                     }
504                     $("#result_query").remove();
505                     $("#sqlqueryresults").prepend(data.sql_query);
506                     $("#result_query .notice").remove();
507                     $("#result_query").prepend((data.message));
508                 }
509             } else {
510                 PMA_ajaxShowMessage(data.error, false);
511                 $("#table_results tbody tr.marked .multi_checkbox " +
512                     ", #table_results tbody tr td.marked .multi_checkbox").prop("checked", false);
513                 $("#table_results tbody tr.marked .multi_checkbox " +
514                     ", #table_results tbody tr td.marked .multi_checkbox").removeClass("last_clicked");
515                 $("#table_results tbody tr" +
516                     ", #table_results tbody tr td").removeClass("marked");
517             }
518             if ($("#change_row_dialog").length > 0) {
519                 $("#change_row_dialog").dialog("close").remove();
520             }
521         }); // end $.post()
522     });
524 }, 'top.frame_content'); // end $(document).ready()
528  * Starting from some th, change the class of all td under it.
529  * If isAddClass is specified, it will be used to determine whether to add or remove the class.
530  */
531 function PMA_changeClassForColumn($this_th, newclass, isAddClass)
533     // index 0 is the th containing the big T
534     var th_index = $this_th.index();
535     var has_big_t = !$this_th.closest('tr').children(':first').hasClass('column_heading');
536     // .eq() is zero-based
537     if (has_big_t) {
538         th_index--;
539     }
540     var $tds = $this_th.closest('table').find('tbody tr').find('td.data:eq('+th_index+')');
541     if (isAddClass == undefined) {
542         $tds.toggleClass(newclass);
543     } else {
544         $tds.toggleClass(newclass, isAddClass);
545     }
548 $(document).ready(function() {
550     $('.browse_foreign').live('click', function(e) {
551         e.preventDefault();
552         window.open(this.href, 'foreigners', 'width=640,height=240,scrollbars=yes,resizable=yes');
553         $anchor = $(this);
554         $anchor.addClass('browse_foreign_clicked');
555         return false;
556     });
558     /**
559      * vertical column highlighting in horizontal mode when hovering over the column header
560      */
561     $('.column_heading.pointer').live('hover', function(e) {
562         PMA_changeClassForColumn($(this), 'hover', e.type == 'mouseenter');
563         });
565     /**
566      * vertical column marking in horizontal mode when clicking the column header
567      */
568     $('.column_heading.marker').live('click', function() {
569         PMA_changeClassForColumn($(this), 'marked');
570         });
572     /**
573      * create resizable table
574      */
575     $("#sqlqueryresults").trigger('makegrid');
579  * Profiling Chart
580  */
581 function makeProfilingChart()
583     if ($('#profilingchart').length == 0) {
584         return;
585     }
587     var data = new Array();
588     $.each(jQuery.parseJSON($('#profilingchart').html()),function(key,value) {
589         data.push([key,parseFloat(value)]);
590     });
592     // Prevent the user from seeing the JSON code
593     $('div#profilingchart').html('').show();
595     PMA_createProfilingChart(data);
599 /**#@- */