Translated using Weblate (Bulgarian)
[phpmyadmin.git] / js / sql.js
blob50665c62242a55650d5dc1d8f99b960660867e1b
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 /* global Stickyfill */
11 /* global isStorageSupported */ // js/config.js
12 /* global codeMirrorEditor */ // js/functions.js
13 /* global MicroHistory */ // js/microhistory.js
14 /* global makeGrid */ // js/makegrid.js
16 var Sql = {};
18 /**
19  * decode a string URL_encoded
20  *
21  * @param string str
22  * @return string the URL-decoded string
23  */
24 Sql.urlDecode = function (str) {
25     if (typeof str !== 'undefined') {
26         return decodeURIComponent(str.replace(/\+/g, '%20'));
27     }
30 /**
31  * endecode a string URL_decoded
32  *
33  * @param string str
34  * @return string the URL-encoded string
35  */
36 Sql.urlEncode = function (str) {
37     if (typeof str !== 'undefined') {
38         return encodeURIComponent(str).replace(/%20/g, '+');
39     }
42 /**
43  * Saves SQL query in local storage or cookie
44  *
45  * @param string SQL query
46  * @return void
47  */
48 Sql.autoSave = function (query) {
49     if (isStorageSupported('localStorage')) {
50         window.localStorage.autoSavedSql = query;
51     } else {
52         Cookies.set('autoSavedSql', query);
53     }
56 /**
57  * Saves SQL query in local storage or cookie
58  *
59  * @param string database name
60  * @param string table name
61  * @param string SQL query
62  * @return void
63  */
64 Sql.showThisQuery = function (db, table, query) {
65     var showThisQueryObject = {
66         'db': db,
67         'table': table,
68         'query': query
69     };
70     if (isStorageSupported('localStorage')) {
71         window.localStorage.showThisQuery = 1;
72         window.localStorage.showThisQueryObject = JSON.stringify(showThisQueryObject);
73     } else {
74         Cookies.set('showThisQuery', 1);
75         Cookies.set('showThisQueryObject', JSON.stringify(showThisQueryObject));
76     }
79 /**
80  * Set query to codemirror if show this query is
81  * checked and query for the db and table pair exists
82  */
83 Sql.setShowThisQuery = function () {
84     var db = $('input[name="db"]').val();
85     var table = $('input[name="table"]').val();
86     if (isStorageSupported('localStorage')) {
87         if (window.localStorage.showThisQueryObject !== undefined) {
88             var storedDb = JSON.parse(window.localStorage.showThisQueryObject).db;
89             var storedTable = JSON.parse(window.localStorage.showThisQueryObject).table;
90             var storedQuery = JSON.parse(window.localStorage.showThisQueryObject).query;
91         }
92         if (window.localStorage.showThisQuery !== undefined
93             && window.localStorage.showThisQuery === '1') {
94             $('input[name="show_query"]').prop('checked', true);
95             if (db === storedDb && table === storedTable) {
96                 if (codeMirrorEditor) {
97                     codeMirrorEditor.setValue(storedQuery);
98                 } else if (document.sqlform) {
99                     document.sqlform.sql_query.value = storedQuery;
100                 }
101             }
102         } else {
103             $('input[name="show_query"]').prop('checked', false);
104         }
105     }
109  * Saves SQL query with sort in local storage or cookie
111  * @param string SQL query
112  * @return void
113  */
114 Sql.autoSaveWithSort = function (query) {
115     if (query) {
116         if (isStorageSupported('localStorage')) {
117             window.localStorage.autoSavedSqlSort = query;
118         } else {
119             Cookies.set('autoSavedSqlSort', query);
120         }
121     }
125  * Clear saved SQL query with sort in local storage or cookie
127  * @return void
128  */
129 Sql.clearAutoSavedSort = function () {
130     if (isStorageSupported('localStorage')) {
131         window.localStorage.removeItem('auto_saved_sql_sort');
132     } else {
133         Cookies.set('auto_saved_sql_sort', '');
134     }
138  * Get the field name for the current field.  Required to construct the query
139  * for grid editing
141  * @param $tableResults enclosing results table
142  * @param $thisField    jQuery object that points to the current field's tr
143  */
144 Sql.getFieldName = function ($tableResults, $thisField) {
145     var thisFieldIndex = $thisField.index();
146     // ltr or rtl direction does not impact how the DOM was generated
147     // check if the action column in the left exist
148     var leftActionExist = !$tableResults.find('th:first').hasClass('draggable');
149     // number of column span for checkbox and Actions
150     var leftActionSkip = leftActionExist ? $tableResults.find('th:first').attr('colspan') - 1 : 0;
152     // If this column was sorted, the text of the a element contains something
153     // like <small>1</small> that is useful to indicate the order in case
154     // of a sort on multiple columns; however, we dont want this as part
155     // of the column name so we strip it ( .clone() to .end() )
156     var fieldName = $tableResults
157         .find('thead')
158         .find('th:eq(' + (thisFieldIndex - leftActionSkip) + ') a')
159         .clone()    // clone the element
160         .children() // select all the children
161         .remove()   // remove all of them
162         .end()      // go back to the selected element
163         .text();    // grab the text
164     // happens when just one row (headings contain no a)
165     if (fieldName === '') {
166         var $heading = $tableResults.find('thead').find('th:eq(' + (thisFieldIndex - leftActionSkip) + ')').children('span');
167         // may contain column comment enclosed in a span - detach it temporarily to read the column name
168         var $tempColComment = $heading.children().detach();
169         fieldName = $heading.text();
170         // re-attach the column comment
171         $heading.append($tempColComment);
172     }
174     fieldName = $.trim(fieldName);
176     return fieldName;
180  * Unbind all event handlers before tearing down a page
181  */
182 AJAX.registerTeardown('sql.js', function () {
183     $(document).off('click', 'a.delete_row.ajax');
184     $(document).off('submit', '.bookmarkQueryForm');
185     $('input#bkm_label').off('input');
186     $(document).off('makegrid', '.sqlqueryresults');
187     $(document).off('stickycolumns', '.sqlqueryresults');
188     $('#togglequerybox').off('click');
189     $(document).off('click', '#button_submit_query');
190     $(document).off('change', '#id_bookmark');
191     $('input[name=\'bookmark_variable\']').off('keypress');
192     $(document).off('submit', '#sqlqueryform.ajax');
193     $(document).off('click', 'input[name=navig].ajax');
194     $(document).off('submit', 'form[name=\'displayOptionsForm\'].ajax');
195     $(document).off('mouseenter', 'th.column_heading.pointer');
196     $(document).off('mouseleave', 'th.column_heading.pointer');
197     $(document).off('click', 'th.column_heading.marker');
198     $(document).off('scroll', window);
199     $(document).off('keyup', '.filter_rows');
200     $(document).off('click', '#printView');
201     if (codeMirrorEditor) {
202         codeMirrorEditor.off('change');
203     } else {
204         $('#sqlquery').off('input propertychange');
205     }
206     $('body').off('click', '.navigation .showAllRows');
207     $('body').off('click', 'a.browse_foreign');
208     $('body').off('click', '#simulate_dml');
209     $('body').off('keyup', '#sqlqueryform');
210     $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
214  * @description <p>Ajax scripts for sql and browse pages</p>
216  * Actions ajaxified here:
217  * <ul>
218  * <li>Retrieve results of an SQL query</li>
219  * <li>Paginate the results table</li>
220  * <li>Sort the results table</li>
221  * <li>Change table according to display options</li>
222  * <li>Grid editing of data</li>
223  * <li>Saving a bookmark</li>
224  * </ul>
226  * @name        document.ready
227  * @memberOf    jQuery
228  */
229 AJAX.registerOnload('sql.js', function () {
230     if (codeMirrorEditor || document.sqlform) {
231         Sql.setShowThisQuery();
232     }
233     $(function () {
234         if (codeMirrorEditor) {
235             codeMirrorEditor.on('change', function () {
236                 Sql.autoSave(codeMirrorEditor.getValue());
237             });
238         } else {
239             $('#sqlquery').on('input propertychange', function () {
240                 Sql.autoSave($('#sqlquery').val());
241             });
242             var useLocalStorageValue = isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined';
243             // Save sql query with sort
244             if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
245                 $('select[name="sql_query"]').on('change', function () {
246                     Sql.autoSaveWithSort($(this).val());
247                 });
248                 $('.sortlink').on('click', function () {
249                     Sql.clearAutoSavedSort();
250                 });
251             } else {
252                 Sql.clearAutoSavedSort();
253             }
254             // If sql query with sort for current table is stored, change sort by key select value
255             var sortStoredQuery = useLocalStorageValue ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
256             if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
257                 $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
258             }
259         }
260     });
262     // Delete row from SQL results
263     $(document).on('click', 'a.delete_row.ajax', function (e) {
264         e.preventDefault();
265         var question =  Functions.sprintf(Messages.strDoYouReally, Functions.escapeHtml($(this).closest('td').find('div').text()));
266         var $link = $(this);
267         $link.confirm(question, $link.attr('href'), function (url) {
268             Functions.ajaxShowMessage();
269             var argsep = CommonParams.get('arg_separator');
270             var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
271             var postData = $link.getPostData();
272             if (postData) {
273                 params += argsep + postData;
274             }
275             $.post(url, params, function (data) {
276                 if (data.success) {
277                     Functions.ajaxShowMessage(data.message);
278                     $link.closest('tr').remove();
279                 } else {
280                     Functions.ajaxShowMessage(data.error, false);
281                 }
282             });
283         });
284     });
286     // Ajaxification for 'Bookmark this SQL query'
287     $(document).on('submit', '.bookmarkQueryForm', function (e) {
288         e.preventDefault();
289         Functions.ajaxShowMessage();
290         var argsep = CommonParams.get('arg_separator');
291         $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
292             if (data.success) {
293                 Functions.ajaxShowMessage(data.message);
294             } else {
295                 Functions.ajaxShowMessage(data.error, false);
296             }
297         });
298     });
300     /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
301     $('input#bkm_label').on('input', function () {
302         $('input#id_bkm_all_users, input#id_bkm_replace')
303             .parent()
304             .toggle($(this).val().length > 0);
305     }).trigger('input');
307     /**
308      * Attach Event Handler for 'Copy to clipbpard
309      */
310     $(document).on('click', '#copyToClipBoard', function (event) {
311         event.preventDefault();
313         var textArea = document.createElement('textarea');
315         //
316         // *** This styling is an extra step which is likely not required. ***
317         //
318         // Why is it here? To ensure:
319         // 1. the element is able to have focus and selection.
320         // 2. if element was to flash render it has minimal visual impact.
321         // 3. less flakyness with selection and copying which **might** occur if
322         //    the textarea element is not visible.
323         //
324         // The likelihood is the element won't even render, not even a flash,
325         // so some of these are just precautions. However in IE the element
326         // is visible whilst the popup box asking the user for permission for
327         // the web page to copy to the clipboard.
328         //
330         // Place in top-left corner of screen regardless of scroll position.
331         textArea.style.position = 'fixed';
332         textArea.style.top = 0;
333         textArea.style.left = 0;
335         // Ensure it has a small width and height. Setting to 1px / 1em
336         // doesn't work as this gives a negative w/h on some browsers.
337         textArea.style.width = '2em';
338         textArea.style.height = '2em';
340         // We don't need padding, reducing the size if it does flash render.
341         textArea.style.padding = 0;
343         // Clean up any borders.
344         textArea.style.border = 'none';
345         textArea.style.outline = 'none';
346         textArea.style.boxShadow = 'none';
348         // Avoid flash of white box if rendered for any reason.
349         textArea.style.background = 'transparent';
351         textArea.value = '';
353         $('#serverinfo a').each(function () {
354             textArea.value += $(this).text().split(':')[1].trim() + '/';
355         });
356         textArea.value += '\t\t' + window.location.href;
357         textArea.value += '\n';
358         $('.success').each(function () {
359             textArea.value += $(this).text() + '\n\n';
360         });
362         $('.sql pre').each(function () {
363             textArea.value += $(this).text() + '\n\n';
364         });
366         $('.table_results .column_heading a').each(function () {
367             // Don't copy ordering number text within <small> tag
368             textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
369         });
371         textArea.value += '\n';
372         $('.table_results tbody tr').each(function () {
373             $(this).find('.data span').each(function () {
374                 textArea.value += $(this).text() + '\t';
375             });
376             textArea.value += '\n';
377         });
379         document.body.appendChild(textArea);
381         textArea.select();
383         try {
384             document.execCommand('copy');
385         } catch (err) {
386             alert('Sorry! Unable to copy');
387         }
389         document.body.removeChild(textArea);
390     }); // end of Copy to Clipboard action
392     /**
393      * Attach Event Handler for 'Print' link
394      */
395     $(document).on('click', '#printView', function (event) {
396         event.preventDefault();
398         // Take to preview mode
399         Functions.printPreview();
400     }); // end of 'Print' action
402     /**
403      * Attach the {@link makegrid} function to a custom event, which will be
404      * triggered manually everytime the table of results is reloaded
405      * @memberOf    jQuery
406      */
407     $(document).on('makegrid', '.sqlqueryresults', function () {
408         $('.table_results').each(function () {
409             makeGrid(this);
410         });
411     });
413     /**
414      * Append the "Show/Hide query box" message to the query input form
415      *
416      * @memberOf jQuery
417      * @name    appendToggleSpan
418      */
419     // do not add this link more than once
420     if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
421         $('<a id="togglequerybox"></a>')
422             .html(Messages.strHideQueryBox)
423             .appendTo('#sqlqueryform')
424         // initially hidden because at this point, nothing else
425         // appears under the link
426             .hide();
428         // Attach the toggling of the query box visibility to a click
429         $('#togglequerybox').on('click', function () {
430             var $link = $(this);
431             $link.siblings().slideToggle('fast');
432             if ($link.text() === Messages.strHideQueryBox) {
433                 $link.text(Messages.strShowQueryBox);
434                 // cheap trick to add a spacer between the menu tabs
435                 // and "Show query box"; feel free to improve!
436                 $('#togglequerybox_spacer').remove();
437                 $link.before('<br id="togglequerybox_spacer">');
438             } else {
439                 $link.text(Messages.strHideQueryBox);
440             }
441             // avoid default click action
442             return false;
443         });
444     }
447     /**
448      * Event handler for sqlqueryform.ajax button_submit_query
449      *
450      * @memberOf    jQuery
451      */
452     $(document).on('click', '#button_submit_query', function () {
453         $('.success,.error').hide();
454         // hide already existing error or success message
455         var $form = $(this).closest('form');
456         // the Go button related to query submission was clicked,
457         // instead of the one related to Bookmarks, so empty the
458         // id_bookmark selector to avoid misinterpretation in
459         // import.php about what needs to be done
460         $form.find('select[name=id_bookmark]').val('');
461         // let normal event propagation happen
462         if (isStorageSupported('localStorage')) {
463             window.localStorage.removeItem('autoSavedSql');
464         } else {
465             Cookies.set('autoSavedSql', '');
466         }
467         var isShowQuery =  $('input[name="show_query"]').is(':checked');
468         if (isShowQuery) {
469             window.localStorage.showThisQuery = '1';
470             var db = $('input[name="db"]').val();
471             var table = $('input[name="table"]').val();
472             var query;
473             if (codeMirrorEditor) {
474                 query = codeMirrorEditor.getValue();
475             } else {
476                 query = $('#sqlquery').val();
477             }
478             Sql.showThisQuery(db, table, query);
479         } else {
480             window.localStorage.showThisQuery = '0';
481         }
482     });
484     /**
485      * Event handler to show appropiate number of variable boxes
486      * based on the bookmarked query
487      */
488     $(document).on('change', '#id_bookmark', function () {
489         var varCount = $(this).find('option:selected').data('varcount');
490         if (typeof varCount === 'undefined') {
491             varCount = 0;
492         }
494         var $varDiv = $('#bookmark_variables');
495         $varDiv.empty();
496         for (var i = 1; i <= varCount; i++) {
497             $varDiv.append($('<label for="bookmark_variable_' + i + '">' + Functions.sprintf(Messages.strBookmarkVariable, i) + '</label>'));
498             $varDiv.append($('<input type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmark_variable_' + i + '">'));
499         }
501         if (varCount === 0) {
502             $varDiv.parent('.formelement').hide();
503         } else {
504             $varDiv.parent('.formelement').show();
505         }
506     });
508     /**
509      * Event handler for hitting enter on sqlqueryform bookmark_variable
510      * (the Variable textfield in Bookmarked SQL query section)
511      *
512      * @memberOf    jQuery
513      */
514     $('input[name=bookmark_variable]').on('keypress', function (event) {
515         // force the 'Enter Key' to implicitly click the #button_submit_bookmark
516         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
517         if (keycode === 13) { // keycode for enter key
518             // When you press enter in the sqlqueryform, which
519             // has 2 submit buttons, the default is to run the
520             // #button_submit_query, because of the tabindex
521             // attribute.
522             // This submits #button_submit_bookmark instead,
523             // because when you are in the Bookmarked SQL query
524             // section and hit enter, you expect it to do the
525             // same action as the Go button in that section.
526             $('#button_submit_bookmark').trigger('click');
527             return false;
528         } else  {
529             return true;
530         }
531     });
533     /**
534      * Ajax Event handler for 'SQL Query Submit'
535      *
536      * @see         Functions.ajaxShowMessage()
537      * @memberOf    jQuery
538      * @name        sqlqueryform_submit
539      */
540     $(document).on('submit', '#sqlqueryform.ajax', function (event) {
541         event.preventDefault();
543         var $form = $(this);
544         if (codeMirrorEditor) {
545             $form[0].elements.sql_query.value = codeMirrorEditor.getValue();
546         }
547         if (! Functions.checkSqlQuery($form[0])) {
548             return false;
549         }
551         // remove any div containing a previous error message
552         $('div.error').remove();
554         var $msgbox = Functions.ajaxShowMessage();
555         var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
557         Functions.prepareForAjaxRequest($form);
559         var argsep = CommonParams.get('arg_separator');
560         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
561             if (typeof data !== 'undefined' && data.success === true) {
562                 // success happens if the query returns rows or not
564                 // show a message that stays on screen
565                 if (typeof data.action_bookmark !== 'undefined') {
566                     // view only
567                     if ('1' === data.action_bookmark) {
568                         $('#sqlquery').text(data.sql_query);
569                         // send to codemirror if possible
570                         Functions.setQuery(data.sql_query);
571                     }
572                     // delete
573                     if ('2' === data.action_bookmark) {
574                         $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
575                         // if there are no bookmarked queries now (only the empty option),
576                         // remove the bookmark section
577                         if ($('#id_bookmark option').length === 1) {
578                             $('#fieldsetBookmarkOptions').hide();
579                             $('#fieldsetBookmarkOptionsFooter').hide();
580                         }
581                     }
582                 }
583                 $sqlqueryresultsouter
584                     .show()
585                     .html(data.message);
586                 Functions.highlightSql($sqlqueryresultsouter);
588                 if (data.menu) {
589                     if (history && history.pushState) {
590                         history.replaceState({
591                             menu : data.menu
592                         },
593                         null
594                         );
595                         AJAX.handleMenu.replace(data.menu);
596                     } else {
597                         MicroHistory.menus.replace(data.menu);
598                         MicroHistory.menus.add(data.menuHash, data.menu);
599                     }
600                 } else if (data.menuHash) {
601                     if (! (history && history.pushState)) {
602                         MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
603                     }
604                 }
606                 if (data.params) {
607                     CommonParams.setAll(data.params);
608                 }
610                 if (typeof data.ajax_reload !== 'undefined') {
611                     if (data.ajax_reload.reload) {
612                         if (data.ajax_reload.table_name) {
613                             CommonParams.set('table', data.ajax_reload.table_name);
614                             CommonActions.refreshMain();
615                         } else {
616                             Navigation.reload();
617                         }
618                     }
619                 } else if (typeof data.reload !== 'undefined') {
620                     // this happens if a USE or DROP command was typed
621                     CommonActions.setDb(data.db);
622                     var url;
623                     if (data.db) {
624                         if (data.table) {
625                             url = 'table_sql.php';
626                         } else {
627                             url = 'db_sql.php';
628                         }
629                     } else {
630                         url = 'server_sql.php';
631                     }
632                     CommonActions.refreshMain(url, function () {
633                         $('#sqlqueryresultsouter')
634                             .show()
635                             .html(data.message);
636                         Functions.highlightSql($('#sqlqueryresultsouter'));
637                     });
638                 }
640                 $('.sqlqueryresults').trigger('makegrid');
641                 $('#togglequerybox').show();
642                 Functions.initSlider();
644                 if (typeof data.action_bookmark === 'undefined') {
645                     if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
646                         if ($('#togglequerybox').siblings(':visible').length > 0) {
647                             $('#togglequerybox').trigger('click');
648                         }
649                     }
650                 }
651             } else if (typeof data !== 'undefined' && data.success === false) {
652                 // show an error message that stays on screen
653                 $sqlqueryresultsouter
654                     .show()
655                     .html(data.error);
656                 $('html, body').animate({ scrollTop: $(document).height() }, 200);
657             }
658             Functions.ajaxRemoveMessage($msgbox);
659         }); // end $.post()
660     }); // end SQL Query submit
662     /**
663      * Ajax Event handler for the display options
664      * @memberOf    jQuery
665      * @name        displayOptionsForm_submit
666      */
667     $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
668         event.preventDefault();
670         var $form = $(this);
672         var $msgbox = Functions.ajaxShowMessage();
673         var argsep = CommonParams.get('arg_separator');
674         $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
675             Functions.ajaxRemoveMessage($msgbox);
676             var $sqlqueryresults = $form.parents('.sqlqueryresults');
677             $sqlqueryresults
678                 .html(data.message)
679                 .trigger('makegrid');
680             Functions.initSlider();
681             Functions.highlightSql($sqlqueryresults);
682         }); // end $.post()
683     }); // end displayOptionsForm handler
685     // Filter row handling. --STARTS--
686     $(document).on('keyup', '.filter_rows', function () {
687         var uniqueId = $(this).data('for');
688         var $targetTable = $('.table_results[data-uniqueId=\'' + uniqueId + '\']');
689         var $headerCells = $targetTable.find('th[data-column]');
690         var targetColumns = [];
691         // To handle colspan=4, in case of edit,copy etc options.
692         var dummyTh = ($('.edit_row_anchor').length !== 0 ?
693             '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
694             : '');
695         // Selecting columns that will be considered for filtering and searching.
696         $headerCells.each(function () {
697             targetColumns.push($.trim($(this).text()));
698         });
700         var phrase = $(this).val();
701         // Set same value to both Filter rows fields.
702         $('.filter_rows[data-for=\'' + uniqueId + '\']').not(this).val(phrase);
703         // Handle colspan.
704         $targetTable.find('thead > tr').prepend(dummyTh);
705         $.uiTableFilter($targetTable, phrase, targetColumns);
706         $targetTable.find('th.dummy_th').remove();
707     });
708     // Filter row handling. --ENDS--
710     // Prompt to confirm on Show All
711     $('body').on('click', '.navigation .showAllRows', function (e) {
712         e.preventDefault();
713         var $form = $(this).parents('form');
715         if (! $(this).is(':checked')) { // already showing all rows
716             Sql.submitShowAllForm();
717         } else {
718             $form.confirm(Messages.strShowAllRowsWarning, $form.attr('action'), function () {
719                 Sql.submitShowAllForm();
720             });
721         }
723         Sql.submitShowAllForm = function () {
724             var argsep = CommonParams.get('arg_separator');
725             var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
726             Functions.ajaxShowMessage();
727             AJAX.source = $form;
728             $.post($form.attr('action'), submitData, AJAX.responseHandler);
729         };
730     });
732     $('body').on('keyup', '#sqlqueryform', function () {
733         Functions.handleSimulateQueryButton();
734     });
736     /**
737      * Ajax event handler for 'Simulate DML'.
738      */
739     $('body').on('click', '#simulate_dml', function () {
740         var $form = $('#sqlqueryform');
741         var query = '';
742         var delimiter = $('#id_sql_delimiter').val();
743         var dbName = $form.find('input[name="db"]').val();
745         if (codeMirrorEditor) {
746             query = codeMirrorEditor.getValue();
747         } else {
748             query = $('#sqlquery').val();
749         }
751         if (query.length === 0) {
752             alert(Messages.strFormEmpty);
753             $('#sqlquery').trigger('focus');
754             return false;
755         }
757         var $msgbox = Functions.ajaxShowMessage();
758         $.ajax({
759             type: 'POST',
760             url: $form.attr('action'),
761             data: {
762                 'server': CommonParams.get('server'),
763                 'db': dbName,
764                 'ajax_request': '1',
765                 'simulate_dml': '1',
766                 'sql_query': query,
767                 'sql_delimiter': delimiter
768             },
769             success: function (response) {
770                 Functions.ajaxRemoveMessage($msgbox);
771                 if (response.success) {
772                     var dialogContent = '<div class="preview_sql">';
773                     if (response.sql_data) {
774                         var len = response.sql_data.length;
775                         for (var i = 0; i < len; i++) {
776                             dialogContent += '<strong>' + Messages.strSQLQuery +
777                                 '</strong>' + response.sql_data[i].sql_query +
778                                 Messages.strMatchedRows +
779                                 ' <a href="' + response.sql_data[i].matched_rows_url +
780                                 '">' + response.sql_data[i].matched_rows + '</a><br>';
781                             if (i < len - 1) {
782                                 dialogContent += '<hr>';
783                             }
784                         }
785                     } else {
786                         dialogContent += response.message;
787                     }
788                     dialogContent += '</div>';
789                     var $dialogContent = $(dialogContent);
790                     var buttonOptions = {};
791                     buttonOptions[Messages.strClose] = function () {
792                         $(this).dialog('close');
793                     };
794                     $('<div></div>').append($dialogContent).dialog({
795                         minWidth: 540,
796                         maxHeight: 400,
797                         modal: true,
798                         buttons: buttonOptions,
799                         title: Messages.strSimulateDML,
800                         open: function () {
801                             Functions.highlightSql($(this));
802                         },
803                         close: function () {
804                             $(this).remove();
805                         }
806                     });
807                 } else {
808                     Functions.ajaxShowMessage(response.error);
809                 }
810             },
811             error: function () {
812                 Functions.ajaxShowMessage(Messages.strErrorProcessingRequest);
813             }
814         });
815     });
817     /**
818      * Handles multi submits of results browsing page such as edit, delete and export
819      */
820     $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
821         e.preventDefault();
822         var $button = $(this);
823         var $form = $button.closest('form');
824         var argsep = CommonParams.get('arg_separator');
825         var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
826         Functions.ajaxShowMessage();
827         AJAX.source = $form;
828         $.post($form.attr('action'), submitData, AJAX.responseHandler);
829     });
830 }); // end $()
833  * Starting from some th, change the class of all td under it.
834  * If isAddClass is specified, it will be used to determine whether to add or remove the class.
835  */
836 Sql.changeClassForColumn = function ($thisTh, newClass, isAddClass) {
837     // index 0 is the th containing the big T
838     var thIndex = $thisTh.index();
839     var hasBigT = $thisTh.closest('tr').children(':first').hasClass('column_action');
840     // .eq() is zero-based
841     if (hasBigT) {
842         thIndex--;
843     }
844     var $table = $thisTh.parents('.table_results');
845     if (! $table.length) {
846         $table = $thisTh.parents('table').siblings('.table_results');
847     }
848     var $tds = $table.find('tbody tr').find('td.data:eq(' + thIndex + ')');
849     if (isAddClass === undefined) {
850         $tds.toggleClass(newClass);
851     } else {
852         $tds.toggleClass(newClass, isAddClass);
853     }
857  * Handles browse foreign values modal dialog
859  * @param object $this_a reference to the browse foreign value link
860  */
861 Sql.browseForeignDialog = function ($thisA) {
862     var formId = '#browse_foreign_form';
863     var showAllId = '#foreign_showAll';
864     var tableId = '#browse_foreign_table';
865     var filterId = '#input_foreign_filter';
866     var $dialog = null;
867     var argSep = CommonParams.get('arg_separator');
868     var params = $thisA.getPostData();
869     params += argSep + 'ajax_request=true';
870     $.post($thisA.attr('href'), params, function (data) {
871         // Creates browse foreign value dialog
872         $dialog = $('<div>').append(data.message).dialog({
873             title: Messages.strBrowseForeignValues,
874             width: Math.min($(window).width() - 100, 700),
875             maxHeight: $(window).height() - 100,
876             dialogClass: 'browse_foreign_modal',
877             close: function () {
878                 // remove event handlers attached to elements related to dialog
879                 $(tableId).off('click', 'td a.foreign_value');
880                 $(formId).off('click', showAllId);
881                 $(formId).off('submit');
882                 // remove dialog itself
883                 $(this).remove();
884             },
885             modal: true
886         });
887     }).done(function () {
888         var showAll = false;
889         $(tableId).on('click', 'td a.foreign_value', function (e) {
890             e.preventDefault();
891             var $input = $thisA.prev('input[type=text]');
892             // Check if input exists or get CEdit edit_box
893             if ($input.length === 0) {
894                 $input = $thisA.closest('.edit_area').prev('.edit_box');
895             }
896             // Set selected value as input value
897             $input.val($(this).data('key'));
898             $dialog.dialog('close');
899         });
900         $(formId).on('click', showAllId, function () {
901             showAll = true;
902         });
903         $(formId).on('submit', function (e) {
904             e.preventDefault();
905             // if filter value is not equal to old value
906             // then reset page number to 1
907             if ($(filterId).val() !== $(filterId).data('old')) {
908                 $(formId).find('select[name=pos]').val('0');
909             }
910             var postParams = $(this).serializeArray();
911             // if showAll button was clicked to submit form then
912             // add showAll button parameter to form
913             if (showAll) {
914                 postParams.push({
915                     name: $(showAllId).attr('name'),
916                     value: $(showAllId).val()
917                 });
918             }
919             // updates values in dialog
920             $.post($(this).attr('action') + '?ajax_request=1', postParams, function (data) {
921                 var $obj = $('<div>').html(data.message);
922                 $(formId).html($obj.find(formId).html());
923                 $(tableId).html($obj.find(tableId).html());
924             });
925             showAll = false;
926         });
927     });
930 Sql.checkSavedQuery = function () {
931     if (isStorageSupported('localStorage') && window.localStorage.autoSavedSql !== undefined) {
932         Functions.ajaxShowMessage(Messages.strPreviousSaveQuery);
933     }
936 AJAX.registerOnload('sql.js', function () {
937     $('body').on('click', 'a.browse_foreign', function (e) {
938         e.preventDefault();
939         Sql.browseForeignDialog($(this));
940     });
942     /**
943      * vertical column highlighting in horizontal mode when hovering over the column header
944      */
945     $(document).on('mouseenter', 'th.column_heading.pointer', function () {
946         Sql.changeClassForColumn($(this), 'hover', true);
947     });
948     $(document).on('mouseleave', 'th.column_heading.pointer', function () {
949         Sql.changeClassForColumn($(this), 'hover', false);
950     });
952     /**
953      * vertical column marking in horizontal mode when clicking the column header
954      */
955     $(document).on('click', 'th.column_heading.marker', function () {
956         Sql.changeClassForColumn($(this), 'marked');
957     });
959     /**
960      * create resizable table
961      */
962     $('.sqlqueryresults').trigger('makegrid');
964     /**
965      * Check if there is any saved query
966      */
967     if (codeMirrorEditor || document.sqlform) {
968         Sql.checkSavedQuery();
969     }
973  * Profiling Chart
974  */
975 Sql.makeProfilingChart = function () {
976     if ($('#profilingchart').length === 0 ||
977         $('#profilingchart').html().length !== 0 ||
978         !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
979     ) {
980         return;
981     }
983     var data = [];
984     $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
985         data.push([key, parseFloat(value)]);
986     });
988     // Remove chart and data divs contents
989     $('#profilingchart').html('').show();
990     $('#profilingChartData').html('');
992     Functions.createProfilingChart('profilingchart', data);
996  * initialize profiling data tables
997  */
998 Sql.initProfilingTables = function () {
999     if (!$.tablesorter) {
1000         return;
1001     }
1002     // Added to allow two direction sorting
1003     $('#profiletable')
1004         .find('thead th')
1005         .off('click mousedown');
1007     $('#profiletable').tablesorter({
1008         widgets: ['zebra'],
1009         sortList: [[0, 0]],
1010         textExtraction: function (node) {
1011             if (node.children.length > 0) {
1012                 return node.children[0].innerHTML;
1013             } else {
1014                 return node.innerHTML;
1015             }
1016         }
1017     });
1018     // Added to allow two direction sorting
1019     $('#profilesummarytable')
1020         .find('thead th')
1021         .off('click mousedown');
1023     $('#profilesummarytable').tablesorter({
1024         widgets: ['zebra'],
1025         sortList: [[1, 1]],
1026         textExtraction: function (node) {
1027             if (node.children.length > 0) {
1028                 return node.children[0].innerHTML;
1029             } else {
1030                 return node.innerHTML;
1031             }
1032         }
1033     });
1036 AJAX.registerOnload('sql.js', function () {
1037     Sql.makeProfilingChart();
1038     Sql.initProfilingTables();
1042  * Polyfill to make table headers sticky.
1043  */
1044 var elements = $('.sticky');
1045 Stickyfill.add(elements);