1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * @fileoverview functions used wherever an sql query form is used
6 * @requires js/functions.js
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
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
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);
174 fieldName = $.trim(fieldName);
180 * Unbind all event handlers before tearing down a page
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');
204 $('#sqlquery').off('input propertychange');
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:
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>
226 * @name document.ready
229 AJAX.registerOnload('sql.js', function () {
230 if (codeMirrorEditor || document.sqlform) {
231 Sql.setShowThisQuery();
234 if (codeMirrorEditor) {
235 codeMirrorEditor.on('change', function () {
236 Sql.autoSave(codeMirrorEditor.getValue());
239 $('#sqlquery').on('input propertychange', function () {
240 Sql.autoSave($('#sqlquery').val());
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());
248 $('.sortlink').on('click', function () {
249 Sql.clearAutoSavedSort();
252 Sql.clearAutoSavedSort();
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');
262 // Delete row from SQL results
263 $(document).on('click', 'a.delete_row.ajax', function (e) {
265 var question = Functions.sprintf(Messages.strDoYouReally, Functions.escapeHtml($(this).closest('td').find('div').text()));
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();
273 params += argsep + postData;
275 $.post(url, params, function (data) {
277 Functions.ajaxShowMessage(data.message);
278 $link.closest('tr').remove();
280 Functions.ajaxShowMessage(data.error, false);
286 // Ajaxification for 'Bookmark this SQL query'
287 $(document).on('submit', '.bookmarkQueryForm', function (e) {
289 Functions.ajaxShowMessage();
290 var argsep = CommonParams.get('arg_separator');
291 $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
293 Functions.ajaxShowMessage(data.message);
295 Functions.ajaxShowMessage(data.error, false);
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')
304 .toggle($(this).val().length > 0);
308 * Attach Event Handler for 'Copy to clipbpard
310 $(document).on('click', '#copyToClipBoard', function (event) {
311 event.preventDefault();
313 var textArea = document.createElement('textarea');
316 // *** This styling is an extra step which is likely not required. ***
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.
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.
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';
353 $('#serverinfo a').each(function () {
354 textArea.value += $(this).text().split(':')[1].trim() + '/';
356 textArea.value += '\t\t' + window.location.href;
357 textArea.value += '\n';
358 $('.success').each(function () {
359 textArea.value += $(this).text() + '\n\n';
362 $('.sql pre').each(function () {
363 textArea.value += $(this).text() + '\n\n';
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';
371 textArea.value += '\n';
372 $('.table_results tbody tr').each(function () {
373 $(this).find('.data span').each(function () {
374 textArea.value += $(this).text() + '\t';
376 textArea.value += '\n';
379 document.body.appendChild(textArea);
384 document.execCommand('copy');
386 alert('Sorry! Unable to copy');
389 document.body.removeChild(textArea);
390 }); // end of Copy to Clipboard action
393 * Attach Event Handler for 'Print' link
395 $(document).on('click', '#printView', function (event) {
396 event.preventDefault();
398 // Take to preview mode
399 Functions.printPreview();
400 }); // end of 'Print' action
403 * Attach the {@link makegrid} function to a custom event, which will be
404 * triggered manually everytime the table of results is reloaded
407 $(document).on('makegrid', '.sqlqueryresults', function () {
408 $('.table_results').each(function () {
414 * Append the "Show/Hide query box" message to the query input form
417 * @name appendToggleSpan
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
428 // Attach the toggling of the query box visibility to a click
429 $('#togglequerybox').on('click', function () {
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">');
439 $link.text(Messages.strHideQueryBox);
441 // avoid default click action
448 * Event handler for sqlqueryform.ajax button_submit_query
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');
465 Cookies.set('autoSavedSql', '');
467 var isShowQuery = $('input[name="show_query"]').is(':checked');
469 window.localStorage.showThisQuery = '1';
470 var db = $('input[name="db"]').val();
471 var table = $('input[name="table"]').val();
473 if (codeMirrorEditor) {
474 query = codeMirrorEditor.getValue();
476 query = $('#sqlquery').val();
478 Sql.showThisQuery(db, table, query);
480 window.localStorage.showThisQuery = '0';
485 * Event handler to show appropiate number of variable boxes
486 * based on the bookmarked query
488 $(document).on('change', '#id_bookmark', function () {
489 var varCount = $(this).find('option:selected').data('varcount');
490 if (typeof varCount === 'undefined') {
494 var $varDiv = $('#bookmark_variables');
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 + '">'));
501 if (varCount === 0) {
502 $varDiv.parent('.formelement').hide();
504 $varDiv.parent('.formelement').show();
509 * Event handler for hitting enter on sqlqueryform bookmark_variable
510 * (the Variable textfield in Bookmarked SQL query section)
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
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');
534 * Ajax Event handler for 'SQL Query Submit'
536 * @see Functions.ajaxShowMessage()
538 * @name sqlqueryform_submit
540 $(document).on('submit', '#sqlqueryform.ajax', function (event) {
541 event.preventDefault();
544 if (codeMirrorEditor) {
545 $form[0].elements.sql_query.value = codeMirrorEditor.getValue();
547 if (! Functions.checkSqlQuery($form[0])) {
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') {
567 if ('1' === data.action_bookmark) {
568 $('#sqlquery').text(data.sql_query);
569 // send to codemirror if possible
570 Functions.setQuery(data.sql_query);
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();
583 $sqlqueryresultsouter
586 Functions.highlightSql($sqlqueryresultsouter);
589 if (history && history.pushState) {
590 history.replaceState({
595 AJAX.handleMenu.replace(data.menu);
597 MicroHistory.menus.replace(data.menu);
598 MicroHistory.menus.add(data.menuHash, data.menu);
600 } else if (data.menuHash) {
601 if (! (history && history.pushState)) {
602 MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
607 CommonParams.setAll(data.params);
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();
619 } else if (typeof data.reload !== 'undefined') {
620 // this happens if a USE or DROP command was typed
621 CommonActions.setDb(data.db);
625 url = 'table_sql.php';
630 url = 'server_sql.php';
632 CommonActions.refreshMain(url, function () {
633 $('#sqlqueryresultsouter')
636 Functions.highlightSql($('#sqlqueryresultsouter'));
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');
651 } else if (typeof data !== 'undefined' && data.success === false) {
652 // show an error message that stays on screen
653 $sqlqueryresultsouter
656 $('html, body').animate({ scrollTop: $(document).height() }, 200);
658 Functions.ajaxRemoveMessage($msgbox);
660 }); // end SQL Query submit
663 * Ajax Event handler for the display options
665 * @name displayOptionsForm_submit
667 $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
668 event.preventDefault();
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');
679 .trigger('makegrid');
680 Functions.initSlider();
681 Functions.highlightSql($sqlqueryresults);
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>'
695 // Selecting columns that will be considered for filtering and searching.
696 $headerCells.each(function () {
697 targetColumns.push($.trim($(this).text()));
700 var phrase = $(this).val();
701 // Set same value to both Filter rows fields.
702 $('.filter_rows[data-for=\'' + uniqueId + '\']').not(this).val(phrase);
704 $targetTable.find('thead > tr').prepend(dummyTh);
705 $.uiTableFilter($targetTable, phrase, targetColumns);
706 $targetTable.find('th.dummy_th').remove();
708 // Filter row handling. --ENDS--
710 // Prompt to confirm on Show All
711 $('body').on('click', '.navigation .showAllRows', function (e) {
713 var $form = $(this).parents('form');
715 if (! $(this).is(':checked')) { // already showing all rows
716 Sql.submitShowAllForm();
718 $form.confirm(Messages.strShowAllRowsWarning, $form.attr('action'), function () {
719 Sql.submitShowAllForm();
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();
728 $.post($form.attr('action'), submitData, AJAX.responseHandler);
732 $('body').on('keyup', '#sqlqueryform', function () {
733 Functions.handleSimulateQueryButton();
737 * Ajax event handler for 'Simulate DML'.
739 $('body').on('click', '#simulate_dml', function () {
740 var $form = $('#sqlqueryform');
742 var delimiter = $('#id_sql_delimiter').val();
743 var dbName = $form.find('input[name="db"]').val();
745 if (codeMirrorEditor) {
746 query = codeMirrorEditor.getValue();
748 query = $('#sqlquery').val();
751 if (query.length === 0) {
752 alert(Messages.strFormEmpty);
753 $('#sqlquery').trigger('focus');
757 var $msgbox = Functions.ajaxShowMessage();
760 url: $form.attr('action'),
762 'server': CommonParams.get('server'),
767 'sql_delimiter': delimiter
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>';
782 dialogContent += '<hr>';
786 dialogContent += response.message;
788 dialogContent += '</div>';
789 var $dialogContent = $(dialogContent);
790 var buttonOptions = {};
791 buttonOptions[Messages.strClose] = function () {
792 $(this).dialog('close');
794 $('<div></div>').append($dialogContent).dialog({
798 buttons: buttonOptions,
799 title: Messages.strSimulateDML,
801 Functions.highlightSql($(this));
808 Functions.ajaxShowMessage(response.error);
812 Functions.ajaxShowMessage(Messages.strErrorProcessingRequest);
818 * Handles multi submits of results browsing page such as edit, delete and export
820 $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
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();
828 $.post($form.attr('action'), submitData, AJAX.responseHandler);
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.
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
844 var $table = $thisTh.parents('.table_results');
845 if (! $table.length) {
846 $table = $thisTh.parents('table').siblings('.table_results');
848 var $tds = $table.find('tbody tr').find('td.data:eq(' + thIndex + ')');
849 if (isAddClass === undefined) {
850 $tds.toggleClass(newClass);
852 $tds.toggleClass(newClass, isAddClass);
857 * Handles browse foreign values modal dialog
859 * @param object $this_a reference to the browse foreign value link
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';
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',
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
887 }).done(function () {
889 $(tableId).on('click', 'td a.foreign_value', function (e) {
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');
896 // Set selected value as input value
897 $input.val($(this).data('key'));
898 $dialog.dialog('close');
900 $(formId).on('click', showAllId, function () {
903 $(formId).on('submit', function (e) {
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');
910 var postParams = $(this).serializeArray();
911 // if showAll button was clicked to submit form then
912 // add showAll button parameter to form
915 name: $(showAllId).attr('name'),
916 value: $(showAllId).val()
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());
930 Sql.checkSavedQuery = function () {
931 if (isStorageSupported('localStorage') && window.localStorage.autoSavedSql !== undefined) {
932 Functions.ajaxShowMessage(Messages.strPreviousSaveQuery);
936 AJAX.registerOnload('sql.js', function () {
937 $('body').on('click', 'a.browse_foreign', function (e) {
939 Sql.browseForeignDialog($(this));
943 * vertical column highlighting in horizontal mode when hovering over the column header
945 $(document).on('mouseenter', 'th.column_heading.pointer', function () {
946 Sql.changeClassForColumn($(this), 'hover', true);
948 $(document).on('mouseleave', 'th.column_heading.pointer', function () {
949 Sql.changeClassForColumn($(this), 'hover', false);
953 * vertical column marking in horizontal mode when clicking the column header
955 $(document).on('click', 'th.column_heading.marker', function () {
956 Sql.changeClassForColumn($(this), 'marked');
960 * create resizable table
962 $('.sqlqueryresults').trigger('makegrid');
965 * Check if there is any saved query
967 if (codeMirrorEditor || document.sqlform) {
968 Sql.checkSavedQuery();
975 Sql.makeProfilingChart = function () {
976 if ($('#profilingchart').length === 0 ||
977 $('#profilingchart').html().length !== 0 ||
978 !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
984 $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
985 data.push([key, parseFloat(value)]);
988 // Remove chart and data divs contents
989 $('#profilingchart').html('').show();
990 $('#profilingChartData').html('');
992 Functions.createProfilingChart('profilingchart', data);
996 * initialize profiling data tables
998 Sql.initProfilingTables = function () {
999 if (!$.tablesorter) {
1002 // Added to allow two direction sorting
1005 .off('click mousedown');
1007 $('#profiletable').tablesorter({
1010 textExtraction: function (node) {
1011 if (node.children.length > 0) {
1012 return node.children[0].innerHTML;
1014 return node.innerHTML;
1018 // Added to allow two direction sorting
1019 $('#profilesummarytable')
1021 .off('click mousedown');
1023 $('#profilesummarytable').tablesorter({
1026 textExtraction: function (node) {
1027 if (node.children.length > 0) {
1028 return node.children[0].innerHTML;
1030 return node.innerHTML;
1036 AJAX.registerOnload('sql.js', function () {
1037 Sql.makeProfilingChart();
1038 Sql.initProfilingTables();
1042 * Polyfill to make table headers sticky.
1044 var elements = $('.sticky');
1045 Stickyfill.add(elements);