2 * @fileoverview functions used wherever an sql query form is used
5 * @requires js/functions.js
9 /* global isStorageSupported */ // js/config.js
10 /* global codeMirrorEditor */ // js/functions.js
11 /* global MicroHistory */ // js/microhistory.js
12 /* global makeGrid */ // js/makegrid.js
19 * decode a string URL_encoded
22 * @return string the URL-decoded string
24 Sql.urlDecode = function (str) {
25 if (typeof str !== 'undefined') {
26 return decodeURIComponent(str.replace(/\+/g, '%20'));
31 * endecode a string URL_decoded
34 * @return string the URL-encoded string
36 Sql.urlEncode = function (str) {
37 if (typeof str !== 'undefined') {
38 return encodeURIComponent(str).replace(/%20/g, '+');
43 * Saves SQL query in local storage or cookie
45 * @param string SQL query
48 Sql.autoSave = function (query) {
49 if (isStorageSupported('localStorage')) {
50 window.localStorage.autoSavedSql = query;
52 Cookies.set('autoSavedSql', query);
57 * Saves SQL query in local storage or cookie
59 * @param string database name
60 * @param string table name
61 * @param string SQL query
64 Sql.showThisQuery = function (db, table, query) {
65 var showThisQueryObject = {
70 if (isStorageSupported('localStorage')) {
71 window.localStorage.showThisQuery = 1;
72 window.localStorage.showThisQueryObject = JSON.stringify(showThisQueryObject);
74 Cookies.set('showThisQuery', 1);
75 Cookies.set('showThisQueryObject', JSON.stringify(showThisQueryObject));
80 * Set query to codemirror if show this query is
81 * checked and query for the db and table pair exists
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;
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;
103 $('input[name="show_query"]').prop('checked', false);
109 * Saves SQL query with sort in local storage or cookie
111 * @param string SQL query
114 Sql.autoSaveWithSort = function (query) {
116 if (isStorageSupported('localStorage')) {
117 window.localStorage.autoSavedSqlSort = query;
119 Cookies.set('autoSavedSqlSort', query);
125 * Clear saved SQL query with sort in local storage or cookie
129 Sql.clearAutoSavedSort = function () {
130 if (isStorageSupported('localStorage')) {
131 window.localStorage.removeItem('auto_saved_sql_sort');
133 Cookies.set('auto_saved_sql_sort', '');
138 * Get the field name for the current field. Required to construct the query
141 * @param $tableResults enclosing results table
142 * @param $thisField jQuery object that points to the current field's tr
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
159 .eq(thisFieldIndex - leftActionSkip)
161 .clone() // clone the element
162 .children() // select all the children
163 .remove() // remove all of them
164 .end() // go back to the selected element
165 .text(); // grab the text
166 // happens when just one row (headings contain no a)
167 if (fieldName === '') {
168 var $heading = $tableResults.find('thead').find('th').eq(thisFieldIndex - leftActionSkip).children('span');
169 // may contain column comment enclosed in a span - detach it temporarily to read the column name
170 var $tempColComment = $heading.children().detach();
171 fieldName = $heading.text();
172 // re-attach the column comment
173 $heading.append($tempColComment);
176 fieldName = $.trim(fieldName);
182 * Unbind all event handlers before tearing down a page
184 AJAX.registerTeardown('sql.js', function () {
185 $(document).off('click', 'a.delete_row.ajax');
186 $(document).off('submit', '.bookmarkQueryForm');
187 $('input#bkm_label').off('input');
188 $(document).off('makegrid', '.sqlqueryresults');
189 $(document).off('stickycolumns', '.sqlqueryresults');
190 $('#togglequerybox').off('click');
191 $(document).off('click', '#button_submit_query');
192 $(document).off('change', '#id_bookmark');
193 $('input[name=\'bookmark_variable\']').off('keypress');
194 $(document).off('submit', '#sqlqueryform.ajax');
195 $(document).off('click', 'input[name=navig].ajax');
196 $(document).off('submit', 'form[name=\'displayOptionsForm\'].ajax');
197 $(document).off('mouseenter', 'th.column_heading.pointer');
198 $(document).off('mouseleave', 'th.column_heading.pointer');
199 $(document).off('click', 'th.column_heading.marker');
200 $(document).off('scroll', window);
201 $(document).off('keyup', '.filter_rows');
202 $(document).off('click', '#printView');
203 if (codeMirrorEditor) {
204 codeMirrorEditor.off('change');
206 $('#sqlquery').off('input propertychange');
208 $('body').off('click', '.navigation .showAllRows');
209 $('body').off('click', 'a.browse_foreign');
210 $('body').off('click', '#simulate_dml');
211 $('body').off('keyup', '#sqlqueryform');
212 $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
216 * @description <p>Ajax scripts for sql and browse pages</p>
218 * Actions ajaxified here:
220 * <li>Retrieve results of an SQL query</li>
221 * <li>Paginate the results table</li>
222 * <li>Sort the results table</li>
223 * <li>Change table according to display options</li>
224 * <li>Grid editing of data</li>
225 * <li>Saving a bookmark</li>
228 * @name document.ready
231 AJAX.registerOnload('sql.js', function () {
232 if (codeMirrorEditor || document.sqlform) {
233 Sql.setShowThisQuery();
236 if (codeMirrorEditor) {
237 codeMirrorEditor.on('change', function () {
238 Sql.autoSave(codeMirrorEditor.getValue());
241 $('#sqlquery').on('input propertychange', function () {
242 Sql.autoSave($('#sqlquery').val());
244 var useLocalStorageValue = isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined';
245 // Save sql query with sort
246 if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
247 $('select[name="sql_query"]').on('change', function () {
248 Sql.autoSaveWithSort($(this).val());
250 $('.sortlink').on('click', function () {
251 Sql.clearAutoSavedSort();
254 Sql.clearAutoSavedSort();
256 // If sql query with sort for current table is stored, change sort by key select value
257 var sortStoredQuery = useLocalStorageValue ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
258 if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
259 $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
264 // Delete row from SQL results
265 $(document).on('click', 'a.delete_row.ajax', function (e) {
267 var question = Functions.sprintf(Messages.strDoYouReally, Functions.escapeHtml($(this).closest('td').find('div').text()));
269 $link.confirm(question, $link.attr('href'), function (url) {
270 Functions.ajaxShowMessage();
271 var argsep = CommonParams.get('arg_separator');
272 var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
273 var postData = $link.getPostData();
275 params += argsep + postData;
277 $.post(url, params, function (data) {
279 Functions.ajaxShowMessage(data.message);
280 $link.closest('tr').remove();
282 Functions.ajaxShowMessage(data.error, false);
288 // Ajaxification for 'Bookmark this SQL query'
289 $(document).on('submit', '.bookmarkQueryForm', function (e) {
291 Functions.ajaxShowMessage();
292 var argsep = CommonParams.get('arg_separator');
293 $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
295 Functions.ajaxShowMessage(data.message);
297 Functions.ajaxShowMessage(data.error, false);
302 /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
303 $('input#bkm_label').on('input', function () {
304 $('input#id_bkm_all_users, input#id_bkm_replace')
306 .toggle($(this).val().length > 0);
310 * Attach Event Handler for 'Copy to clipbpard
312 $(document).on('click', '#copyToClipBoard', function (event) {
313 event.preventDefault();
315 var textArea = document.createElement('textarea');
318 // *** This styling is an extra step which is likely not required. ***
320 // Why is it here? To ensure:
321 // 1. the element is able to have focus and selection.
322 // 2. if element was to flash render it has minimal visual impact.
323 // 3. less flakyness with selection and copying which **might** occur if
324 // the textarea element is not visible.
326 // The likelihood is the element won't even render, not even a flash,
327 // so some of these are just precautions. However in IE the element
328 // is visible whilst the popup box asking the user for permission for
329 // the web page to copy to the clipboard.
332 // Place in top-left corner of screen regardless of scroll position.
333 textArea.style.position = 'fixed';
334 textArea.style.top = 0;
335 textArea.style.left = 0;
337 // Ensure it has a small width and height. Setting to 1px / 1em
338 // doesn't work as this gives a negative w/h on some browsers.
339 textArea.style.width = '2em';
340 textArea.style.height = '2em';
342 // We don't need padding, reducing the size if it does flash render.
343 textArea.style.padding = 0;
345 // Clean up any borders.
346 textArea.style.border = 'none';
347 textArea.style.outline = 'none';
348 textArea.style.boxShadow = 'none';
350 // Avoid flash of white box if rendered for any reason.
351 textArea.style.background = 'transparent';
355 $('#server-breadcrumb a').each(function () {
356 textArea.value += $(this).text().split(':')[1].trim() + '/';
358 textArea.value += '\t\t' + window.location.href;
359 textArea.value += '\n';
360 $('.alert-success').each(function () {
361 textArea.value += $(this).text() + '\n\n';
364 $('.sql pre').each(function () {
365 textArea.value += $(this).text() + '\n\n';
368 $('.table_results .column_heading a').each(function () {
369 // Don't copy ordering number text within <small> tag
370 textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
373 textArea.value += '\n';
374 $('.table_results tbody tr').each(function () {
375 $(this).find('.data span').each(function () {
376 textArea.value += $(this).text() + '\t';
378 textArea.value += '\n';
381 document.body.appendChild(textArea);
386 document.execCommand('copy');
388 alert('Sorry! Unable to copy');
391 document.body.removeChild(textArea);
392 }); // end of Copy to Clipboard action
395 * Attach Event Handler for 'Print' link
397 $(document).on('click', '#printView', function (event) {
398 event.preventDefault();
400 // Take to preview mode
401 Functions.printPreview();
402 }); // end of 'Print' action
405 * Attach the {@link makegrid} function to a custom event, which will be
406 * triggered manually everytime the table of results is reloaded
409 $(document).on('makegrid', '.sqlqueryresults', function () {
410 $('.table_results').each(function () {
416 * Attach a custom event for sticky column headings which will be
417 * triggered manually everytime the table of results is reloaded
420 $(document).on('stickycolumns', '.sqlqueryresults', function () {
421 $('.sticky_columns').remove();
422 $('.table_results').each(function () {
423 var $tableResults = $(this);
424 // add sticky columns div
425 var $stickColumns = Sql.initStickyColumns($tableResults);
426 Sql.rearrangeStickyColumns($stickColumns, $tableResults);
427 // adjust sticky columns on scroll
428 $(document).on('scroll', window, function () {
429 Sql.handleStickyColumns($stickColumns, $tableResults);
435 * Append the "Show/Hide query box" message to the query input form
438 * @name appendToggleSpan
440 // do not add this link more than once
441 if (! $('#sqlqueryform').find('button').is('#togglequerybox')) {
442 $('<button class="btn btn-secondary" id="togglequerybox"></button>')
443 .html(Messages.strHideQueryBox)
444 .appendTo('#sqlqueryform')
445 // initially hidden because at this point, nothing else
446 // appears under the link
449 // Attach the toggling of the query box visibility to a click
450 $('#togglequerybox').on('click', function () {
452 $link.siblings().slideToggle('fast');
453 if ($link.text() === Messages.strHideQueryBox) {
454 $link.text(Messages.strShowQueryBox);
455 // cheap trick to add a spacer between the menu tabs
456 // and "Show query box"; feel free to improve!
457 $('#togglequerybox_spacer').remove();
458 $link.before('<br id="togglequerybox_spacer">');
460 $link.text(Messages.strHideQueryBox);
462 // avoid default click action
469 * Event handler for sqlqueryform.ajax button_submit_query
473 $(document).on('click', '#button_submit_query', function () {
474 $('.alert-success,.alert-danger').hide();
475 // hide already existing error or success message
476 var $form = $(this).closest('form');
477 // the Go button related to query submission was clicked,
478 // instead of the one related to Bookmarks, so empty the
479 // id_bookmark selector to avoid misinterpretation in
480 // /import about what needs to be done
481 $form.find('select[name=id_bookmark]').val('');
482 // let normal event propagation happen
483 if (isStorageSupported('localStorage')) {
484 window.localStorage.removeItem('autoSavedSql');
486 Cookies.set('autoSavedSql', '');
488 var isShowQuery = $('input[name="show_query"]').is(':checked');
490 window.localStorage.showThisQuery = '1';
491 var db = $('input[name="db"]').val();
492 var table = $('input[name="table"]').val();
494 if (codeMirrorEditor) {
495 query = codeMirrorEditor.getValue();
497 query = $('#sqlquery').val();
499 Sql.showThisQuery(db, table, query);
501 window.localStorage.showThisQuery = '0';
506 * Event handler to show appropiate number of variable boxes
507 * based on the bookmarked query
509 $(document).on('change', '#id_bookmark', function () {
510 var varCount = $(this).find('option:selected').data('varcount');
511 if (typeof varCount === 'undefined') {
515 var $varDiv = $('#bookmarkVariables');
517 for (var i = 1; i <= varCount; i++) {
518 $varDiv.append($('<div class="form-group">'));
519 $varDiv.append($('<label for="bookmarkVariable' + i + '">' + Functions.sprintf(Messages.strBookmarkVariable, i) + '</label>'));
520 $varDiv.append($('<input class="form-control" type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmarkVariable' + i + '">'));
521 $varDiv.append($('</div>'));
524 if (varCount === 0) {
525 $varDiv.parent().hide();
527 $varDiv.parent().show();
532 * Event handler for hitting enter on sqlqueryform bookmark_variable
533 * (the Variable textfield in Bookmarked SQL query section)
537 $('input[name=bookmark_variable]').on('keypress', function (event) {
538 // force the 'Enter Key' to implicitly click the #button_submit_bookmark
539 var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
540 if (keycode === 13) { // keycode for enter key
541 // When you press enter in the sqlqueryform, which
542 // has 2 submit buttons, the default is to run the
543 // #button_submit_query, because of the tabindex
545 // This submits #button_submit_bookmark instead,
546 // because when you are in the Bookmarked SQL query
547 // section and hit enter, you expect it to do the
548 // same action as the Go button in that section.
549 $('#button_submit_bookmark').trigger('click');
557 * Ajax Event handler for 'SQL Query Submit'
559 * @see Functions.ajaxShowMessage()
561 * @name sqlqueryform_submit
563 $(document).on('submit', '#sqlqueryform.ajax', function (event) {
564 event.preventDefault();
567 if (codeMirrorEditor) {
568 $form[0].elements.sql_query.value = codeMirrorEditor.getValue();
570 if (! Functions.checkSqlQuery($form[0])) {
574 // remove any div containing a previous error message
575 $('.alert-danger').remove();
577 var $msgbox = Functions.ajaxShowMessage();
578 var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
580 Functions.prepareForAjaxRequest($form);
582 var argsep = CommonParams.get('arg_separator');
583 $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
584 if (typeof data !== 'undefined' && data.success === true) {
585 // success happens if the query returns rows or not
587 // show a message that stays on screen
588 if (typeof data.action_bookmark !== 'undefined') {
590 if ('1' === data.action_bookmark) {
591 $('#sqlquery').text(data.sql_query);
592 // send to codemirror if possible
593 Functions.setQuery(data.sql_query);
596 if ('2' === data.action_bookmark) {
597 $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
598 // if there are no bookmarked queries now (only the empty option),
599 // remove the bookmark section
600 if ($('#id_bookmark option').length === 1) {
601 $('#fieldsetBookmarkOptions').hide();
602 $('#fieldsetBookmarkOptionsFooter').hide();
606 $sqlqueryresultsouter
609 Functions.highlightSql($sqlqueryresultsouter);
612 if (history && history.pushState) {
613 history.replaceState({
618 AJAX.handleMenu.replace(data.menu);
620 MicroHistory.menus.replace(data.menu);
621 MicroHistory.menus.add(data.menuHash, data.menu);
623 } else if (data.menuHash) {
624 if (! (history && history.pushState)) {
625 MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
630 CommonParams.setAll(data.params);
633 if (typeof data.ajax_reload !== 'undefined') {
634 if (data.ajax_reload.reload) {
635 if (data.ajax_reload.table_name) {
636 CommonParams.set('table', data.ajax_reload.table_name);
637 CommonActions.refreshMain();
642 } else if (typeof data.reload !== 'undefined') {
643 // this happens if a USE or DROP command was typed
644 CommonActions.setDb(data.db);
648 url = 'index.php?route=/table/sql';
650 url = 'index.php?route=/database/sql';
653 url = 'index.php?route=/server/sql';
655 CommonActions.refreshMain(url, function () {
656 $('#sqlqueryresultsouter')
659 Functions.highlightSql($('#sqlqueryresultsouter'));
663 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
664 $('#togglequerybox').show();
665 Functions.initSlider();
667 if (typeof data.action_bookmark === 'undefined') {
668 if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
669 if ($('#togglequerybox').siblings(':visible').length > 0) {
670 $('#togglequerybox').trigger('click');
674 } else if (typeof data !== 'undefined' && data.success === false) {
675 // show an error message that stays on screen
676 $sqlqueryresultsouter
679 $('html, body').animate({ scrollTop: $(document).height() }, 200);
681 Functions.ajaxRemoveMessage($msgbox);
683 }); // end SQL Query submit
686 * Ajax Event handler for the display options
688 * @name displayOptionsForm_submit
690 $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
691 event.preventDefault();
695 var $msgbox = Functions.ajaxShowMessage();
696 var argsep = CommonParams.get('arg_separator');
697 $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
698 Functions.ajaxRemoveMessage($msgbox);
699 var $sqlqueryresults = $form.parents('.sqlqueryresults');
703 .trigger('stickycolumns');
704 Functions.initSlider();
705 Functions.highlightSql($sqlqueryresults);
707 }); // end displayOptionsForm handler
709 // Filter row handling. --STARTS--
710 $(document).on('keyup', '.filter_rows', function () {
711 var uniqueId = $(this).data('for');
712 var $targetTable = $('.table_results[data-uniqueId=\'' + uniqueId + '\']');
713 var $headerCells = $targetTable.find('th[data-column]');
714 var targetColumns = [];
715 // To handle colspan=4, in case of edit,copy etc options.
716 var dummyTh = ($('.edit_row_anchor').length !== 0 ?
717 '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
719 // Selecting columns that will be considered for filtering and searching.
720 $headerCells.each(function () {
721 targetColumns.push($.trim($(this).text()));
724 var phrase = $(this).val();
725 // Set same value to both Filter rows fields.
726 $('.filter_rows[data-for=\'' + uniqueId + '\']').not(this).val(phrase);
728 $targetTable.find('thead > tr').prepend(dummyTh);
729 $.uiTableFilter($targetTable, phrase, targetColumns);
730 $targetTable.find('th.dummy_th').remove();
732 // Filter row handling. --ENDS--
734 // Prompt to confirm on Show All
735 $('body').on('click', '.navigation .showAllRows', function (e) {
737 var $form = $(this).parents('form');
739 if (! $(this).is(':checked')) { // already showing all rows
740 Sql.submitShowAllForm();
742 $form.confirm(Messages.strShowAllRowsWarning, $form.attr('action'), function () {
743 Sql.submitShowAllForm();
747 Sql.submitShowAllForm = function () {
748 var argsep = CommonParams.get('arg_separator');
749 var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
750 Functions.ajaxShowMessage();
752 $.post($form.attr('action'), submitData, AJAX.responseHandler);
756 $('body').on('keyup', '#sqlqueryform', function () {
757 Functions.handleSimulateQueryButton();
761 * Ajax event handler for 'Simulate DML'.
763 $('body').on('click', '#simulate_dml', function () {
764 var $form = $('#sqlqueryform');
766 var delimiter = $('#id_sql_delimiter').val();
767 var dbName = $form.find('input[name="db"]').val();
769 if (codeMirrorEditor) {
770 query = codeMirrorEditor.getValue();
772 query = $('#sqlquery').val();
775 if (query.length === 0) {
776 alert(Messages.strFormEmpty);
777 $('#sqlquery').trigger('focus');
781 var $msgbox = Functions.ajaxShowMessage();
784 url: $form.attr('action'),
786 'server': CommonParams.get('server'),
791 'sql_delimiter': delimiter
793 success: function (response) {
794 Functions.ajaxRemoveMessage($msgbox);
795 if (response.success) {
796 var dialogContent = '<div class="preview_sql">';
797 if (response.sql_data) {
798 var len = response.sql_data.length;
799 for (var i = 0; i < len; i++) {
800 dialogContent += '<strong>' + Messages.strSQLQuery +
801 '</strong>' + response.sql_data[i].sql_query +
802 Messages.strMatchedRows +
803 ' <a href="' + response.sql_data[i].matched_rows_url +
804 '">' + response.sql_data[i].matched_rows + '</a><br>';
806 dialogContent += '<hr>';
810 dialogContent += response.message;
812 dialogContent += '</div>';
813 var $dialogContent = $(dialogContent);
814 var buttonOptions = {};
815 buttonOptions[Messages.strClose] = function () {
816 $(this).dialog('close');
818 $('<div></div>').append($dialogContent).dialog({
822 buttons: buttonOptions,
823 title: Messages.strSimulateDML,
825 Functions.highlightSql($(this));
832 Functions.ajaxShowMessage(response.error);
836 Functions.ajaxShowMessage(Messages.strErrorProcessingRequest);
842 * Handles multi submits of results browsing page such as edit, delete and export
844 $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
846 var $button = $(this);
847 var $form = $button.closest('form');
848 var argsep = CommonParams.get('arg_separator');
849 var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
850 Functions.ajaxShowMessage();
852 $.post($form.attr('action'), submitData, AJAX.responseHandler);
857 * Starting from some th, change the class of all td under it.
858 * If isAddClass is specified, it will be used to determine whether to add or remove the class.
860 Sql.changeClassForColumn = function ($thisTh, newClass, isAddClass) {
861 // index 0 is the th containing the big T
862 var thIndex = $thisTh.index();
863 var hasBigT = $thisTh.closest('tr').children().first().hasClass('column_action');
864 // .eq() is zero-based
868 var $table = $thisTh.parents('.table_results');
869 if (! $table.length) {
870 $table = $thisTh.parents('table').siblings('.table_results');
872 var $tds = $table.find('tbody tr').find('td.data').eq(thIndex);
873 if (isAddClass === undefined) {
874 $tds.toggleClass(newClass);
876 $tds.toggleClass(newClass, isAddClass);
881 * Handles browse foreign values modal dialog
883 * @param object $this_a reference to the browse foreign value link
885 Sql.browseForeignDialog = function ($thisA) {
886 var formId = '#browse_foreign_form';
887 var showAllId = '#foreign_showAll';
888 var tableId = '#browse_foreign_table';
889 var filterId = '#input_foreign_filter';
891 var argSep = CommonParams.get('arg_separator');
892 var params = $thisA.getPostData();
893 params += argSep + 'ajax_request=true';
894 $.post($thisA.attr('href'), params, function (data) {
895 // Creates browse foreign value dialog
896 $dialog = $('<div>').append(data.message).dialog({
897 title: Messages.strBrowseForeignValues,
898 width: Math.min($(window).width() - 100, 700),
899 maxHeight: $(window).height() - 100,
900 dialogClass: 'browse_foreign_modal',
902 // remove event handlers attached to elements related to dialog
903 $(tableId).off('click', 'td a.foreign_value');
904 $(formId).off('click', showAllId);
905 $(formId).off('submit');
906 // remove dialog itself
911 }).done(function () {
913 $(tableId).on('click', 'td a.foreign_value', function (e) {
915 var $input = $thisA.prev('input[type=text]');
916 // Check if input exists or get CEdit edit_box
917 if ($input.length === 0) {
918 $input = $thisA.closest('.edit_area').prev('.edit_box');
920 // Set selected value as input value
921 $input.val($(this).data('key'));
922 $dialog.dialog('close');
924 $(formId).on('click', showAllId, function () {
927 $(formId).on('submit', function (e) {
929 // if filter value is not equal to old value
930 // then reset page number to 1
931 if ($(filterId).val() !== $(filterId).data('old')) {
932 $(formId).find('select[name=pos]').val('0');
934 var postParams = $(this).serializeArray();
935 // if showAll button was clicked to submit form then
936 // add showAll button parameter to form
939 name: $(showAllId).attr('name'),
940 value: $(showAllId).val()
943 // updates values in dialog
944 $.post($(this).attr('action') + '&ajax_request=1', postParams, function (data) {
945 var $obj = $('<div>').html(data.message);
946 $(formId).html($obj.find(formId).html());
947 $(tableId).html($obj.find(tableId).html());
954 Sql.checkSavedQuery = function () {
955 if (isStorageSupported('localStorage') && window.localStorage.autoSavedSql !== undefined) {
956 Functions.ajaxShowMessage(Messages.strPreviousSaveQuery);
960 AJAX.registerOnload('sql.js', function () {
961 $('body').on('click', 'a.browse_foreign', function (e) {
963 Sql.browseForeignDialog($(this));
967 * vertical column highlighting in horizontal mode when hovering over the column header
969 $(document).on('mouseenter', 'th.column_heading.pointer', function () {
970 Sql.changeClassForColumn($(this), 'hover', true);
972 $(document).on('mouseleave', 'th.column_heading.pointer', function () {
973 Sql.changeClassForColumn($(this), 'hover', false);
977 * vertical column marking in horizontal mode when clicking the column header
979 $(document).on('click', 'th.column_heading.marker', function () {
980 Sql.changeClassForColumn($(this), 'marked');
984 * create resizable table
986 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
989 * Check if there is any saved query
991 if (codeMirrorEditor || document.sqlform) {
992 Sql.checkSavedQuery();
999 Sql.makeProfilingChart = function () {
1000 if ($('#profilingchart').length === 0 ||
1001 $('#profilingchart').html().length !== 0 ||
1002 !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
1008 $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
1009 data.push([key, parseFloat(value)]);
1012 // Remove chart and data divs contents
1013 $('#profilingchart').html('').show();
1014 $('#profilingChartData').html('');
1016 Functions.createProfilingChart('profilingchart', data);
1020 * initialize profiling data tables
1022 Sql.initProfilingTables = function () {
1023 if (!$.tablesorter) {
1026 // Added to allow two direction sorting
1029 .off('click mousedown');
1031 $('#profiletable').tablesorter({
1034 textExtraction: function (node) {
1035 if (node.children.length > 0) {
1036 return node.children[0].innerHTML;
1038 return node.innerHTML;
1042 // Added to allow two direction sorting
1043 $('#profilesummarytable')
1045 .off('click mousedown');
1047 $('#profilesummarytable').tablesorter({
1050 textExtraction: function (node) {
1051 if (node.children.length > 0) {
1052 return node.children[0].innerHTML;
1054 return node.innerHTML;
1061 * Set position, left, top, width of sticky_columns div
1063 Sql.setStickyColumnsPosition = function ($stickyColumns, $tableResults, position, top, left, marginLeft) {
1065 .css('position', position)
1067 .css('left', left ? left : 'auto')
1068 .css('margin-left', marginLeft ? marginLeft : '0px')
1069 .css('width', $tableResults.width());
1073 * Initialize sticky columns
1075 Sql.initStickyColumns = function ($tableResults) {
1076 return $('<table class="sticky_columns"></table>')
1077 .insertBefore($tableResults)
1078 .css('position', 'fixed')
1079 .css('z-index', '98')
1080 .css('width', $tableResults.width())
1081 .css('margin-left', $('#page_content').css('margin-left'))
1082 .css('top', $('#floating_menubar').height())
1083 .css('display', 'none');
1087 * Arrange/Rearrange columns in sticky header
1089 Sql.rearrangeStickyColumns = function ($stickyColumns, $tableResults) {
1090 var $originalHeader = $tableResults.find('thead');
1091 var $originalColumns = $originalHeader.find('tr').first().children();
1092 var $clonedHeader = $originalHeader.clone();
1093 var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
1094 var isSafari = navigator.userAgent.indexOf('Safari') > -1;
1095 // clone width per cell
1096 $clonedHeader.find('tr').first().children().each(function (i) {
1097 var width = $originalColumns.eq(i).width();
1098 if (! isFirefox && ! isSafari) {
1101 $(this).width(width);
1103 $(this).css('min-width', width).css('max-width', width);
1106 $stickyColumns.empty().append($clonedHeader);
1110 * Adjust sticky columns on horizontal/vertical scroll for all tables
1112 Sql.handleAllStickyColumns = function () {
1113 $('.sticky_columns').each(function () {
1114 Sql.handleStickyColumns($(this), $(this).next('.table_results'));
1119 * Adjust sticky columns on horizontal/vertical scroll
1121 Sql.handleStickyColumns = function ($stickyColumns, $tableResults) {
1122 var currentScrollX = $(window).scrollLeft();
1123 var windowOffset = $(window).scrollTop();
1124 var tableStartOffset = $tableResults.offset().top;
1125 var tableEndOffset = tableStartOffset + $tableResults.height();
1126 if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
1127 // for horizontal scrolling
1128 if (prevScrollX !== currentScrollX) {
1129 prevScrollX = currentScrollX;
1130 Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'absolute', $('#floating_menubar').height() + windowOffset - tableStartOffset);
1131 // for vertical scrolling
1133 Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'fixed', $('#floating_menubar').height(), $('#pma_navigation').width() - currentScrollX, $('#page_content').css('margin-left'));
1135 $stickyColumns.show();
1137 $stickyColumns.hide();
1141 AJAX.registerOnload('sql.js', function () {
1142 Sql.makeProfilingChart();
1143 Sql.initProfilingTables();