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"]');
213 $(document).off('submit', '#maxRowsForm');
217 * @description <p>Ajax scripts for sql and browse pages</p>
219 * Actions ajaxified here:
221 * <li>Retrieve results of an SQL query</li>
222 * <li>Paginate the results table</li>
223 * <li>Sort the results table</li>
224 * <li>Change table according to display options</li>
225 * <li>Grid editing of data</li>
226 * <li>Saving a bookmark</li>
229 * @name document.ready
232 AJAX.registerOnload('sql.js', function () {
233 if (codeMirrorEditor || document.sqlform) {
234 Sql.setShowThisQuery();
237 if (codeMirrorEditor) {
238 codeMirrorEditor.on('change', function () {
239 Sql.autoSave(codeMirrorEditor.getValue());
242 $('#sqlquery').on('input propertychange', function () {
243 Sql.autoSave($('#sqlquery').val());
245 var useLocalStorageValue = isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined';
246 // Save sql query with sort
247 if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
248 $('select[name="sql_query"]').on('change', function () {
249 Sql.autoSaveWithSort($(this).val());
251 $('.sortlink').on('click', function () {
252 Sql.clearAutoSavedSort();
255 Sql.clearAutoSavedSort();
257 // If sql query with sort for current table is stored, change sort by key select value
258 var sortStoredQuery = useLocalStorageValue ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
259 if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
260 $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
265 // Delete row from SQL results
266 $(document).on('click', 'a.delete_row.ajax', function (e) {
268 var question = Functions.sprintf(Messages.strDoYouReally, Functions.escapeHtml($(this).closest('td').find('div').text()));
270 $link.confirm(question, $link.attr('href'), function (url) {
271 Functions.ajaxShowMessage();
272 var argsep = CommonParams.get('arg_separator');
273 var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
274 var postData = $link.getPostData();
276 params += argsep + postData;
278 $.post(url, params, function (data) {
280 Functions.ajaxShowMessage(data.message);
281 $link.closest('tr').remove();
283 Functions.ajaxShowMessage(data.error, false);
289 // Ajaxification for 'Bookmark this SQL query'
290 $(document).on('submit', '.bookmarkQueryForm', function (e) {
292 Functions.ajaxShowMessage();
293 var argsep = CommonParams.get('arg_separator');
294 $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
296 Functions.ajaxShowMessage(data.message);
298 Functions.ajaxShowMessage(data.error, false);
303 /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
304 $('input#bkm_label').on('input', function () {
305 $('input#id_bkm_all_users, input#id_bkm_replace')
307 .toggle($(this).val().length > 0);
311 * Attach Event Handler for 'Copy to clipbpard
313 $(document).on('click', '#copyToClipBoard', function (event) {
314 event.preventDefault();
316 var textArea = document.createElement('textarea');
319 // *** This styling is an extra step which is likely not required. ***
321 // Why is it here? To ensure:
322 // 1. the element is able to have focus and selection.
323 // 2. if element was to flash render it has minimal visual impact.
324 // 3. less flakyness with selection and copying which **might** occur if
325 // the textarea element is not visible.
327 // The likelihood is the element won't even render, not even a flash,
328 // so some of these are just precautions. However in IE the element
329 // is visible whilst the popup box asking the user for permission for
330 // the web page to copy to the clipboard.
333 // Place in top-left corner of screen regardless of scroll position.
334 textArea.style.position = 'fixed';
335 textArea.style.top = 0;
336 textArea.style.left = 0;
338 // Ensure it has a small width and height. Setting to 1px / 1em
339 // doesn't work as this gives a negative w/h on some browsers.
340 textArea.style.width = '2em';
341 textArea.style.height = '2em';
343 // We don't need padding, reducing the size if it does flash render.
344 textArea.style.padding = 0;
346 // Clean up any borders.
347 textArea.style.border = 'none';
348 textArea.style.outline = 'none';
349 textArea.style.boxShadow = 'none';
351 // Avoid flash of white box if rendered for any reason.
352 textArea.style.background = 'transparent';
356 $('#server-breadcrumb a').each(function () {
357 textArea.value += $(this).text().split(':')[1].trim() + '/';
359 textArea.value += '\t\t' + window.location.href;
360 textArea.value += '\n';
361 $('.alert-success').each(function () {
362 textArea.value += $(this).text() + '\n\n';
365 $('.sql pre').each(function () {
366 textArea.value += $(this).text() + '\n\n';
369 $('.table_results .column_heading a').each(function () {
370 // Don't copy ordering number text within <small> tag
371 textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
374 textArea.value += '\n';
375 $('.table_results tbody tr').each(function () {
376 $(this).find('.data span').each(function () {
377 textArea.value += $(this).text() + '\t';
379 textArea.value += '\n';
382 document.body.appendChild(textArea);
387 document.execCommand('copy');
389 alert('Sorry! Unable to copy');
392 document.body.removeChild(textArea);
393 }); // end of Copy to Clipboard action
396 * Attach Event Handler for 'Print' link
398 $(document).on('click', '#printView', function (event) {
399 event.preventDefault();
401 // Take to preview mode
402 Functions.printPreview();
403 }); // end of 'Print' action
406 * Attach the {@link makegrid} function to a custom event, which will be
407 * triggered manually everytime the table of results is reloaded
410 $(document).on('makegrid', '.sqlqueryresults', function () {
411 $('.table_results').each(function () {
417 * Attach a custom event for sticky column headings which will be
418 * triggered manually everytime the table of results is reloaded
421 $(document).on('stickycolumns', '.sqlqueryresults', function () {
422 $('.sticky_columns').remove();
423 $('.table_results').each(function () {
424 var $tableResults = $(this);
425 // add sticky columns div
426 var $stickColumns = Sql.initStickyColumns($tableResults);
427 Sql.rearrangeStickyColumns($stickColumns, $tableResults);
428 // adjust sticky columns on scroll
429 $(document).on('scroll', window, function () {
430 Sql.handleStickyColumns($stickColumns, $tableResults);
436 * Append the "Show/Hide query box" message to the query input form
439 * @name appendToggleSpan
441 // do not add this link more than once
442 if (! $('#sqlqueryform').find('button').is('#togglequerybox')) {
443 $('<button class="btn btn-secondary" id="togglequerybox"></button>')
444 .html(Messages.strHideQueryBox)
445 .appendTo('#sqlqueryform')
446 // initially hidden because at this point, nothing else
447 // appears under the link
450 // Attach the toggling of the query box visibility to a click
451 $('#togglequerybox').on('click', function () {
453 $link.siblings().slideToggle('fast');
454 if ($link.text() === Messages.strHideQueryBox) {
455 $link.text(Messages.strShowQueryBox);
456 // cheap trick to add a spacer between the menu tabs
457 // and "Show query box"; feel free to improve!
458 $('#togglequerybox_spacer').remove();
459 $link.before('<br id="togglequerybox_spacer">');
461 $link.text(Messages.strHideQueryBox);
463 // avoid default click action
470 * Event handler for sqlqueryform.ajax button_submit_query
474 $(document).on('click', '#button_submit_query', function () {
475 $('.alert-success,.alert-danger').hide();
476 // hide already existing error or success message
477 var $form = $(this).closest('form');
478 // the Go button related to query submission was clicked,
479 // instead of the one related to Bookmarks, so empty the
480 // id_bookmark selector to avoid misinterpretation in
481 // /import about what needs to be done
482 $form.find('select[name=id_bookmark]').val('');
483 // let normal event propagation happen
484 if (isStorageSupported('localStorage')) {
485 window.localStorage.removeItem('autoSavedSql');
487 Cookies.set('autoSavedSql', '');
489 var isShowQuery = $('input[name="show_query"]').is(':checked');
491 window.localStorage.showThisQuery = '1';
492 var db = $('input[name="db"]').val();
493 var table = $('input[name="table"]').val();
495 if (codeMirrorEditor) {
496 query = codeMirrorEditor.getValue();
498 query = $('#sqlquery').val();
500 Sql.showThisQuery(db, table, query);
502 window.localStorage.showThisQuery = '0';
507 * Event handler to show appropiate number of variable boxes
508 * based on the bookmarked query
510 $(document).on('change', '#id_bookmark', function () {
511 var varCount = $(this).find('option:selected').data('varcount');
512 if (typeof varCount === 'undefined') {
516 var $varDiv = $('#bookmarkVariables');
518 for (var i = 1; i <= varCount; i++) {
519 $varDiv.append($('<div class="form-group">'));
520 $varDiv.append($('<label for="bookmarkVariable' + i + '">' + Functions.sprintf(Messages.strBookmarkVariable, i) + '</label>'));
521 $varDiv.append($('<input class="form-control" type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmarkVariable' + i + '">'));
522 $varDiv.append($('</div>'));
525 if (varCount === 0) {
526 $varDiv.parent().hide();
528 $varDiv.parent().show();
533 * Event handler for hitting enter on sqlqueryform bookmark_variable
534 * (the Variable textfield in Bookmarked SQL query section)
538 $('input[name=bookmark_variable]').on('keypress', function (event) {
539 // force the 'Enter Key' to implicitly click the #button_submit_bookmark
540 var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
541 if (keycode === 13) { // keycode for enter key
542 // When you press enter in the sqlqueryform, which
543 // has 2 submit buttons, the default is to run the
544 // #button_submit_query, because of the tabindex
546 // This submits #button_submit_bookmark instead,
547 // because when you are in the Bookmarked SQL query
548 // section and hit enter, you expect it to do the
549 // same action as the Go button in that section.
550 $('#button_submit_bookmark').trigger('click');
558 * Ajax Event handler for 'SQL Query Submit'
560 * @see Functions.ajaxShowMessage()
562 * @name sqlqueryform_submit
564 $(document).on('submit', '#sqlqueryform.ajax', function (event) {
565 event.preventDefault();
568 if (codeMirrorEditor) {
569 $form[0].elements.sql_query.value = codeMirrorEditor.getValue();
571 if (! Functions.checkSqlQuery($form[0])) {
575 // remove any div containing a previous error message
576 $('.alert-danger').remove();
578 var $msgbox = Functions.ajaxShowMessage();
579 var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
581 Functions.prepareForAjaxRequest($form);
583 var argsep = CommonParams.get('arg_separator');
584 $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
585 if (typeof data !== 'undefined' && data.success === true) {
586 // success happens if the query returns rows or not
588 // show a message that stays on screen
589 if (typeof data.action_bookmark !== 'undefined') {
591 if ('1' === data.action_bookmark) {
592 $('#sqlquery').text(data.sql_query);
593 // send to codemirror if possible
594 Functions.setQuery(data.sql_query);
597 if ('2' === data.action_bookmark) {
598 $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
599 // if there are no bookmarked queries now (only the empty option),
600 // remove the bookmark section
601 if ($('#id_bookmark option').length === 1) {
602 $('#fieldsetBookmarkOptions').hide();
603 $('#fieldsetBookmarkOptionsFooter').hide();
607 $sqlqueryresultsouter
610 Functions.highlightSql($sqlqueryresultsouter);
613 if (history && history.pushState) {
614 history.replaceState({
619 AJAX.handleMenu.replace(data.menu);
621 MicroHistory.menus.replace(data.menu);
622 MicroHistory.menus.add(data.menuHash, data.menu);
624 } else if (data.menuHash) {
625 if (! (history && history.pushState)) {
626 MicroHistory.menus.replace(MicroHistory.menus.get(data.menuHash));
631 CommonParams.setAll(data.params);
634 if (typeof data.ajax_reload !== 'undefined') {
635 if (data.ajax_reload.reload) {
636 if (data.ajax_reload.table_name) {
637 CommonParams.set('table', data.ajax_reload.table_name);
638 CommonActions.refreshMain();
643 } else if (typeof data.reload !== 'undefined') {
644 // this happens if a USE or DROP command was typed
645 CommonActions.setDb(data.db);
649 url = 'index.php?route=/table/sql';
651 url = 'index.php?route=/database/sql';
654 url = 'index.php?route=/server/sql';
656 CommonActions.refreshMain(url, function () {
657 $('#sqlqueryresultsouter')
660 Functions.highlightSql($('#sqlqueryresultsouter'));
664 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
665 $('#togglequerybox').show();
666 Functions.initSlider();
668 if (typeof data.action_bookmark === 'undefined') {
669 if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
670 if ($('#togglequerybox').siblings(':visible').length > 0) {
671 $('#togglequerybox').trigger('click');
675 } else if (typeof data !== 'undefined' && data.success === false) {
676 // show an error message that stays on screen
677 $sqlqueryresultsouter
680 $('html, body').animate({ scrollTop: $(document).height() }, 200);
682 Functions.ajaxRemoveMessage($msgbox);
684 }); // end SQL Query submit
687 * Ajax Event handler for the display options
689 * @name displayOptionsForm_submit
691 $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
692 event.preventDefault();
696 var $msgbox = Functions.ajaxShowMessage();
697 var argsep = CommonParams.get('arg_separator');
698 $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
699 Functions.ajaxRemoveMessage($msgbox);
700 var $sqlqueryresults = $form.parents('.sqlqueryresults');
704 .trigger('stickycolumns');
705 Functions.initSlider();
706 Functions.highlightSql($sqlqueryresults);
708 }); // end displayOptionsForm handler
710 // Filter row handling. --STARTS--
711 $(document).on('keyup', '.filter_rows', function () {
712 var uniqueId = $(this).data('for');
713 var $targetTable = $('.table_results[data-uniqueId=\'' + uniqueId + '\']');
714 var $headerCells = $targetTable.find('th[data-column]');
715 var targetColumns = [];
716 // To handle colspan=4, in case of edit,copy etc options.
717 var dummyTh = ($('.edit_row_anchor').length !== 0 ?
718 '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
720 // Selecting columns that will be considered for filtering and searching.
721 $headerCells.each(function () {
722 targetColumns.push($.trim($(this).text()));
725 var phrase = $(this).val();
726 // Set same value to both Filter rows fields.
727 $('.filter_rows[data-for=\'' + uniqueId + '\']').not(this).val(phrase);
729 $targetTable.find('thead > tr').prepend(dummyTh);
730 $.uiTableFilter($targetTable, phrase, targetColumns);
731 $targetTable.find('th.dummy_th').remove();
733 // Filter row handling. --ENDS--
735 // Prompt to confirm on Show All
736 $('body').on('click', '.navigation .showAllRows', function (e) {
738 var $form = $(this).parents('form');
740 if (! $(this).is(':checked')) { // already showing all rows
741 Sql.submitShowAllForm();
743 $form.confirm(Messages.strShowAllRowsWarning, $form.attr('action'), function () {
744 Sql.submitShowAllForm();
748 Sql.submitShowAllForm = function () {
749 var argsep = CommonParams.get('arg_separator');
750 var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
751 Functions.ajaxShowMessage();
753 $.post($form.attr('action'), submitData, AJAX.responseHandler);
757 $('body').on('keyup', '#sqlqueryform', function () {
758 Functions.handleSimulateQueryButton();
762 * Ajax event handler for 'Simulate DML'.
764 $('body').on('click', '#simulate_dml', function () {
765 var $form = $('#sqlqueryform');
767 var delimiter = $('#id_sql_delimiter').val();
768 var dbName = $form.find('input[name="db"]').val();
770 if (codeMirrorEditor) {
771 query = codeMirrorEditor.getValue();
773 query = $('#sqlquery').val();
776 if (query.length === 0) {
777 alert(Messages.strFormEmpty);
778 $('#sqlquery').trigger('focus');
782 var $msgbox = Functions.ajaxShowMessage();
785 url: $form.attr('action'),
787 'server': CommonParams.get('server'),
792 'sql_delimiter': delimiter
794 success: function (response) {
795 Functions.ajaxRemoveMessage($msgbox);
796 if (response.success) {
797 var dialogContent = '<div class="preview_sql">';
798 if (response.sql_data) {
799 var len = response.sql_data.length;
800 for (var i = 0; i < len; i++) {
801 dialogContent += '<strong>' + Messages.strSQLQuery +
802 '</strong>' + response.sql_data[i].sql_query +
803 Messages.strMatchedRows +
804 ' <a href="' + response.sql_data[i].matched_rows_url +
805 '">' + response.sql_data[i].matched_rows + '</a><br>';
807 dialogContent += '<hr>';
811 dialogContent += response.message;
813 dialogContent += '</div>';
814 var $dialogContent = $(dialogContent);
815 var buttonOptions = {};
816 buttonOptions[Messages.strClose] = function () {
817 $(this).dialog('close');
819 $('<div></div>').append($dialogContent).dialog({
823 buttons: buttonOptions,
824 title: Messages.strSimulateDML,
826 Functions.highlightSql($(this));
833 Functions.ajaxShowMessage(response.error);
837 Functions.ajaxShowMessage(Messages.strErrorProcessingRequest);
843 * Handles multi submits of results browsing page such as edit, delete and export
845 $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
847 var $button = $(this);
848 var action = $button.val();
849 var $form = $button.closest('form');
850 var argsep = CommonParams.get('arg_separator');
851 var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep;
852 Functions.ajaxShowMessage();
856 if (action === 'edit') {
857 submitData = submitData + argsep + 'default_action=update';
858 url = 'index.php?route=/table/change/rows';
859 } else if (action === 'copy') {
860 submitData = submitData + argsep + 'default_action=insert';
861 url = 'index.php?route=/table/change/rows';
862 } else if (action === 'export') {
863 url = 'index.php?route=/table/export/rows';
864 } else if (action === 'delete') {
865 url = 'index.php?route=/table/delete/confirm';
870 $.post(url, submitData, AJAX.responseHandler);
873 $(document).on('submit', '#maxRowsForm', function () {
874 var unlimNumRows = $(this).find('input[name="unlim_num_rows"]').val();
876 var maxRowsCheck = Functions.checkFormElementInRange(
879 Messages.strNotValidRowNumber,
882 var posCheck = Functions.checkFormElementInRange(
885 Messages.strNotValidRowNumber,
887 unlimNumRows > 0 ? unlimNumRows - 1 : null
890 return maxRowsCheck && posCheck;
895 * Starting from some th, change the class of all td under it.
896 * If isAddClass is specified, it will be used to determine whether to add or remove the class.
898 Sql.changeClassForColumn = function ($thisTh, newClass, isAddClass) {
899 // index 0 is the th containing the big T
900 var thIndex = $thisTh.index();
901 var hasBigT = $thisTh.closest('tr').children().first().hasClass('column_action');
902 // .eq() is zero-based
906 var $table = $thisTh.parents('.table_results');
907 if (! $table.length) {
908 $table = $thisTh.parents('table').siblings('.table_results');
910 var $tds = $table.find('tbody tr').find('td.data').eq(thIndex);
911 if (isAddClass === undefined) {
912 $tds.toggleClass(newClass);
914 $tds.toggleClass(newClass, isAddClass);
919 * Handles browse foreign values modal dialog
921 * @param object $this_a reference to the browse foreign value link
923 Sql.browseForeignDialog = function ($thisA) {
924 var formId = '#browse_foreign_form';
925 var showAllId = '#foreign_showAll';
926 var tableId = '#browse_foreign_table';
927 var filterId = '#input_foreign_filter';
929 var argSep = CommonParams.get('arg_separator');
930 var params = $thisA.getPostData();
931 params += argSep + 'ajax_request=true';
932 $.post($thisA.attr('href'), params, function (data) {
933 // Creates browse foreign value dialog
934 $dialog = $('<div>').append(data.message).dialog({
935 title: Messages.strBrowseForeignValues,
936 width: Math.min($(window).width() - 100, 700),
937 maxHeight: $(window).height() - 100,
938 dialogClass: 'browse_foreign_modal',
940 // remove event handlers attached to elements related to dialog
941 $(tableId).off('click', 'td a.foreign_value');
942 $(formId).off('click', showAllId);
943 $(formId).off('submit');
944 // remove dialog itself
949 }).done(function () {
951 $(tableId).on('click', 'td a.foreign_value', function (e) {
953 var $input = $thisA.prev('input[type=text]');
954 // Check if input exists or get CEdit edit_box
955 if ($input.length === 0) {
956 $input = $thisA.closest('.edit_area').prev('.edit_box');
958 // Set selected value as input value
959 $input.val($(this).data('key'));
960 $dialog.dialog('close');
962 $(formId).on('click', showAllId, function () {
965 $(formId).on('submit', function (e) {
967 // if filter value is not equal to old value
968 // then reset page number to 1
969 if ($(filterId).val() !== $(filterId).data('old')) {
970 $(formId).find('select[name=pos]').val('0');
972 var postParams = $(this).serializeArray();
973 // if showAll button was clicked to submit form then
974 // add showAll button parameter to form
977 name: $(showAllId).attr('name'),
978 value: $(showAllId).val()
981 // updates values in dialog
982 $.post($(this).attr('action') + '&ajax_request=1', postParams, function (data) {
983 var $obj = $('<div>').html(data.message);
984 $(formId).html($obj.find(formId).html());
985 $(tableId).html($obj.find(tableId).html());
992 Sql.checkSavedQuery = function () {
993 if (isStorageSupported('localStorage') && window.localStorage.autoSavedSql !== undefined) {
994 Functions.ajaxShowMessage(Messages.strPreviousSaveQuery);
998 AJAX.registerOnload('sql.js', function () {
999 $('body').on('click', 'a.browse_foreign', function (e) {
1001 Sql.browseForeignDialog($(this));
1005 * vertical column highlighting in horizontal mode when hovering over the column header
1007 $(document).on('mouseenter', 'th.column_heading.pointer', function () {
1008 Sql.changeClassForColumn($(this), 'hover', true);
1010 $(document).on('mouseleave', 'th.column_heading.pointer', function () {
1011 Sql.changeClassForColumn($(this), 'hover', false);
1015 * vertical column marking in horizontal mode when clicking the column header
1017 $(document).on('click', 'th.column_heading.marker', function () {
1018 Sql.changeClassForColumn($(this), 'marked');
1022 * create resizable table
1024 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
1027 * Check if there is any saved query
1029 if (codeMirrorEditor || document.sqlform) {
1030 Sql.checkSavedQuery();
1037 Sql.makeProfilingChart = function () {
1038 if ($('#profilingchart').length === 0 ||
1039 $('#profilingchart').html().length !== 0 ||
1040 !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
1046 $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
1047 data.push([key, parseFloat(value)]);
1050 // Remove chart and data divs contents
1051 $('#profilingchart').html('').show();
1052 $('#profilingChartData').html('');
1054 Functions.createProfilingChart('profilingchart', data);
1058 * initialize profiling data tables
1060 Sql.initProfilingTables = function () {
1061 if (!$.tablesorter) {
1064 // Added to allow two direction sorting
1067 .off('click mousedown');
1069 $('#profiletable').tablesorter({
1072 textExtraction: function (node) {
1073 if (node.children.length > 0) {
1074 return node.children[0].innerHTML;
1076 return node.innerHTML;
1080 // Added to allow two direction sorting
1081 $('#profilesummarytable')
1083 .off('click mousedown');
1085 $('#profilesummarytable').tablesorter({
1088 textExtraction: function (node) {
1089 if (node.children.length > 0) {
1090 return node.children[0].innerHTML;
1092 return node.innerHTML;
1099 * Set position, left, top, width of sticky_columns div
1101 Sql.setStickyColumnsPosition = function ($stickyColumns, $tableResults, position, top, left, marginLeft) {
1103 .css('position', position)
1105 .css('left', left ? left : 'auto')
1106 .css('margin-left', marginLeft ? marginLeft : '0px')
1107 .css('width', $tableResults.width());
1111 * Initialize sticky columns
1113 Sql.initStickyColumns = function ($tableResults) {
1114 return $('<table class="sticky_columns"></table>')
1115 .insertBefore($tableResults)
1116 .css('position', 'fixed')
1117 .css('z-index', '98')
1118 .css('width', $tableResults.width())
1119 .css('margin-left', $('#page_content').css('margin-left'))
1120 .css('top', $('#floating_menubar').height())
1121 .css('display', 'none');
1125 * Arrange/Rearrange columns in sticky header
1127 Sql.rearrangeStickyColumns = function ($stickyColumns, $tableResults) {
1128 var $originalHeader = $tableResults.find('thead');
1129 var $originalColumns = $originalHeader.find('tr').first().children();
1130 var $clonedHeader = $originalHeader.clone();
1131 var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
1132 var isSafari = navigator.userAgent.indexOf('Safari') > -1;
1133 // clone width per cell
1134 $clonedHeader.find('tr').first().children().each(function (i) {
1135 var width = $originalColumns.eq(i).width();
1136 if (! isFirefox && ! isSafari) {
1139 $(this).width(width);
1141 $(this).css('min-width', width).css('max-width', width);
1144 $stickyColumns.empty().append($clonedHeader);
1148 * Adjust sticky columns on horizontal/vertical scroll for all tables
1150 Sql.handleAllStickyColumns = function () {
1151 $('.sticky_columns').each(function () {
1152 Sql.handleStickyColumns($(this), $(this).next('.table_results'));
1157 * Adjust sticky columns on horizontal/vertical scroll
1159 Sql.handleStickyColumns = function ($stickyColumns, $tableResults) {
1160 var currentScrollX = $(window).scrollLeft();
1161 var windowOffset = $(window).scrollTop();
1162 var tableStartOffset = $tableResults.offset().top;
1163 var tableEndOffset = tableStartOffset + $tableResults.height();
1164 if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
1165 // for horizontal scrolling
1166 if (prevScrollX !== currentScrollX) {
1167 prevScrollX = currentScrollX;
1168 Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'absolute', $('#floating_menubar').height() + windowOffset - tableStartOffset);
1169 // for vertical scrolling
1171 Sql.setStickyColumnsPosition($stickyColumns, $tableResults, 'fixed', $('#floating_menubar').height(), $('#pma_navigation').width() - currentScrollX, $('#page_content').css('margin-left'));
1173 $stickyColumns.show();
1175 $stickyColumns.hide();
1179 AJAX.registerOnload('sql.js', function () {
1180 Sql.makeProfilingChart();
1181 Sql.initProfilingTables();