1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * Used in or for console
5 * @package phpMyAdmin-Console
13 * @var object, jQuery object, selector is '#pma_console>.content'
16 $consoleContent: null,
18 * @var object, jQuery object, selector is '#pma_console .content',
22 $consoleAllContents: null,
24 * @var object, jQuery object, selector is '#pma_console .toolbar'
27 $consoleToolbar: null,
29 * @var object, jQuery object, selector is '#pma_console .template'
32 $consoleTemplates: null,
34 * @var object, jQuery object, form for submit
39 * @var object, contain console config
44 * @var bool, if console element exist, it'll be true
49 * @var bool, make sure console events bind only once
54 * Used for console initialize, reinit is ok, just some variable assignment
58 initialize: function() {
60 if ($('#pma_console').length === 0) {
64 PMA_console.isEnabled = true;
66 // Cookie var checks and init
67 if (! Cookies.get('pma_console_height')) {
68 Cookies.set('pma_console_height', 92);
70 if (! Cookies.get('pma_console_mode')) {
71 Cookies.set('pma_console_mode', 'info');
75 PMA_console.$consoleToolbar = $("#pma_console").find(">.toolbar");
76 PMA_console.$consoleContent = $("#pma_console").find(">.content");
77 PMA_console.$consoleAllContents = $('#pma_console').find('.content');
78 PMA_console.$consoleTemplates = $('#pma_console').find('>.templates');
80 // Generate a from for post
81 PMA_console.$requestForm = $('<form method="post" action="import.php">' +
82 '<input name="is_js_confirmed" value="0">' +
83 '<textarea name="sql_query"></textarea>' +
84 '<input name="console_message_id" value="0">' +
85 '<input name="server" value="">' +
86 '<input name="db" value="">' +
87 '<input name="table" value="">' +
88 '<input name="token" value="">' +
91 PMA_console.$requestForm.children('[name=token]').val(PMA_commonParams.get('token'));
92 PMA_console.$requestForm.on('submit', AJAX.requestHandler);
94 // Event binds shouldn't run again
95 if (PMA_console.isInitialized === false) {
98 var tempConfig = Cookies.getJSON('pma_console_config');
100 if (tempConfig.alwaysExpand === true) {
101 $('#pma_console_options input[name=always_expand]').prop('checked', true);
103 if (tempConfig.startHistory === true) {
104 $('#pma_console_options').find('input[name=start_history]').prop('checked', true);
106 if (tempConfig.currentQuery === true) {
107 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
109 if (ConsoleEnterExecutes === true) {
110 $('#pma_console_options').find('input[name=enter_executes]').prop('checked', true);
112 if (tempConfig.darkTheme === true) {
113 $('#pma_console_options').find('input[name=dark_theme]').prop('checked', true);
114 $('#pma_console').find('>.content').addClass('console_dark_theme');
117 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
120 PMA_console.updateConfig();
122 PMA_consoleResizer.initialize();
123 PMA_consoleInput.initialize();
124 PMA_consoleMessages.initialize();
125 PMA_consoleBookmarks.initialize();
126 PMA_consoleDebug.initialize();
128 PMA_console.$consoleToolbar.children('.console_switch').click(PMA_console.toggle);
130 $('#pma_console').find('.toolbar').children().mousedown(function(event) {
131 event.preventDefault();
132 event.stopImmediatePropagation();
135 $('#pma_console').find('.button.clear').click(function() {
136 PMA_consoleMessages.clear();
139 $('#pma_console').find('.button.history').click(function() {
140 PMA_consoleMessages.showHistory();
143 $('#pma_console').find('.button.options').click(function() {
144 PMA_console.showCard('#pma_console_options');
147 $('#pma_console').find('.button.debug').click(function() {
148 PMA_console.showCard('#debug_console');
151 PMA_console.$consoleContent.click(function(event) {
152 if (event.target == this) {
153 PMA_consoleInput.focus();
157 $('#pma_console').find('.mid_layer').click(function() {
158 PMA_console.hideCard($(this).parent().children('.card'));
160 $('#debug_console').find('.switch_button').click(function() {
161 PMA_console.hideCard($(this).closest('.card'));
163 $('#pma_bookmarks').find('.switch_button').click(function() {
164 PMA_console.hideCard($(this).closest('.card'));
166 $('#pma_console_options').find('.switch_button').click(function() {
167 PMA_console.hideCard($(this).closest('.card'));
170 $('#pma_console_options').find('input[type=checkbox]').change(function() {
171 PMA_console.updateConfig();
174 $('#pma_console_options').find('.button.default').click(function() {
175 $('#pma_console_options input[name=always_expand]').prop('checked', false);
176 $('#pma_console_options').find('input[name=start_history]').prop('checked', false);
177 $('#pma_console_options').find('input[name=current_query]').prop('checked', true);
178 $('#pma_console_options').find('input[name=enter_executes]').prop('checked', false);
179 $('#pma_console_options').find('input[name=dark_theme]').prop('checked', false);
180 PMA_console.updateConfig();
183 $('#pma_console_options').find('input[name=enter_executes]').change(function() {
184 PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
187 $(document).ajaxComplete(function (event, xhr, ajaxOptions) {
188 if (ajaxOptions.dataType && ajaxOptions.dataType.indexOf('json') != -1) {
191 if (xhr.status !== 200) {
195 var data = JSON.parse(xhr.responseText);
196 PMA_console.ajaxCallback(data);
199 console.log("Failed to parse JSON: " + e.message);
203 PMA_console.isInitialized = true;
206 // Change console mode from cookie
207 switch(Cookies.get('pma_console_mode')) {
209 PMA_console.collapse();
211 /* jshint -W086 */// no break needed in default section
213 Cookies.set('pma_console_mode', 'info');
219 PMA_console.show(true);
220 PMA_console.scrollBottom();
225 * Execute query and show results in console
229 execute: function(queryString, options) {
230 if (typeof(queryString) != 'string' || ! /[a-z]|[A-Z]/.test(queryString)) {
233 PMA_console.$requestForm.children('textarea').val(queryString);
234 PMA_console.$requestForm.children('[name=server]').attr('value', PMA_commonParams.get('server'));
235 if (options && options.db) {
236 PMA_console.$requestForm.children('[name=db]').val(options.db);
238 PMA_console.$requestForm.children('[name=table]').val(options.table);
240 PMA_console.$requestForm.children('[name=table]').val('');
243 PMA_console.$requestForm.children('[name=db]').val(
244 (PMA_commonParams.get('db').length > 0 ? PMA_commonParams.get('db') : ''));
246 PMA_console.$requestForm.find('[name=profiling]').remove();
247 if (options && options.profiling === true) {
248 PMA_console.$requestForm.append('<input name="profiling" value="on">');
250 if (! confirmQuery(PMA_console.$requestForm[0], PMA_console.$requestForm.children('textarea')[0].value)) {
253 PMA_console.$requestForm.children('[name=console_message_id]')
254 .val(PMA_consoleMessages.appendQuery({sql_query: queryString}).message_id);
255 PMA_console.$requestForm.trigger('submit');
256 PMA_consoleInput.clear();
257 PMA_reloadNavigation();
259 ajaxCallback: function(data) {
260 if (data && data.console_message_id) {
261 PMA_consoleMessages.updateQuery(data.console_message_id, data.success,
262 (data._reloadQuerywindow ? data._reloadQuerywindow : false));
263 } else if ( data && data._reloadQuerywindow) {
264 if (data._reloadQuerywindow.sql_query.length > 0) {
265 PMA_consoleMessages.appendQuery(data._reloadQuerywindow, 'successed')
266 .$message.addClass(PMA_console.config.currentQuery ? '' : 'hide');
271 * Change console to collapse mode
275 collapse: function() {
276 Cookies.set('pma_console_mode', 'collapse');
277 var pmaConsoleHeight = Cookies.get('pma_console_height');
279 if (pmaConsoleHeight < 32) {
280 Cookies.set('pma_console_height', 92);
282 PMA_console.$consoleToolbar.addClass('collapsed');
283 PMA_console.$consoleAllContents.height(pmaConsoleHeight);
284 PMA_console.$consoleContent.stop();
285 PMA_console.$consoleContent.animate({'margin-bottom': -1 * PMA_console.$consoleContent.outerHeight() + 'px'},
286 'fast', 'easeOutQuart', function() {
287 PMA_console.$consoleContent.css({display:'none'});
288 $(window).trigger('resize');
290 PMA_console.hideCard();
295 * @param bool inputFocus If true, focus the input line after show()
298 show: function(inputFocus) {
299 Cookies.set('pma_console_mode', 'show');
301 var pmaConsoleHeight = Cookies.get('pma_console_height');
303 if (pmaConsoleHeight < 32) {
304 Cookies.set('pma_console_height', 32);
305 PMA_console.collapse();
308 PMA_console.$consoleContent.css({display:'block'});
309 if (PMA_console.$consoleToolbar.hasClass('collapsed')) {
310 PMA_console.$consoleToolbar.removeClass('collapsed');
312 PMA_console.$consoleAllContents.height(pmaConsoleHeight);
313 PMA_console.$consoleContent.stop();
314 PMA_console.$consoleContent.animate({'margin-bottom': 0},
315 'fast', 'easeOutQuart', function() {
316 $(window).trigger('resize');
318 PMA_consoleInput.focus();
323 * Change console to SQL information mode
324 * this mode shows current SQL query
325 * This mode is the default mode
330 // Under construction
331 PMA_console.collapse();
334 * Toggle console mode between collapse/show
335 * Used for toggle buttons and shortcuts
340 switch(Cookies.get('pma_console_mode')) {
343 PMA_console.show(true);
346 PMA_console.collapse();
349 PMA_consoleInitialize();
353 * Scroll console to bottom
357 scrollBottom: function() {
358 PMA_console.$consoleContent.scrollTop(PMA_console.$consoleContent.prop("scrollHeight"));
363 * @param string cardSelector Selector, select string will be "#pma_console " + cardSelector
364 * this param also can be JQuery object, if you need.
368 showCard: function(cardSelector) {
370 if (typeof(cardSelector) !== 'string') {
371 if (cardSelector.length > 0) {
372 $card = cardSelector;
377 $card = $("#pma_console " + cardSelector);
379 if ($card.length === 0) {
382 $card.parent().children('.mid_layer').show().fadeTo(0, 0.15);
383 $card.addClass('show');
384 PMA_consoleInput.blur();
385 if ($card.parents('.card').length > 0) {
386 PMA_console.showCard($card.parents('.card'));
390 * Scroll console to bottom
392 * @param object $targetCard Target card JQuery object, if it's empty, function will hide all cards
395 hideCard: function($targetCard) {
397 $('#pma_console').find('.mid_layer').fadeOut(140);
398 $('#pma_console').find('.card').removeClass('show');
399 } else if ($targetCard.length > 0) {
400 $targetCard.parent().find('.mid_layer').fadeOut(140);
401 $targetCard.find('.card').removeClass('show');
402 $targetCard.removeClass('show');
406 * Used for update console config
410 updateConfig: function() {
411 PMA_console.config = {
412 alwaysExpand: $('#pma_console_options input[name=always_expand]').prop('checked'),
413 startHistory: $('#pma_console_options').find('input[name=start_history]').prop('checked'),
414 currentQuery: $('#pma_console_options').find('input[name=current_query]').prop('checked'),
415 enterExecutes: $('#pma_console_options').find('input[name=enter_executes]').prop('checked'),
416 darkTheme: $('#pma_console_options').find('input[name=dark_theme]').prop('checked')
418 Cookies.set('pma_console_config', PMA_console.config);
419 /*Setting the dark theme of the console*/
420 if (PMA_console.config.darkTheme) {
421 $('#pma_console').find('>.content').addClass('console_dark_theme');
423 $('#pma_console').find('>.content').removeClass('console_dark_theme');
426 isSelect: function (queryString) {
427 var reg_exp = /^SELECT\s+/i;
428 return reg_exp.test(queryString);
434 * Careful: this object UI logics highly related with functions under PMA_console
435 * Resizing min-height is 32, if small than it, console will collapse
437 var PMA_consoleResizer = {
442 * Mousedown event handler for bind to resizer
446 _mousedown: function(event) {
447 if (Cookies.get('pma_console_mode') !== 'show') {
450 PMA_consoleResizer._posY = event.pageY;
451 PMA_consoleResizer._height = PMA_console.$consoleContent.height();
452 $(document).mousemove(PMA_consoleResizer._mousemove);
453 $(document).mouseup(PMA_consoleResizer._mouseup);
454 // Disable text selection while resizing
455 $(document).on('selectstart', function() { return false; });
458 * Mousemove event handler for bind to resizer
462 _mousemove: function(event) {
463 if (event.pageY < 35) {
466 PMA_consoleResizer._resultHeight = PMA_consoleResizer._height + (PMA_consoleResizer._posY -event.pageY);
467 // Content min-height is 32, if adjusting height small than it we'll move it out of the page
468 if (PMA_consoleResizer._resultHeight <= 32) {
469 PMA_console.$consoleAllContents.height(32);
470 PMA_console.$consoleContent.css('margin-bottom', PMA_consoleResizer._resultHeight - 32);
473 // Logic below makes viewable area always at bottom when adjusting height and content already at bottom
474 if (PMA_console.$consoleContent.scrollTop() + PMA_console.$consoleContent.innerHeight() + 16
475 >= PMA_console.$consoleContent.prop('scrollHeight')) {
476 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
477 PMA_console.scrollBottom();
479 PMA_console.$consoleAllContents.height(PMA_consoleResizer._resultHeight);
484 * Mouseup event handler for bind to resizer
488 _mouseup: function() {
489 Cookies.set('pma_console_height', PMA_consoleResizer._resultHeight);
491 $(document).off('mousemove');
492 $(document).off('mouseup');
493 $(document).off('selectstart');
496 * Used for console resizer initialize
500 initialize: function() {
501 $('#pma_console').find('.toolbar').off('mousedown');
502 $('#pma_console').find('.toolbar').mousedown(PMA_consoleResizer._mousedown);
508 * Console input object
510 var PMA_consoleInput = {
512 * @var array, contains Codemirror objects or input jQuery objects
517 * @var bool, if codemirror enabled
522 * @var int, count for history navigation, 0 for current input
527 * @var string, current input when navigating through history
530 _historyPreserveCurrent: null,
532 * Used for console input initialize
536 initialize: function() {
537 // _cm object can't be reinitialize
538 if (PMA_consoleInput._inputs !== null) {
541 if (typeof CodeMirror !== 'undefined') {
542 PMA_consoleInput._codemirror = true;
544 PMA_consoleInput._inputs = [];
545 if (PMA_consoleInput._codemirror) {
546 PMA_consoleInput._inputs.console = CodeMirror($('#pma_console').find('.console_query_input')[0], {
550 extraKeys: {"Ctrl-Space": "autocomplete"},
551 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
552 gutters: ["CodeMirror-lint-markers"],
554 "getAnnotations": CodeMirror.sqlLint,
558 PMA_consoleInput._inputs.console.on("inputRead", codemirrorAutocompleteOnInputRead);
559 PMA_consoleInput._inputs.console.on("keydown", function(instance, event) {
560 PMA_consoleInput._historyNavigate(event);
562 if ($('#pma_bookmarks').length !== 0) {
563 PMA_consoleInput._inputs.bookmark = CodeMirror($('#pma_console').find('.bookmark_add_input')[0], {
567 extraKeys: {"Ctrl-Space": "autocomplete"},
568 hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
569 gutters: ["CodeMirror-lint-markers"],
571 "getAnnotations": CodeMirror.sqlLint,
575 PMA_consoleInput._inputs.bookmark.on("inputRead", codemirrorAutocompleteOnInputRead);
578 PMA_consoleInput._inputs.console =
579 $('<textarea>').appendTo('#pma_console .console_query_input')
580 .on('keydown', PMA_consoleInput._historyNavigate);
581 if ($('#pma_bookmarks').length !== 0) {
582 PMA_consoleInput._inputs.bookmark =
583 $('<textarea>').appendTo('#pma_console .bookmark_add_input');
586 $('#pma_console').find('.console_query_input').keydown(PMA_consoleInput._keydown);
588 _historyNavigate: function(event) {
589 if (event.keyCode == 38 || event.keyCode == 40) {
590 var upPermitted = false;
591 var downPermitted = false;
592 var editor = PMA_consoleInput._inputs.console;
595 if (PMA_consoleInput._codemirror) {
596 cursorLine = editor.getCursor().line;
597 totalLine = editor.lineCount();
599 // Get cursor position from textarea
600 var text = PMA_consoleInput.getText();
601 cursorLine = text.substr(0, editor.prop("selectionStart")).split("\n").length - 1;
602 totalLine = text.split(/\r*\n/).length;
604 if (cursorLine === 0) {
607 if (cursorLine == totalLine - 1) {
608 downPermitted = true;
611 var queryString = false;
612 if (upPermitted && event.keyCode == 38) {
613 // Navigate up in history
614 if (PMA_consoleInput._historyCount === 0) {
615 PMA_consoleInput._historyPreserveCurrent = PMA_consoleInput.getText();
617 nextCount = PMA_consoleInput._historyCount + 1;
618 queryString = PMA_consoleMessages.getHistory(nextCount);
619 } else if (downPermitted && event.keyCode == 40) {
620 // Navigate down in history
621 if (PMA_consoleInput._historyCount === 0) {
624 nextCount = PMA_consoleInput._historyCount - 1;
625 if (nextCount === 0) {
626 queryString = PMA_consoleInput._historyPreserveCurrent;
628 queryString = PMA_consoleMessages.getHistory(nextCount);
631 if (queryString !== false) {
632 PMA_consoleInput._historyCount = nextCount;
633 PMA_consoleInput.setText(queryString, 'console');
634 if (PMA_consoleInput._codemirror) {
635 editor.setCursor(editor.lineCount(), 0);
637 event.preventDefault();
642 * Mousedown event handler for bind to input
643 * Shortcut is Ctrl+Enter key or just ENTER, depending on console's
648 _keydown: function(event) {
649 if (PMA_console.config.enterExecutes) {
650 // Enter, but not in combination with Shift (which writes a new line).
651 if (!event.shiftKey && event.keyCode === 13) {
652 PMA_consoleInput.execute();
656 if (event.ctrlKey && event.keyCode === 13) {
657 PMA_consoleInput.execute();
662 * Used for send text to PMA_console.execute()
666 execute: function() {
667 if (PMA_consoleInput._codemirror) {
668 PMA_console.execute(PMA_consoleInput._inputs.console.getValue());
670 PMA_console.execute(PMA_consoleInput._inputs.console.val());
674 * Used for clear the input
676 * @param string target, default target is console input
679 clear: function(target) {
680 PMA_consoleInput.setText('', target);
683 * Used for set focus to input
688 PMA_consoleInput._inputs.console.focus();
691 * Used for blur input
696 if (PMA_consoleInput._codemirror) {
697 PMA_consoleInput._inputs.console.getInputField().blur();
699 PMA_consoleInput._inputs.console.blur();
703 * Used for set text in input
706 * @param string target
709 setText: function(text, target) {
710 if (PMA_consoleInput._codemirror) {
713 PMA_console.execute(PMA_consoleInput._inputs.bookmark.setValue(text));
717 PMA_console.execute(PMA_consoleInput._inputs.console.setValue(text));
722 PMA_console.execute(PMA_consoleInput._inputs.bookmark.val(text));
726 PMA_console.execute(PMA_consoleInput._inputs.console.val(text));
730 getText: function(target) {
731 if (PMA_consoleInput._codemirror) {
734 return PMA_consoleInput._inputs.bookmark.getValue();
737 return PMA_consoleInput._inputs.console.getValue();
742 return PMA_consoleInput._inputs.bookmark.val();
745 return PMA_consoleInput._inputs.console.val();
754 * Console messages, and message items management object
756 var PMA_consoleMessages = {
758 * Used for clear the messages
763 $('#pma_console').find('.content .console_message_container .message:not(.welcome)').addClass('hide');
764 $('#pma_console').find('.content .console_message_container .message.failed').remove();
765 $('#pma_console').find('.content .console_message_container .message.expanded').find('.action.collapse').click();
768 * Used for show history messages
772 showHistory: function() {
773 $('#pma_console').find('.content .console_message_container .message.hide').removeClass('hide');
776 * Used for getting a perticular history query
778 * @param int nthLast get nth query message from latest, i.e 1st is last
779 * @return string message
781 getHistory: function(nthLast) {
782 var $queries = $('#pma_console').find('.content .console_message_container .query');
783 var length = $queries.length;
784 var $query = $queries.eq(length - nthLast);
785 if (!$query || (length - nthLast) < 0) {
788 return $query.text();
792 * Used to show the correct message depending on which key
793 * combination executes the query (Ctrl+Enter or Enter).
795 * @param bool enterExecutes Only Enter has to be pressed to execute query.
798 showInstructions: function(enterExecutes) {
799 enterExecutes = +enterExecutes || 0; // conversion to int
800 var $welcomeMsg = $('#pma_console').find('.content .console_message_container .message.welcome span');
801 $welcomeMsg.children('[id^=instructions]').hide();
802 $welcomeMsg.children('#instructions-' + enterExecutes).show();
805 * Used for log new message
807 * @param string msgString Message to show
808 * @param string msgType Message type
809 * @return object, {message_id, $message}
811 append: function(msgString, msgType) {
812 if (typeof(msgString) !== 'string') {
815 // Generate an ID for each message, we can find them later
816 var msgId = Math.round(Math.random()*(899999999999)+100000000000);
817 var now = new Date();
819 $('<div class="message ' +
820 (PMA_console.config.alwaysExpand ? 'expanded' : 'collapsed') +
821 '" msgid="' + msgId + '"><div class="action_content"></div></div>');
824 $newMessage.append('<div class="query highlighted"></div>');
825 if (PMA_consoleInput._codemirror) {
826 CodeMirror.runMode(msgString,
827 'text/x-sql', $newMessage.children('.query')[0]);
829 $newMessage.children('.query').text(msgString);
831 $newMessage.children('.action_content')
832 .append(PMA_console.$consoleTemplates.children('.query_actions').html());
836 $newMessage.append('<div>' + msgString + '</div>');
838 PMA_consoleMessages._msgEventBinds($newMessage);
839 $newMessage.find('span.text.query_time span')
840 .text(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds())
841 .parent().attr('title', now);
842 return {message_id: msgId,
843 $message: $newMessage.appendTo('#pma_console .content .console_message_container')};
846 * Used for log new query
848 * @param string queryData Struct should be
849 * {sql_query: "Query string", db: "Target DB", table: "Target Table"}
850 * @param string state Message state
851 * @return object, {message_id: string message id, $message: JQuery object}
853 appendQuery: function(queryData, state) {
854 var targetMessage = PMA_consoleMessages.append(queryData.sql_query, 'query');
855 if (! targetMessage) {
858 if (queryData.db && queryData.table) {
859 targetMessage.$message.attr('targetdb', queryData.db);
860 targetMessage.$message.attr('targettable', queryData.table);
861 targetMessage.$message.find('.text.targetdb span').text(queryData.db);
863 if (PMA_console.isSelect(queryData.sql_query)) {
864 targetMessage.$message.addClass('select');
868 targetMessage.$message.addClass('failed');
871 targetMessage.$message.addClass('successed');
875 targetMessage.$message.addClass('pending');
877 return targetMessage;
879 _msgEventBinds: function($targetMessage) {
880 // Leave unbinded elements, remove binded.
881 $targetMessage = $targetMessage.filter(':not(.binded)');
882 if ($targetMessage.length === 0) {
885 $targetMessage.addClass('binded');
887 $targetMessage.find('.action.expand').click(function () {
888 $(this).closest('.message').removeClass('collapsed');
889 $(this).closest('.message').addClass('expanded');
891 $targetMessage.find('.action.collapse').click(function () {
892 $(this).closest('.message').addClass('collapsed');
893 $(this).closest('.message').removeClass('expanded');
895 $targetMessage.find('.action.edit').click(function () {
896 PMA_consoleInput.setText($(this).parent().siblings('.query').text());
897 PMA_consoleInput.focus();
899 $targetMessage.find('.action.requery').click(function () {
900 var query = $(this).parent().siblings('.query').text();
901 var $message = $(this).closest('.message');
902 if (confirm(PMA_messages.strConsoleRequeryConfirm + '\n' +
903 (query.length<100 ? query : query.slice(0, 100) + '...'))
905 PMA_console.execute(query, {db: $message.attr('targetdb'), table: $message.attr('targettable')});
908 $targetMessage.find('.action.bookmark').click(function () {
909 var query = $(this).parent().siblings('.query').text();
910 var $message = $(this).closest('.message');
911 PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'));
912 PMA_console.showCard('#pma_bookmarks .card.add');
914 $targetMessage.find('.action.edit_bookmark').click(function () {
915 var query = $(this).parent().siblings('.query').text();
916 var $message = $(this).closest('.message');
917 var isShared = $message.find('span.bookmark_label').hasClass('shared');
918 var label = $message.find('span.bookmark_label').text();
919 PMA_consoleBookmarks.addBookmark(query, $message.attr('targetdb'), label, isShared);
920 PMA_console.showCard('#pma_bookmarks .card.add');
922 $targetMessage.find('.action.delete_bookmark').click(function () {
923 var $message = $(this).closest('.message');
924 if (confirm(PMA_messages.strConsoleDeleteBookmarkConfirm + '\n' + $message.find('.bookmark_label').text())) {
927 server: PMA_commonParams.get('server'),
930 id_bookmark: $message.attr('bookmarkid')},
932 PMA_consoleBookmarks.refresh();
936 $targetMessage.find('.action.profiling').click(function () {
937 var $message = $(this).closest('.message');
938 PMA_console.execute($(this).parent().siblings('.query').text(),
939 {db: $message.attr('targetdb'),
940 table: $message.attr('targettable'),
943 $targetMessage.find('.action.explain').click(function () {
944 var $message = $(this).closest('.message');
945 PMA_console.execute('EXPLAIN ' + $(this).parent().siblings('.query').text(),
946 {db: $message.attr('targetdb'),
947 table: $message.attr('targettable')});
949 $targetMessage.find('.action.dbg_show_trace').click(function () {
950 var $message = $(this).closest('.message');
951 if (!$message.find('.trace').length) {
952 PMA_consoleDebug.getQueryDetails(
953 $message.data('queryInfo'),
954 $message.data('totalTime'),
957 PMA_consoleMessages._msgEventBinds($message.find('.message:not(.binded)'));
959 $message.addClass('show_trace');
960 $message.removeClass('hide_trace');
962 $targetMessage.find('.action.dbg_hide_trace').click(function () {
963 var $message = $(this).closest('.message');
964 $message.addClass('hide_trace');
965 $message.removeClass('show_trace');
967 $targetMessage.find('.action.dbg_show_args').click(function () {
968 var $message = $(this).closest('.message');
969 $message.addClass('show_args expanded');
970 $message.removeClass('hide_args collapsed');
972 $targetMessage.find('.action.dbg_hide_args').click(function () {
973 var $message = $(this).closest('.message');
974 $message.addClass('hide_args collapsed');
975 $message.removeClass('show_args expanded');
977 if (PMA_consoleInput._codemirror) {
978 $targetMessage.find('.query:not(.highlighted)').each(function(index, elem) {
979 CodeMirror.runMode($(elem).text(),
981 $(this).addClass('highlighted');
985 msgAppend: function(msgId, msgString, msgType) {
986 var $targetMessage = $('#pma_console').find('.content .console_message_container .message[msgid=' + msgId +']');
987 if ($targetMessage.length === 0 || isNaN(parseInt(msgId)) || typeof(msgString) !== 'string') {
990 $targetMessage.append('<div>' + msgString + '</div>');
992 updateQuery: function(msgId, isSuccessed, queryData) {
993 var $targetMessage = $('#pma_console').find('.console_message_container .message[msgid=' + parseInt(msgId) +']');
994 if ($targetMessage.length === 0 || isNaN(parseInt(msgId))) {
997 $targetMessage.removeClass('pending failed successed');
999 $targetMessage.addClass('successed');
1001 $targetMessage.children('.query').text('');
1002 $targetMessage.removeClass('select');
1003 if (PMA_console.isSelect(queryData.sql_query)) {
1004 $targetMessage.addClass('select');
1006 if (PMA_consoleInput._codemirror) {
1007 CodeMirror.runMode(queryData.sql_query, 'text/x-sql', $targetMessage.children('.query')[0]);
1009 $targetMessage.children('.query').text(queryData.sql_query);
1011 $targetMessage.attr('targetdb', queryData.db);
1012 $targetMessage.attr('targettable', queryData.table);
1013 $targetMessage.find('.text.targetdb span').text(queryData.db);
1016 $targetMessage.addClass('failed');
1020 * Used for console messages initialize
1024 initialize: function() {
1025 PMA_consoleMessages._msgEventBinds($('#pma_console').find('.message:not(.binded)'));
1026 if (PMA_console.config.startHistory) {
1027 PMA_consoleMessages.showHistory();
1029 PMA_consoleMessages.showInstructions(PMA_console.config.enterExecutes);
1035 * Console bookmarks card, and bookmarks items management object
1037 var PMA_consoleBookmarks = {
1039 addBookmark: function (queryString, targetDb, label, isShared, id) {
1040 $('#pma_bookmarks').find('.add [name=shared]').prop('checked', false);
1041 $('#pma_bookmarks').find('.add [name=label]').val('');
1042 $('#pma_bookmarks').find('.add [name=targetdb]').val('');
1043 $('#pma_bookmarks').find('.add [name=id_bookmark]').val('');
1044 PMA_consoleInput.setText('', 'bookmark');
1046 switch(arguments.length) {
1048 $('#pma_bookmarks').find('.add [name=shared]').prop('checked', isShared);
1050 $('#pma_bookmarks').find('.add [name=label]').val(label);
1052 $('#pma_bookmarks').find('.add [name=targetdb]').val(targetDb);
1054 PMA_consoleInput.setText(queryString, 'bookmark');
1059 refresh: function () {
1061 {ajax_request: true,
1062 server: PMA_commonParams.get('server'),
1063 console_bookmark_refresh: 'refresh'},
1065 if (data.console_message_bookmark) {
1066 $('#pma_bookmarks').find('.content.bookmark').html(data.console_message_bookmark);
1067 PMA_consoleMessages._msgEventBinds($('#pma_bookmarks').find('.message:not(.binded)'));
1072 * Used for console bookmarks initialize
1073 * message events are already binded by PMA_consoleMsg._msgEventBinds
1077 initialize: function() {
1078 if ($('#pma_bookmarks').length === 0) {
1081 $('#pma_console').find('.button.bookmarks').click(function() {
1082 PMA_console.showCard('#pma_bookmarks');
1084 $('#pma_bookmarks').find('.button.add').click(function() {
1085 PMA_console.showCard('#pma_bookmarks .card.add');
1087 $('#pma_bookmarks').find('.card.add [name=submit]').click(function () {
1088 if ($('#pma_bookmarks').find('.card.add [name=label]').val().length === 0
1089 || PMA_consoleInput.getText('bookmark').length === 0)
1091 alert(PMA_messages.strFormEmpty);
1094 $(this).prop('disabled', true);
1095 $.post('import.php',
1098 console_bookmark_add: 'true',
1099 label: $('#pma_bookmarks').find('.card.add [name=label]').val(),
1100 server: PMA_commonParams.get('server'),
1101 db: $('#pma_bookmarks').find('.card.add [name=targetdb]').val(),
1102 bookmark_query: PMA_consoleInput.getText('bookmark'),
1103 shared: $('#pma_bookmarks').find('.card.add [name=shared]').prop('checked')},
1105 PMA_consoleBookmarks.refresh();
1106 $('#pma_bookmarks').find('.card.add [name=submit]').prop('disabled', false);
1107 PMA_console.hideCard($('#pma_bookmarks').find('.card.add'));
1110 $('#pma_console').find('.button.refresh').click(function() {
1111 PMA_consoleBookmarks.refresh();
1116 var PMA_consoleDebug;
1117 PMA_consoleDebug = {
1119 groupQueries: false,
1120 orderBy: 'exec', // Possible 'exec' => Execution order, 'time' => Time taken, 'count'
1121 order: 'asc' // Possible 'asc', 'desc'
1127 initialize: function () {
1128 // Try to get debug info after every AJAX request
1129 $(document).ajaxSuccess(function (event, xhr, settings, data) {
1131 PMA_consoleDebug.showLog(data._debug, settings.url);
1135 // Initialize config
1138 if (this.configParam('groupQueries')) {
1139 $('#debug_console').addClass('grouped');
1141 $('#debug_console').addClass('ungrouped');
1142 if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1143 $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
1146 var orderBy = this.configParam('orderBy');
1147 var order = this.configParam('order');
1148 $('#debug_console').find('.button.order_by.sort_' + orderBy).addClass('active');
1149 $('#debug_console').find('.button.order.order_' + order).addClass('active');
1151 // Initialize actions in toolbar
1152 $('#debug_console').find('.button.group_queries').click(function () {
1153 $('#debug_console').addClass('grouped');
1154 $('#debug_console').removeClass('ungrouped');
1155 PMA_consoleDebug.configParam('groupQueries', true);
1156 PMA_consoleDebug.refresh();
1157 if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1158 $('#debug_console').find('.button.order_by.sort_exec').removeClass('active');
1161 $('#debug_console').find('.button.ungroup_queries').click(function () {
1162 $('#debug_console').addClass('ungrouped');
1163 $('#debug_console').removeClass('grouped');
1164 PMA_consoleDebug.configParam('groupQueries', false);
1165 PMA_consoleDebug.refresh();
1166 if (PMA_consoleDebug.configParam('orderBy') == 'count') {
1167 $('#debug_console').find('.button.order_by.sort_exec').addClass('active');
1170 $('#debug_console').find('.button.order_by').click(function () {
1171 var $this = $(this);
1172 $('#debug_console').find('.button.order_by').removeClass('active');
1173 $this.addClass('active');
1174 if ($this.hasClass('sort_time')) {
1175 PMA_consoleDebug.configParam('orderBy', 'time');
1176 } else if ($this.hasClass('sort_exec')) {
1177 PMA_consoleDebug.configParam('orderBy', 'exec');
1178 } else if ($this.hasClass('sort_count')) {
1179 PMA_consoleDebug.configParam('orderBy', 'count');
1181 PMA_consoleDebug.refresh();
1183 $('#debug_console').find('.button.order').click(function () {
1184 var $this = $(this);
1185 $('#debug_console').find('.button.order').removeClass('active');
1186 $this.addClass('active');
1187 if ($this.hasClass('order_asc')) {
1188 PMA_consoleDebug.configParam('order', 'asc');
1189 } else if ($this.hasClass('order_desc')) {
1190 PMA_consoleDebug.configParam('order', 'desc');
1192 PMA_consoleDebug.refresh();
1195 // Show SQL debug info for first page load
1196 if (typeof debugSQLInfo !== 'undefined' && debugSQLInfo !== 'null') {
1197 $('#pma_console').find('.button.debug').removeClass('hide');
1202 PMA_consoleDebug.showLog(debugSQLInfo);
1204 _initConfig: function () {
1205 var config = Cookies.getJSON('pma_console_dbg_config');
1207 for (var name in config) {
1208 if (config.hasOwnProperty(name)) {
1209 this._config[name] = config[name];
1214 configParam: function (name, value) {
1215 if (typeof value === 'undefined') {
1216 return this._config[name];
1218 this._config[name] = value;
1219 Cookies.set('pma_console_dbg_config', this._config);
1222 _formatFunctionCall: function (dbgStep) {
1223 var functionName = '';
1224 if ('class' in dbgStep) {
1225 functionName += dbgStep.class;
1226 functionName += dbgStep.type;
1228 functionName += dbgStep.function;
1229 if (dbgStep.args && dbgStep.args.length) {
1230 functionName += '(...)';
1232 functionName += '()';
1234 return functionName;
1236 _formatFunctionArgs: function (dbgStep) {
1237 var $args = $('<div>');
1238 if (dbgStep.args.length) {
1239 $args.append('<div class="message welcome">')
1241 $('<div class="message welcome">')
1244 PMA_messages.strConsoleDebugArgsSummary,
1249 for (var i = 0; i < dbgStep.args.length; i++) {
1251 $('<div class="message">')
1254 escapeHtml(JSON.stringify(dbgStep.args[i], null, " ")) +
1262 _formatFileName: function (dbgStep) {
1264 if ('file' in dbgStep) {
1265 fileName += dbgStep.file;
1266 fileName += '#' + dbgStep.line;
1270 _formatBackTrace: function (dbgTrace) {
1271 var $traceElem = $('<div class="trace">');
1273 $('<div class="message welcome">')
1275 var step, $stepElem;
1276 for (var stepId in dbgTrace) {
1277 if (dbgTrace.hasOwnProperty(stepId)) {
1278 step = dbgTrace[stepId];
1279 if (!Array.isArray(step) && typeof step !== 'object') {
1281 $('<div class="message traceStep collapsed hide_args">')
1283 $('<span>').text(step)
1286 if (typeof step.args === 'string' && step.args) {
1287 step.args = [step.args];
1290 $('<div class="message traceStep collapsed hide_args">')
1292 $('<span class="function">').text(this._formatFunctionCall(step))
1295 $('<span class="file">').text(this._formatFileName(step))
1297 if (step.args && step.args.length) {
1300 $('<span class="args">').html(this._formatFunctionArgs(step))
1303 $('<div class="action_content">')
1305 '<span class="action dbg_show_args">' +
1306 PMA_messages.strConsoleDebugShowArgs +
1310 '<span class="action dbg_hide_args">' +
1311 PMA_messages.strConsoleDebugHideArgs +
1317 $traceElem.append($stepElem);
1322 _formatQueryOrGroup: function (queryInfo, totalTime) {
1323 var grouped, queryText, queryTime, count, i;
1324 if (Array.isArray(queryInfo)) {
1328 queryText = queryInfo[0].query;
1331 for (i in queryInfo) {
1332 queryTime += queryInfo[i].time;
1335 count = queryInfo.length;
1337 queryText = queryInfo.query;
1338 queryTime = queryInfo.time;
1341 var $query = $('<div class="message collapsed hide_trace">')
1343 $('#debug_console').find('.templates .debug_query').clone()
1346 $('<div class="query">')
1349 .data('queryInfo', queryInfo)
1350 .data('totalTime', totalTime);
1352 $query.find('.text.count').removeClass('hide');
1353 $query.find('.text.count span').text(count);
1355 $query.find('.text.time span').text(queryTime + 's (' + ((queryTime * 100) / totalTime).toFixed(3) + '%)');
1359 _appendQueryExtraInfo: function (query, $elem) {
1360 if ('error' in query) {
1362 $('<div>').html(query.error)
1365 $elem.append(this._formatBackTrace(query.trace));
1367 getQueryDetails: function (queryInfo, totalTime, $query) {
1368 if (Array.isArray(queryInfo)) {
1370 for (var i in queryInfo) {
1371 $singleQuery = $('<div class="message welcome trace">')
1372 .text((parseInt(i) + 1) + '.')
1374 $('<span class="time">').text(
1375 PMA_messages.strConsoleDebugTimeTaken +
1376 ' ' + queryInfo[i].time + 's' +
1377 ' (' + ((queryInfo[i].time * 100) / totalTime).toFixed(3) + '%)'
1380 this._appendQueryExtraInfo(queryInfo[i], $singleQuery);
1382 .append('<div class="message welcome trace">')
1383 .append($singleQuery);
1386 this._appendQueryExtraInfo(queryInfo, $query);
1389 showLog: function (debugInfo, url) {
1390 this._lastDebugInfo.debugInfo = debugInfo;
1391 this._lastDebugInfo.url = url;
1393 $('#debug_console').find('.debugLog').empty();
1394 $("#debug_console").find(".debug>.welcome").empty();
1396 var debugJson = false, i;
1397 if (typeof debugInfo === "object" && 'queries' in debugInfo) {
1398 // Copy it to debugJson, so that it doesn't get changed
1399 if (!('queries' in debugInfo)) {
1402 debugJson = {queries: []};
1403 for (i in debugInfo.queries) {
1404 debugJson.queries[i] = debugInfo.queries[i];
1407 } else if (typeof debugInfo === "string") {
1409 debugJson = JSON.parse(debugInfo);
1413 if (debugJson && !('queries' in debugJson)) {
1417 if (debugJson === false) {
1418 $("#debug_console").find(".debug>.welcome").text(
1419 PMA_messages.strConsoleDebugError
1423 var allQueries = debugJson.queries;
1424 var uniqueQueries = {};
1426 var totalExec = allQueries.length;
1428 // Calculate total time and make unique query array
1430 for (i = 0; i < totalExec; ++i) {
1431 totalTime += allQueries[i].time;
1432 if (!(allQueries[i].hash in uniqueQueries)) {
1433 uniqueQueries[allQueries[i].hash] = [];
1435 uniqueQueries[allQueries[i].hash].push(allQueries[i]);
1437 // Count total unique queries, convert uniqueQueries to Array
1438 var totalUnique = 0, uniqueArray = [];
1439 for (var hash in uniqueQueries) {
1440 if (uniqueQueries.hasOwnProperty(hash)) {
1442 uniqueArray.push(uniqueQueries[hash]);
1445 uniqueQueries = uniqueArray;
1447 $("#debug_console").find(".debug>.welcome").append(
1448 $('<span class="debug_summary">').text(
1450 PMA_messages.strConsoleDebugSummary,
1458 $("#debug_console").find(".debug>.welcome").append(
1459 $('<span class="script_name">').text(url.split('?')[0])
1463 // For sorting queries
1464 function sortByTime(a, b) {
1465 var order = ((PMA_consoleDebug.configParam('order') == 'asc') ? 1 : -1);
1466 if (Array.isArray(a) && Array.isArray(b)) {
1468 var timeA = 0, timeB = 0, i;
1475 return (timeA - timeB) * order;
1477 return (a.time - b.time) * order;
1481 function sortByCount(a, b) {
1482 var order = ((PMA_consoleDebug.configParam('order') == 'asc') ? 1 : -1);
1483 return (a.length - b.length) * order;
1486 var orderBy = this.configParam('orderBy');
1487 var order = PMA_consoleDebug.configParam('order');
1489 if (this.configParam('groupQueries')) {
1491 if (orderBy == 'time') {
1492 uniqueQueries.sort(sortByTime);
1493 } else if (orderBy == 'count') {
1494 uniqueQueries.sort(sortByCount);
1495 } else if (orderBy == 'exec' && order == 'desc') {
1496 uniqueQueries.reverse();
1498 for (i in uniqueQueries) {
1499 if (orderBy == 'time') {
1500 uniqueQueries[i].sort(sortByTime);
1501 } else if (orderBy == 'exec' && order == 'desc') {
1502 uniqueQueries[i].reverse();
1504 $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(uniqueQueries[i], totalTime));
1507 if (orderBy == 'time') {
1508 allQueries.sort(sortByTime);
1509 } else if (order == 'desc') {
1510 allQueries.reverse();
1512 for (i = 0; i < totalExec; ++i) {
1513 $('#debug_console').find('.debugLog').append(this._formatQueryOrGroup(allQueries[i], totalTime));
1517 PMA_consoleMessages._msgEventBinds($('#debug_console').find('.message:not(.binded)'));
1519 refresh: function () {
1520 var last = this._lastDebugInfo;
1521 PMA_consoleDebug.showLog(last.debugInfo, last.url);
1526 * Executed on page load
1529 PMA_console.initialize();