Refactor keyboard shortcut functions in the query tool. Fix some incorrect keycodes and update docs.

Initial work by Sarah & Violet @ Pivotal, with additional tweaks by Murtuza @ EDB.
REL-1_X
Sarah McAlear 2017-08-21 15:27:29 +01:00 committed by Dave Page
parent 2e2ca26020
commit b585063a26
8 changed files with 3977 additions and 3488 deletions

View File

@ -41,11 +41,11 @@ When using the syntax-highlighting SQL editors, the following shortcuts are avai
+--------------------------+------------------+-------------------------------------+ +--------------------------+------------------+-------------------------------------+
| Ctrl+Alt+Right | Cmd+Option+Right | Move right one word | | Ctrl+Alt+Right | Cmd+Option+Right | Move right one word |
+--------------------------+------------------+-------------------------------------+ +--------------------------+------------------+-------------------------------------+
| Ctrl+Shift+/ | Cmd+Shift+/ | Comment selected code (Inline) | | Ctrl+/ | Cmd+/ | Comment selected code (Inline) |
+--------------------------+------------------+-------------------------------------+ +--------------------------+------------------+-------------------------------------+
| Ctrl+Shift+. | Cmd+Shift+. | Uncomment selected code (Inline) | | Ctrl+. | Cmd+. | Uncomment selected code (Inline) |
+--------------------------+------------------+-------------------------------------+ +--------------------------+------------------+-------------------------------------+
| Ctrl+/ | Cmd+/ | Comment/Uncomment code (Block) | | Ctrl+Shift+/ | Cmd+Shift+/ | Comment/Uncomment code (Block) |
+--------------------------+------------------+-------------------------------------+ +--------------------------+------------------+-------------------------------------+
| Ctrl+A | Cmd+A | Select all | | Ctrl+A | Cmd+A | Select all |
+--------------------------+------------------+-------------------------------------+ +--------------------------+------------------+-------------------------------------+

View File

@ -2,10 +2,9 @@ const F5_KEY = 116,
F7_KEY = 118, F7_KEY = 118,
F8_KEY = 119, F8_KEY = 119,
PERIOD_KEY = 190, PERIOD_KEY = 190,
FWD_SLASH_KEY = 191, FWD_SLASH_KEY = 191;
IS_CMD_KEY = window.navigator.platform.search('Mac') != -1;
function keyboardShortcuts(sqlEditorController, event) { function keyboardShortcuts(sqlEditorController, queryToolActions, event) {
if (sqlEditorController.isQueryRunning()) { if (sqlEditorController.isQueryRunning()) {
return; return;
} }
@ -14,28 +13,28 @@ function keyboardShortcuts(sqlEditorController, event) {
if (keyCode === F5_KEY) { if (keyCode === F5_KEY) {
event.preventDefault(); event.preventDefault();
sqlEditorController.executeQuery(); queryToolActions.executeQuery(sqlEditorController);
} else if (event.shiftKey && keyCode === F7_KEY) { } else if (event.shiftKey && keyCode === F7_KEY) {
_stopEventPropagation(); _stopEventPropagation();
sqlEditorController.explainAnalyze(event); queryToolActions.explainAnalyze(sqlEditorController);
} else if (keyCode === F7_KEY) { } else if (keyCode === F7_KEY) {
_stopEventPropagation(); _stopEventPropagation();
sqlEditorController.explain(event); queryToolActions.explain(sqlEditorController);
} else if (keyCode === F8_KEY) { } else if (keyCode === F8_KEY) {
event.preventDefault(); event.preventDefault();
sqlEditorController.download(); queryToolActions.download(sqlEditorController);
} else if (((IS_CMD_KEY && event.metaKey) || (!IS_CMD_KEY && event.ctrlKey)) && } else if (((this.isMac() && event.metaKey) || (!this.isMac() && event.ctrlKey)) &&
event.shiftKey && keyCode === FWD_SLASH_KEY) { event.shiftKey && keyCode === FWD_SLASH_KEY) {
_stopEventPropagation(); _stopEventPropagation();
sqlEditorController.commentLineCode(); queryToolActions.commentBlockCode(sqlEditorController);
} else if (((IS_CMD_KEY && event.metaKey) || (!IS_CMD_KEY && event.ctrlKey)) && } else if (((this.isMac() && event.metaKey) || (!this.isMac() && event.ctrlKey)) &&
event.shiftKey && keyCode === PERIOD_KEY) {
_stopEventPropagation();
sqlEditorController.uncommentLineCode();
} else if (((IS_CMD_KEY && event.metaKey) || (!IS_CMD_KEY && event.ctrlKey)) &&
keyCode === FWD_SLASH_KEY) { keyCode === FWD_SLASH_KEY) {
_stopEventPropagation(); _stopEventPropagation();
sqlEditorController.commentBlockCode(); queryToolActions.commentLineCode(sqlEditorController);
} else if (((this.isMac() && event.metaKey) || (!this.isMac() && event.ctrlKey)) &&
keyCode === PERIOD_KEY) {
_stopEventPropagation();
queryToolActions.uncommentLineCode(sqlEditorController);
} }
function _stopEventPropagation() { function _stopEventPropagation() {
@ -46,6 +45,11 @@ function keyboardShortcuts(sqlEditorController, event) {
} }
} }
function isMac() {
return window.navigator.platform.search('Mac') != -1;
}
module.exports = { module.exports = {
processEvent: keyboardShortcuts, processEvent: keyboardShortcuts,
isMac: isMac,
}; };

View File

@ -0,0 +1,99 @@
import $ from 'jquery';
let queryToolActions = {
_verbose: function () {
return $('.explain-verbose').hasClass('visibility-hidden') ? 'OFF' : 'ON';
},
_costsEnabled: function () {
return $('.explain-costs').hasClass('visibility-hidden') ? 'OFF' : 'ON';
},
_buffers: function () {
return $('.explain-buffers').hasClass('visibility-hidden') ? 'OFF' : 'ON';
},
_timing: function () {
return $('.explain-timing').hasClass('visibility-hidden') ? 'OFF' : 'ON';
},
_clearMessageTab: function () {
$('.sql-editor-message').html('');
},
executeQuery: function (sqlEditorController) {
if(sqlEditorController.is_query_tool) {
this._clearMessageTab();
sqlEditorController.execute();
} else {
sqlEditorController.execute_data_query();
}
},
explainAnalyze: function (sqlEditorController) {
let costEnabled = this._costsEnabled();
let verbose = this._verbose();
let buffers = this._buffers();
let timing = this._timing();
let explainAnalyzeQuery = `EXPLAIN (FORMAT JSON, ANALYZE ON, VERBOSE ${verbose}, COSTS ${costEnabled}, BUFFERS ${buffers}, TIMING ${timing}) `;
sqlEditorController.execute(explainAnalyzeQuery);
},
explain: function (sqlEditorController) {
let costEnabled = this._costsEnabled();
let verbose = this._verbose();
let explainQuery = `EXPLAIN (FORMAT JSON, ANALYZE OFF, VERBOSE ${verbose}, COSTS ${costEnabled}, BUFFERS OFF, TIMING OFF) `;
sqlEditorController.execute(explainQuery);
},
download: function (sqlEditorController) {
let sqlQuery = sqlEditorController.gridView.query_tool_obj.getSelection();
if (!sqlQuery) {
sqlQuery = sqlEditorController.gridView.query_tool_obj.getValue();
}
if (!sqlQuery) return;
let filename = 'data-' + new Date().getTime() + '.csv';
if (!sqlEditorController.is_query_tool) {
filename = sqlEditorController.table_name + '.csv';
}
sqlEditorController.trigger_csv_download(sqlQuery, filename);
},
commentBlockCode: function (sqlEditorController) {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
if (!codeMirrorObj.getValue()) return;
codeMirrorObj.toggleComment(codeMirrorObj.getCursor(true), codeMirrorObj.getCursor(false));
},
commentLineCode: function (sqlEditorController) {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
if (!codeMirrorObj.getValue()) return;
codeMirrorObj.lineComment(codeMirrorObj.getCursor(true),
codeMirrorObj.getCursor(false),
{lineComment: '--'}
);
},
uncommentLineCode: function (sqlEditorController) {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
if (!codeMirrorObj.getValue()) return;
codeMirrorObj.uncomment(codeMirrorObj.getCursor(true),
codeMirrorObj.getCursor(false),
{lineComment: '--'}
);
},
};
module.exports = queryToolActions;

View File

@ -217,7 +217,7 @@ def panel(trans_id, is_query_tool, editor_title):
is_desktop_mode=app.PGADMIN_RUNTIME, is_desktop_mode=app.PGADMIN_RUNTIME,
is_linux=is_linux_platform, is_linux=is_linux_platform,
is_new_browser_tab=new_browser_tab, is_new_browser_tab=new_browser_tab,
client_plaform=user_agent.platform client_platform=user_agent.platform
) )

View File

@ -58,7 +58,7 @@
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li> <li>
<a id="btn-find-menu-find" href="#"> <a id="btn-find-menu-find" href="#">
<span> {{ _('Find') }}{% if client_plaform == 'macos' -%} <span> {{ _('Find') }}{% if client_platform == 'macos' -%}
{{ _(' (Cmd+F)') }} {{ _(' (Cmd+F)') }}
{% else %} {% else %}
{{ _(' (Ctrl+F)') }}{%- endif %}</span> {{ _(' (Ctrl+F)') }}{%- endif %}</span>
@ -66,7 +66,7 @@
</li> </li>
<li> <li>
<a id="btn-find-menu-find-next" href="#"> <a id="btn-find-menu-find-next" href="#">
<span> {{ _('Find next') }}{% if client_plaform == 'macos' -%} <span> {{ _('Find next') }}{% if client_platform == 'macos' -%}
{{ _(' (Cmd+G)') }} {{ _(' (Cmd+G)') }}
{% else %} {% else %}
{{ _(' (Ctrl+G)') }}{%- endif %}</span> {{ _(' (Ctrl+G)') }}{%- endif %}</span>
@ -74,7 +74,7 @@
</li> </li>
<li> <li>
<a id="btn-find-menu-find-previous" href="#"> <a id="btn-find-menu-find-previous" href="#">
<span> {{ _('Find previous') }}{% if client_plaform == 'macos' -%} <span> {{ _('Find previous') }}{% if client_platform == 'macos' -%}
{{ _(' (Cmd+Shift+G)') }} {{ _(' (Cmd+Shift+G)') }}
{% else %} {% else %}
{{ _(' (Ctrl+Shift+G)') }}{%- endif %}</span> {{ _(' (Ctrl+Shift+G)') }}{%- endif %}</span>
@ -88,7 +88,7 @@
<li class="divider"></li> <li class="divider"></li>
<li> <li>
<a id="btn-find-menu-replace" href="#"> <a id="btn-find-menu-replace" href="#">
<span> {{ _('Replace') }}{% if client_plaform == 'macos' -%} <span> {{ _('Replace') }}{% if client_platform == 'macos' -%}
{{ _(' (Cmd+Shift+F)') }} {{ _(' (Cmd+Shift+F)') }}
{% else %} {% else %}
{{ _(' (Ctrl+Shift+F)') }}{%- endif %}</span> {{ _(' (Ctrl+Shift+F)') }}{%- endif %}</span>
@ -139,23 +139,23 @@
<span> {{ _('Unindent Selection (Shift+Tab)') }} </span> <span> {{ _('Unindent Selection (Shift+Tab)') }} </span>
</a> </a>
<a id="btn-comment-line" href="#"> <a id="btn-comment-line" href="#">
<span> {{ _('Inline Comment Selection') }}{% if client_plaform == 'macos' -%} <span> {{ _('Inline Comment Selection') }}{% if client_platform == 'macos' -%}
{{ _(' (Cmd+Shift+/)') }}
{% else %}
{{ _(' (Ctrl+Shift+/)') }}{%- endif %}</span>
</a>
<a id="btn-uncomment-line" href="#">
<span> {{ _('Inline Uncomment Selection') }}{% if client_plaform == 'macos' -%}
{{ _(' (Cmd+Shift+.)') }}
{% else %}
{{ _(' (Ctrl+Shift+.)') }}{%- endif %}</span>
</a>
<a id="btn-toggle-comment-block" href="#">
<span> {{ _('Block Comment/Uncomment Selection') }}{% if client_plaform == 'macos' -%}
{{ _(' (Cmd+/)') }} {{ _(' (Cmd+/)') }}
{% else %} {% else %}
{{ _(' (Ctrl+/)') }}{%- endif %}</span> {{ _(' (Ctrl+/)') }}{%- endif %}</span>
</a> </a>
<a id="btn-uncomment-line" href="#">
<span> {{ _('Inline Uncomment Selection') }}{% if client_platform == 'macos' -%}
{{ _(' (Cmd+.)') }}
{% else %}
{{ _(' (Ctrl+.)') }}{%- endif %}</span>
</a>
<a id="btn-toggle-comment-block" href="#">
<span> {{ _('Block Comment/Uncomment Selection') }}{% if client_platform == 'macos' -%}
{{ _(' (Shift+Cmd+/)') }}
{% else %}
{{ _(' (Shift+Ctrl+/)') }}{%- endif %}</span>
</a>
</li> </li>
</ul> </ul>
</div> </div>

View File

@ -16,6 +16,7 @@ define('tools.querytool', [
'sources/../jsx/history/query_history', 'sources/../jsx/history/query_history',
'react', 'react-dom', 'react', 'react-dom',
'sources/sqleditor/keyboard_shortcuts', 'sources/sqleditor/keyboard_shortcuts',
'sources/sqleditor/query_tool_actions',
'sources/../bundle/slickgrid', 'sources/../bundle/slickgrid',
'pgadmin.file_manager', 'pgadmin.file_manager',
'backgrid.sizeable.columns', 'backgrid.sizeable.columns',
@ -27,7 +28,7 @@ define('tools.querytool', [
pgExplain, GridSelector, ActiveCellCapture, clipboard, copyData, RangeSelectionHelper, handleQueryOutputKeyboardEvent, pgExplain, GridSelector, ActiveCellCapture, clipboard, copyData, RangeSelectionHelper, handleQueryOutputKeyboardEvent,
XCellSelectionModel, setStagedRows, SqlEditorUtils, HistoryBundle, queryHistory, React, ReactDOM, XCellSelectionModel, setStagedRows, SqlEditorUtils, HistoryBundle, queryHistory, React, ReactDOM,
keyboardShortcuts keyboardShortcuts
) { , queryToolActions) {
/* Return back, this has been called more than once */ /* Return back, this has been called more than once */
if (pgAdmin.SqlEditor) if (pgAdmin.SqlEditor)
return pgAdmin.SqlEditor; return pgAdmin.SqlEditor;
@ -36,8 +37,7 @@ define('tools.querytool', [
// Generally the one, which do no have AMD support. // Generally the one, which do no have AMD support.
var wcDocker = window.wcDocker, var wcDocker = window.wcDocker,
pgBrowser = pgAdmin.Browser, pgBrowser = pgAdmin.Browser,
CodeMirror = codemirror.default, CodeMirror = codemirror.default,Slick = window.Slick;
Slick = window.Slick;
var is_query_running = false; var is_query_running = false;
@ -255,7 +255,9 @@ define('tools.querytool', [
msg = gettext("The text has changed. Do you want to save changes?"); msg = gettext("The text has changed. Do you want to save changes?");
notify = true; notify = true;
} }
if(notify) {return self.user_confirmation(p, msg);} if (notify) {
return self.user_confirmation(p, msg);
}
return true; return true;
}); });
// Set focus on query tool of active panel // Set focus on query tool of active panel
@ -552,7 +554,7 @@ define('tools.querytool', [
var column_size = self.handler['col_size'], var column_size = self.handler['col_size'],
query = self.handler.query, query = self.handler.query,
// Extract table name from query // Extract table name from query
table_list = query.match(/select.*from\s+(\w+)/i); table_list = query.match(/select.*from\s+\w+\.*(\w+)/i);
if (!table_list) { if (!table_list) {
table_name = SqlEditorUtils.getHash(query); table_name = SqlEditorUtils.getHash(query);
@ -1265,7 +1267,7 @@ define('tools.querytool', [
// Callback function for the flash button click. // Callback function for the flash button click.
on_flash: function () { on_flash: function () {
this.handler.executeQuery(); queryToolActions.executeQuery(this.handler);
}, },
// Callback function for the cancel query button click. // Callback function for the cancel query button click.
@ -1282,17 +1284,17 @@ define('tools.querytool', [
// Callback function for the line comment code // Callback function for the line comment code
on_comment_line_code: function () { on_comment_line_code: function () {
this.handler.commentLineCode(); queryToolActions.commentLineCode(this.handler);
}, },
// Callback function for the line uncomment code // Callback function for the line uncomment code
on_uncomment_line_code: function () { on_uncomment_line_code: function () {
this.handler.uncommentLineCode(); queryToolActions.uncommentLineCode(this.handler);
}, },
// Callback function for the block comment/uncomment code // Callback function for the block comment/uncomment code
on_toggle_comment_block_code: function () { on_toggle_comment_block_code: function () {
this.handler.commentBlockCode(); queryToolActions.commentBlockCode(this.handler);
}, },
on_indent_code: function () { on_indent_code: function () {
@ -1347,7 +1349,9 @@ define('tools.querytool', [
this._stopEventPropogation(ev); this._stopEventPropogation(ev);
this._closeDropDown(ev); this._closeDropDown(ev);
// ask for confirmation only if anything to clear // ask for confirmation only if anything to clear
if(!self.history_collection.length()) { return; } if (!self.history_collection.length()) {
return;
}
alertify.confirm(gettext("Clear history"), alertify.confirm(gettext("Clear history"),
gettext("Are you sure you wish to clear the history?"), gettext("Are you sure you wish to clear the history?"),
@ -1395,7 +1399,7 @@ define('tools.querytool', [
this._stopEventPropogation(event); this._stopEventPropogation(event);
this._closeDropDown(event); this._closeDropDown(event);
this.handler.explain(event); queryToolActions.explain(this.handler);
}, },
// Callback function for explain analyze button click. // Callback function for explain analyze button click.
@ -1403,7 +1407,7 @@ define('tools.querytool', [
this._stopEventPropogation(event); this._stopEventPropogation(event);
this._closeDropDown(event); this._closeDropDown(event);
this.handler.explainAnalyze(event); queryToolActions.explainAnalyze(this.handler);
}, },
// Callback function for explain option "verbose" button click // Callback function for explain option "verbose" button click
@ -1482,11 +1486,11 @@ define('tools.querytool', [
}, },
on_download: function () { on_download: function () {
this.handler.download(); queryToolActions.download(this.handler);
}, },
keyAction: function (event) { keyAction: function (event) {
keyboardShortcuts.processEvent(this.handler, event); keyboardShortcuts.processEvent(this.handler, queryToolActions, event);
}, },
}); });
@ -1589,13 +1593,13 @@ define('tools.querytool', [
cm.className += ' bg-gray-1 opacity-5'; cm.className += ' bg-gray-1 opacity-5';
} }
self.disable_tool_buttons(true); self.disable_tool_buttons(true);
self._execute_data_query(); self.execute_data_query();
} }
}, },
// This function checks if there is any dirty data in the grid before // This function checks if there is any dirty data in the grid before
// it executes the sql query // it executes the sql query
_execute_data_query: function() { execute_data_query: function () {
var self = this; var self = this;
// Check if the data grid has any changes before running query // Check if the data grid has any changes before running query
@ -1889,6 +1893,7 @@ define('tools.querytool', [
var _msg = msg1 + '\n' + msg2; var _msg = msg1 + '\n' + msg2;
// If there is additional messages from server then add it to message // If there is additional messages from server then add it to message
if(!_.isNull(data.additional_messages) && if(!_.isNull(data.additional_messages) &&
!_.isUndefined(data.additional_messages)) { !_.isUndefined(data.additional_messages)) {
@ -2084,7 +2089,8 @@ define('tools.querytool', [
// Scroll automatically when msgs appends to element // Scroll automatically when msgs appends to element
setTimeout(function () { setTimeout(function () {
$(".sql-editor-message").scrollTop($(".sql-editor-message")[0].scrollHeight);; $(".sql-editor-message").scrollTop($(".sql-editor-message")[0].scrollHeight);
;
}, 10); }, 10);
if (status != 'Busy') { if (status != 'Busy') {
@ -2633,20 +2639,6 @@ define('tools.querytool', [
} }
}, },
// This function will run the SQL query and refresh the data in the backgrid.
executeQuery: function() {
var self = this;
// Start execution of the query.
if (self.is_query_tool) {
$('.sql-editor-message').html('');
self._execute();
} else {
self._execute_data_query();
}
},
// This function will set the required flag for polling response data // This function will set the required flag for polling response data
_init_polling_flags: function () { _init_polling_flags: function () {
var self = this; var self = this;
@ -2764,7 +2756,7 @@ define('tools.querytool', [
function () { function () {
if (res.data.status) { if (res.data.status) {
// Refresh the sql grid // Refresh the sql grid
self.executeQuery(); queryToolActions.executeQuery(self);
} }
else { else {
alertify.alert('Filter By Selection Error', res.data.result); alertify.alert('Filter By Selection Error', res.data.result);
@ -2834,7 +2826,7 @@ define('tools.querytool', [
function () { function () {
if (res.data.status) { if (res.data.status) {
// Refresh the sql grid // Refresh the sql grid
self.executeQuery(); queryToolActions.executeQuery(self);
} }
else { else {
alertify.alert('Filter Exclude Selection Error', res.data.result); alertify.alert('Filter Exclude Selection Error', res.data.result);
@ -2885,7 +2877,7 @@ define('tools.querytool', [
function () { function () {
if (res.data.status) { if (res.data.status) {
// Refresh the sql grid // Refresh the sql grid
self.executeQuery(); queryToolActions.executeQuery(self);
} }
else { else {
alertify.alert('Remove Filter Error', res.data.result); alertify.alert('Remove Filter Error', res.data.result);
@ -2940,7 +2932,7 @@ define('tools.querytool', [
$('#filter').addClass('hidden'); $('#filter').addClass('hidden');
$('#editor-panel').removeClass('sql-editor-busy-fetching'); $('#editor-panel').removeClass('sql-editor-busy-fetching');
// Refresh the sql grid // Refresh the sql grid
self.executeQuery(); queryToolActions.executeQuery(self);
} }
else { else {
alertify.alert('Apply Filter Error', res.data.result); alertify.alert('Apply Filter Error', res.data.result);
@ -2982,7 +2974,9 @@ define('tools.querytool', [
data = dataView.getItems(), data = dataView.getItems(),
count = dataView.getLength(), count = dataView.getLength(),
rows = grid.getSelectedRows().sort( rows = grid.getSelectedRows().sort(
function (a, b) { return a - b; } function (a, b) {
return a - b;
}
), ),
copied_rows = rows.map(function (rowIndex) { copied_rows = rows.map(function (rowIndex) {
return data[rowIndex]; return data[rowIndex];
@ -3064,7 +3058,7 @@ define('tools.querytool', [
function () { function () {
if (res.data.status) { if (res.data.status) {
// Refresh the sql grid // Refresh the sql grid
self.executeQuery(); queryToolActions.executeQuery(self);
} }
else else
alertify.alert('Change limit Error', res.data.result); alertify.alert('Change limit Error', res.data.result);
@ -3105,7 +3099,7 @@ define('tools.querytool', [
// This function will fetch the sql query from the text box // This function will fetch the sql query from the text box
// and execute the query. // and execute the query.
_execute: function (explain_prefix) { execute: function (explain_prefix) {
var self = this, var self = this,
sql = '', sql = '',
history_msg = ''; history_msg = '';
@ -3303,57 +3297,8 @@ define('tools.querytool', [
}); });
}, },
// This function will download the grid data as CSV file.
download: function() {
var self = this,
selected_code = self.gridView.query_tool_obj.getSelection(),
sql = "";
if (selected_code.length > 0)
sql = selected_code;
else
sql = self.gridView.query_tool_obj.getValue();
// If it is an empty query, do nothing.
if (sql.length <= 0) return;
/* If download is from view data then file name should be
* the object name for which data is to be displayed.
*/
if (!self.is_query_tool) {
$.ajax({
url: url_for('sqleditor.get_object_name', {'trans_id': self.transId}),
method: 'GET',
success: function(res) {
if (res.data.status) {
filename = res.data.result + '.csv';
self._trigger_csv_download(sql, filename);
}
},
error: function(e) {
if (e.readyState == 0) {
alertify.alert('Get Object Name Error',
gettext("Not connected to the server or the connection to the server has been closed.")
);
return;
}
var msg = e.responseText;
if (e.responseJSON != undefined &&
e.responseJSON.errormsg != undefined)
msg = e.responseJSON.errormsg;
alertify.alert('Get Object Name Error', msg);
}
});
} else {
var cur_time = new Date();
var filename = 'data-' + cur_time.getTime() + '.csv';
self._trigger_csv_download(sql, filename);
}
},
// Trigger query result download to csv. // Trigger query result download to csv.
_trigger_csv_download: function(query, filename) { trigger_csv_download: function (query, filename) {
var self = this, var self = this,
link = $(this.container).find("#download-csv"), link = $(this.container).find("#download-csv"),
url = url_for('sqleditor.query_tool_download', {'trans_id': self.transId}); url = url_for('sqleditor.query_tool_download', {'trans_id': self.transId});
@ -3440,31 +3385,6 @@ define('tools.querytool', [
}); });
}, },
// This function will
explain: function() {
var self = this;
var verbose = $('.explain-verbose').hasClass('visibility-hidden') ? 'OFF' : 'ON';
var costs = $('.explain-costs').hasClass('visibility-hidden') ? 'OFF' : 'ON';
// No need to check for buffers and timing option value in explain
var explain_query = 'EXPLAIN (FORMAT JSON, ANALYZE OFF, VERBOSE %s, COSTS %s, BUFFERS OFF, TIMING OFF) ';
explain_query = S(explain_query).sprintf(verbose, costs).value();
self._execute(explain_query);
},
// This function will
explainAnalyze: function() {
var self = this;
var verbose = $('.explain-verbose').hasClass('visibility-hidden') ? 'OFF' : 'ON';
var costs = $('.explain-costs').hasClass('visibility-hidden') ? 'OFF' : 'ON';
var buffers = $('.explain-buffers').hasClass('visibility-hidden') ? 'OFF' : 'ON';
var timing = $('.explain-timing').hasClass('visibility-hidden') ? 'OFF' : 'ON';
var explain_query = 'Explain (FORMAT JSON, ANALYZE ON, VERBOSE %s, COSTS %s, BUFFERS %s, TIMING %s) ';
explain_query = S(explain_query).sprintf(verbose, costs, buffers, timing).value();
self._execute(explain_query);
},
// This function will toggle "verbose" option in explain // This function will toggle "verbose" option in explain
_explain_verbose: function () { _explain_verbose: function () {
var self = this; var self = this;
@ -3613,55 +3533,6 @@ define('tools.querytool', [
}); });
}, },
/*
* This function will comment code (Wrapper function)
*/
commentLineCode: function() {
this._toggle_comment_code('comment_line');
},
/*
* This function will uncomment code (Wrapper function)
*/
uncommentLineCode: function() {
this._toggle_comment_code('uncomment_line');
},
/*
* This function will comment/uncomment code (Wrapper function)
*/
commentBlockCode: function() {
this._toggle_comment_code('block');
},
/*
* This function will comment/uncomment code (Main function)
*/
_toggle_comment_code: function(of_type) {
var self = this, editor = self.gridView.query_tool_obj,
selected_code = editor.getSelection(),
sql = selected_code.length > 0 ? selected_code : editor.getValue();
// If it is an empty query, do nothing.
if (sql.length <= 0) return;
// Find the code selection range
var range = {
from: editor.getCursor(true),
to: editor.getCursor(false)
},
option = { lineComment: '--' };
if(of_type == 'comment_line') {
// Comment line
editor.lineComment(range.from, range.to, option);
} else if(of_type == 'uncomment_line') {
// Uncomment line
editor.uncomment(range.from, range.to, option);
} else if(of_type == 'block') {
editor.toggleComment(range.from, range.to);
}
},
/* /*
* This function will indent selected code * This function will indent selected code
*/ */

View File

@ -8,6 +8,7 @@
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
import keyboardShortcuts from 'sources/sqleditor/keyboard_shortcuts'; import keyboardShortcuts from 'sources/sqleditor/keyboard_shortcuts';
import {queryToolActions} from 'sources/sqleditor/query_tool_actions';
describe('the keyboard shortcuts', () => { describe('the keyboard shortcuts', () => {
const F1_KEY = 112, const F1_KEY = 112,
@ -15,11 +16,9 @@ describe('the keyboard shortcuts', () => {
F7_KEY = 118, F7_KEY = 118,
F8_KEY = 119, F8_KEY = 119,
PERIOD_KEY = 190, PERIOD_KEY = 190,
FWD_SLASH_KEY = 191, FWD_SLASH_KEY = 191;
isMacSystem = window.navigator.platform.search('Mac') != -1;
let sqlEditorControllerSpy; let sqlEditorControllerSpy, event, queryToolActionsSpy;
let event;
beforeEach(() => { beforeEach(() => {
event = { event = {
shift: false, shift: false,
@ -30,15 +29,27 @@ describe('the keyboard shortcuts', () => {
stopImmediatePropagation: jasmine.createSpy('stopImmediatePropagation'), stopImmediatePropagation: jasmine.createSpy('stopImmediatePropagation'),
}; };
let gridView = {
query_tool_obj: {
getSelection: jasmine.createSpy('getSelection'),
getValue: jasmine.createSpy('getValue'),
},
};
sqlEditorControllerSpy = jasmine.createSpyObj('SqlEditorController', [ sqlEditorControllerSpy = jasmine.createSpyObj('SqlEditorController', [
'isQueryRunning', 'isQueryRunning',
'download', 'execute',
'explain', ]);
sqlEditorControllerSpy.gridView = gridView;
queryToolActionsSpy = jasmine.createSpyObj(queryToolActions, [
'explainAnalyze', 'explainAnalyze',
'executeQuery', 'explain',
'download',
'commentBlockCode',
'commentLineCode', 'commentLineCode',
'uncommentLineCode', 'uncommentLineCode',
'commentBlockCode', 'executeQuery',
]); ]);
}); });
@ -46,7 +57,7 @@ describe('the keyboard shortcuts', () => {
beforeEach(() => { beforeEach(() => {
event.which = F1_KEY; event.which = F1_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should allow event to propagate', () => { it('should allow event to propagate', () => {
@ -58,11 +69,11 @@ describe('the keyboard shortcuts', () => {
describe('when there is no query already running', () => { describe('when there is no query already running', () => {
beforeEach(() => { beforeEach(() => {
event.keyCode = F5_KEY; event.keyCode = F5_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should execute the query', () => { it('should execute the query', () => {
expect(sqlEditorControllerSpy.executeQuery).toHaveBeenCalled(); expect(queryToolActionsSpy.executeQuery).toHaveBeenCalledWith(sqlEditorControllerSpy);
}); });
it('should stop event propagation', () => { it('should stop event propagation', () => {
@ -75,9 +86,9 @@ describe('the keyboard shortcuts', () => {
event.keyCode = F5_KEY; event.keyCode = F5_KEY;
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(sqlEditorControllerSpy.executeQuery).not.toHaveBeenCalled(); expect(queryToolActionsSpy.executeQuery).not.toHaveBeenCalled();
}); });
}); });
}); });
@ -86,11 +97,11 @@ describe('the keyboard shortcuts', () => {
describe('when there is not a query already running', () => { describe('when there is not a query already running', () => {
beforeEach(() => { beforeEach(() => {
event.which = F7_KEY; event.which = F7_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should explain the query plan', () => { it('should explain the query plan', () => {
expect(sqlEditorControllerSpy.explain).toHaveBeenCalledWith(event); expect(queryToolActionsSpy.explain).toHaveBeenCalledWith(sqlEditorControllerSpy);
}); });
expectEventPropagationToStop(); expectEventPropagationToStop();
@ -101,23 +112,23 @@ describe('the keyboard shortcuts', () => {
event.keyCode = F7_KEY; event.keyCode = F7_KEY;
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(sqlEditorControllerSpy.explain).not.toHaveBeenCalled(); expect(queryToolActionsSpy.explain).not.toHaveBeenCalled();
}); });
}); });
}); });
describe('Shift+F7', () => { describe('Shift+F7', () => {
describe('when therre is not a query already running', () => { describe('when there is not a query already running', () => {
beforeEach(() => { beforeEach(() => {
event.shiftKey = true; event.shiftKey = true;
event.which = F7_KEY; event.which = F7_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should analyze explain the query plan', () => { it('should analyze explain the query plan', () => {
expect(sqlEditorControllerSpy.explainAnalyze).toHaveBeenCalledWith(event); expect(queryToolActionsSpy.explainAnalyze).toHaveBeenCalledWith(sqlEditorControllerSpy);
}); });
expectEventPropagationToStop(); expectEventPropagationToStop();
@ -129,9 +140,9 @@ describe('the keyboard shortcuts', () => {
event.which = F7_KEY; event.which = F7_KEY;
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(sqlEditorControllerSpy.explainAnalyze).not.toHaveBeenCalled(); expect(queryToolActionsSpy.explainAnalyze).not.toHaveBeenCalled();
}); });
}); });
}); });
@ -140,11 +151,11 @@ describe('the keyboard shortcuts', () => {
describe('when there is not a query already running', () => { describe('when there is not a query already running', () => {
beforeEach(() => { beforeEach(() => {
event.which = F8_KEY; event.which = F8_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should download the query results as a CSV', () => { it('should download the query results as a CSV', () => {
expect(sqlEditorControllerSpy.download).toHaveBeenCalled(); expect(queryToolActionsSpy.download).toHaveBeenCalled();
}); });
it('should stop event propagation', () => { it('should stop event propagation', () => {
@ -157,102 +168,196 @@ describe('the keyboard shortcuts', () => {
event.keyCode = F8_KEY; event.keyCode = F8_KEY;
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(sqlEditorControllerSpy.download).not.toHaveBeenCalled(); expect(queryToolActionsSpy.download).not.toHaveBeenCalled();
}); });
}); });
}); });
describe('inlineComment', () => { describe('inlineComment', () => {
describe('when there is not a query already running', () => { describe('when there is not a query already running', () => {
describe('and the system is a Mac', () => {
beforeEach(() => { beforeEach(() => {
event.metaKey = isMacSystem; macKeysSetup();
event.shiftKey = true;
event.ctrlKey = !isMacSystem;
event.which = FWD_SLASH_KEY; event.which = FWD_SLASH_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should comment the line', () => { it('should comment the line', () => {
expect(sqlEditorControllerSpy.commentLineCode).toHaveBeenCalled(); expect(queryToolActionsSpy.commentLineCode).toHaveBeenCalledWith(sqlEditorControllerSpy);
}); });
expectEventPropagationToStop(); expectEventPropagationToStop();
}); });
describe('when the query is already running', () => { describe('and the system is Windows', () => {
it('does nothing', () => { beforeEach(() => {
event.shiftKey = isMacSystem; windowsKeysSetup();
event.ctrlKey = !isMacSystem;
event.which = FWD_SLASH_KEY; event.which = FWD_SLASH_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
});
it('should comment the line', () => {
expect(queryToolActionsSpy.commentLineCode).toHaveBeenCalledWith(sqlEditorControllerSpy);
});
expectEventPropagationToStop();
});
});
describe('when the query is already running', () => {
beforeEach(() => {
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
});
describe('and the system is a Mac', () => {
beforeEach(() => {
macKeysSetup();
event.which = FWD_SLASH_KEY;
});
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); it('does nothing', () => {
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(sqlEditorControllerSpy.commentLineCode).not.toHaveBeenCalled(); expect(queryToolActionsSpy.commentLineCode).not.toHaveBeenCalled();
});
});
describe('and the system is a Windows', () => {
beforeEach(() => {
windowsKeysSetup();
event.which = FWD_SLASH_KEY;
});
it('does nothing', () => {
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(queryToolActionsSpy.commentLineCode).not.toHaveBeenCalled();
});
}); });
}); });
}); });
describe('inlineUncomment', () => { describe('inlineUncomment', () => {
describe('when there is not a query already running', () => { describe('when there is not a query already running', () => {
describe('and the system is a mac', () => {
beforeEach(() => { beforeEach(() => {
event.metaKey = isMacSystem; macKeysSetup();
event.shiftKey = true;
event.ctrlKey = !isMacSystem;
event.which = PERIOD_KEY; event.which = PERIOD_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should uncomment the line', () => { it('should uncomment the line', () => {
expect(sqlEditorControllerSpy.uncommentLineCode).toHaveBeenCalled(); expect(queryToolActionsSpy.uncommentLineCode).toHaveBeenCalledWith(sqlEditorControllerSpy);
}); });
expectEventPropagationToStop(); expectEventPropagationToStop();
}); });
describe('and the system is a windows', () => {
beforeEach(() => {
windowsKeysSetup();
event.which = PERIOD_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
});
it('should uncomment the line', () => {
expect(queryToolActionsSpy.uncommentLineCode).toHaveBeenCalledWith(sqlEditorControllerSpy);
});
expectEventPropagationToStop();
});
});
describe('when the query is already running', () => { describe('when the query is already running', () => {
it('does nothing', () => { beforeEach(() => {
event.metaKey = isMacSystem;
event.shiftKey = true;
event.ctrlKey = !isMacSystem;
event.which = PERIOD_KEY;
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
});
describe('and the system is a Mac', () => {
beforeEach(() => {
macKeysSetup();
event.which = PERIOD_KEY;
});
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); it('does nothing', () => {
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(queryToolActionsSpy.uncommentLineCode).not.toHaveBeenCalled();
});
});
describe('and the system is a Windows', () => {
beforeEach(() => {
windowsKeysSetup();
event.which = PERIOD_KEY;
});
expect(sqlEditorControllerSpy.uncommentLineCode).not.toHaveBeenCalled(); it('does nothing', () => {
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
expect(queryToolActionsSpy.uncommentLineCode).not.toHaveBeenCalled();
});
}); });
}); });
}); });
describe('blockComment', () => { describe('blockComment', () => {
describe('when there is not a query already running', () => { describe('when there is not a query already running', () => {
describe('and the system is a Mac', () => {
beforeEach(() => { beforeEach(() => {
event.metaKey = isMacSystem; macKeysSetup();
event.ctrlKey = !isMacSystem;
event.which = FWD_SLASH_KEY; event.which = FWD_SLASH_KEY;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); event.shiftKey = true;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
}); });
it('should comment a block of code', () => { it('should comment out the block selection', () => {
expect(sqlEditorControllerSpy.commentBlockCode).toHaveBeenCalled(); expect(queryToolActionsSpy.commentBlockCode).toHaveBeenCalledWith(sqlEditorControllerSpy);
}); });
expectEventPropagationToStop(); expectEventPropagationToStop();
}); });
});
describe('when the query is already running', () => { describe('when there is not a query already running', () => {
it('does nothing', () => { describe('and the system is a Windows', () => {
event.metaKey = isMacSystem; beforeEach(() => {
event.ctrlKey = !isMacSystem; windowsKeysSetup();
event.which = FWD_SLASH_KEY; event.which = FWD_SLASH_KEY;
event.shiftKey = true;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
});
it('should comment out the block selection', () => {
expect(queryToolActionsSpy.commentBlockCode).toHaveBeenCalledWith(sqlEditorControllerSpy);
});
expectEventPropagationToStop();
});
});
describe('when there is a query already running', () => {
beforeEach(() => {
sqlEditorControllerSpy.isQueryRunning.and.returnValue(true); sqlEditorControllerSpy.isQueryRunning.and.returnValue(true);
});
keyboardShortcuts.processEvent(sqlEditorControllerSpy, event); describe('and the system is a Mac', () => {
beforeEach(() => {
expect(sqlEditorControllerSpy.commentBlockCode).not.toHaveBeenCalled(); macKeysSetup();
event.which = FWD_SLASH_KEY;
event.shiftKey = true;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
});
it('does nothing', () => {
expect(queryToolActionsSpy.commentBlockCode).not.toHaveBeenCalled();
});
});
describe('and the system is a Windows', () => {
beforeEach(() => {
windowsKeysSetup();
event.which = FWD_SLASH_KEY;
event.shiftKey = true;
keyboardShortcuts.processEvent(sqlEditorControllerSpy, queryToolActionsSpy, event);
});
it('does nothing', () => {
expect(queryToolActionsSpy.commentBlockCode).not.toHaveBeenCalled();
});
}); });
}); });
}); });
@ -274,4 +379,16 @@ describe('the keyboard shortcuts', () => {
}); });
}); });
} }
function windowsKeysSetup() {
spyOn(keyboardShortcuts, 'isMac').and.returnValue(false);
event.ctrlKey = true;
event.metaKey = false;
}
function macKeysSetup() {
spyOn(keyboardShortcuts, 'isMac').and.returnValue(true);
event.ctrlKey = false;
event.metaKey = true;
}
}); });

View File

@ -0,0 +1,398 @@
//////////////////////////////////////////////////////////////////////////
//
// pgAdmin 4 - PostgreSQL Tools
//
// Copyright (C) 2013 - 2017, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////////////////
import queryToolActions from 'sources/sqleditor/query_tool_actions';
describe('queryToolActions', () => {
let sqlEditorController,
getSelectionSpy, getValueSpy,
selectedQueryString, entireQueryString;
describe('executeQuery', () => {
describe('when the command is being run from the query tool', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_clearMessageTab');
});
it('clears the html in the message tab', () => {
queryToolActions.executeQuery(sqlEditorController);
expect(queryToolActions._clearMessageTab).toHaveBeenCalled();
});
it('calls the execute function on the sqlEditorController', () => {
queryToolActions.executeQuery(sqlEditorController);
expect(sqlEditorController.execute).toHaveBeenCalled();
});
});
describe('when the command is being run from the view data view', () => {
beforeEach(() => {
setUpSpies('', '');
sqlEditorController.is_query_tool = false;
});
it('it calls the execute_data_query function on the sqlEditorController', () => {
queryToolActions.executeQuery(sqlEditorController);
expect(sqlEditorController.execute_data_query).toHaveBeenCalled();
});
});
});
describe('explainAnalyze', () => {
describe('when verbose and costs are not selected and buffers and timing are not selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('OFF');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('OFF');
spyOn(queryToolActions, '_buffers').and.returnValue('OFF');
spyOn(queryToolActions, '_timing').and.returnValue('OFF');
});
it('calls the execute function', () => {
queryToolActions.explainAnalyze(sqlEditorController);
let explainAnalyzeQuery = 'EXPLAIN (FORMAT JSON, ANALYZE ON, VERBOSE OFF, COSTS OFF, BUFFERS OFF, TIMING OFF) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainAnalyzeQuery);
});
});
describe('when verbose and costs and buffers and timing are all selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('ON');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('ON');
spyOn(queryToolActions, '_buffers').and.returnValue('ON');
spyOn(queryToolActions, '_timing').and.returnValue('ON');
});
it('calls the execute function', () => {
queryToolActions.explainAnalyze(sqlEditorController);
let explainAnalyzeQuery = 'EXPLAIN (FORMAT JSON, ANALYZE ON, VERBOSE ON, COSTS ON, BUFFERS ON, TIMING ON) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainAnalyzeQuery);
});
});
describe('when verbose is selected and costs is not selected and buffer is selected and timing is not selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('ON');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('OFF');
spyOn(queryToolActions, '_buffers').and.returnValue('ON');
spyOn(queryToolActions, '_timing').and.returnValue('OFF');
});
it('calls the execute function', () => {
queryToolActions.explainAnalyze(sqlEditorController);
let explainAnalyzeQuery = 'EXPLAIN (FORMAT JSON, ANALYZE ON, VERBOSE ON, COSTS OFF, BUFFERS ON, TIMING OFF) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainAnalyzeQuery);
});
});
describe('when verbose is not selected and costs is selected and buffer is not selected and timing is selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('OFF');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('ON');
spyOn(queryToolActions, '_buffers').and.returnValue('OFF');
spyOn(queryToolActions, '_timing').and.returnValue('ON');
});
it('calls the execute function', () => {
queryToolActions.explainAnalyze(sqlEditorController);
let explainAnalyzeQuery = 'EXPLAIN (FORMAT JSON, ANALYZE ON, VERBOSE OFF, COSTS ON, BUFFERS OFF, TIMING ON) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainAnalyzeQuery);
});
});
});
describe('explain', () => {
describe('when verbose and costs are selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('ON');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('ON');
});
it('calls the execute function', () => {
queryToolActions.explain(sqlEditorController);
let explainQuery = 'EXPLAIN (FORMAT JSON, ANALYZE OFF, VERBOSE ON, COSTS ON, BUFFERS OFF, TIMING OFF) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainQuery);
});
});
describe('when verbose and costs are not selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('OFF');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('OFF');
});
it('calls the execute function', () => {
queryToolActions.explain(sqlEditorController);
let explainQuery = 'EXPLAIN (FORMAT JSON, ANALYZE OFF, VERBOSE OFF, COSTS OFF, BUFFERS OFF, TIMING OFF) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainQuery);
});
});
describe('when verbose is selected and costs is not selected', () => {
beforeEach(() => {
setUpSpies('', '');
spyOn(queryToolActions, '_verbose').and.returnValue('ON');
spyOn(queryToolActions, '_costsEnabled').and.returnValue('OFF');
});
it('calls the execute function', () => {
queryToolActions.explain(sqlEditorController);
let explainQuery = 'EXPLAIN (FORMAT JSON, ANALYZE OFF, VERBOSE ON, COSTS OFF, BUFFERS OFF, TIMING OFF) ';
expect(sqlEditorController.execute).toHaveBeenCalledWith(explainQuery);
});
});
});
describe('download', () => {
describe('when the query is empty', () => {
beforeEach(() => {
setUpSpies('', '');
});
it('does nothing', () => {
queryToolActions.download(sqlEditorController);
expect(sqlEditorController.trigger_csv_download).not.toHaveBeenCalled();
});
});
describe('when the table was opened through the queryTool', () => {
describe('when the query tool object has a selection', () => {
let time;
beforeEach(() => {
entireQueryString = 'include some more of that yummy string cheese;';
selectedQueryString = 'some silly string cheese';
setUpSpies(selectedQueryString, entireQueryString);
time = 'rightNow';
spyOn(window, 'Date').and.callFake(() => ({
getTime: () => {
return time;
},
}));
});
it('calls trigger_csv_download with the query and the filename', () => {
let filename = 'data-' + time + '.csv';
queryToolActions.download(sqlEditorController);
expect(sqlEditorController.trigger_csv_download).toHaveBeenCalledWith(selectedQueryString, filename);
});
});
describe('when there is no selection', () => {
let time;
beforeEach(() => {
selectedQueryString = '';
entireQueryString = 'include some more of that yummy string cheese;';
setUpSpies(selectedQueryString, entireQueryString);
time = 'rightNow';
spyOn(window, 'Date').and.callFake(() => ({
getTime: () => {
return time;
},
}));
});
it('calls trigger_csv_download with the query and the filename', () => {
let filename = 'data-' + time + '.csv';
queryToolActions.download(sqlEditorController);
expect(sqlEditorController.trigger_csv_download).toHaveBeenCalledWith(entireQueryString, filename);
});
});
});
describe('when the table was opened through tables, view all data', () => {
it('calls trigger_csv_download with the sqlQuery and the table name', () => {
let query = 'a very long query';
setUpSpies('', query);
sqlEditorController.is_query_tool = false;
queryToolActions.download(sqlEditorController);
expect(sqlEditorController.trigger_csv_download).toHaveBeenCalledWith(query, 'iAmATable' + '.csv');
});
});
});
describe('commentBlockCode', () => {
describe('when there is no query text', () => {
beforeEach(() => {
setUpSpies('', '');
});
it('does nothing', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.commentBlockCode(sqlEditorController);
expect(codeMirrorObj.toggleComment).not.toHaveBeenCalled();
});
});
describe('when there is empty selection', () => {
beforeEach(() => {
setUpSpies('', 'a string\nddd\nsss');
sqlEditorController.gridView.query_tool_obj.getCursor = (isFrom) => {
return isFrom ? 3 : 3;
};
});
it('comments the current line', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.commentBlockCode(sqlEditorController);
expect(codeMirrorObj.toggleComment).toHaveBeenCalledWith(3, 3);
});
});
describe('when some part of the query is selected', () => {
beforeEach(() => {
setUpSpies('a string\nddd', 'a string\nddd\nsss');
});
it('comments the selection', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.commentBlockCode(sqlEditorController);
expect(codeMirrorObj.toggleComment).toHaveBeenCalledWith(0, 12);
});
});
});
describe('commentLineCode', () => {
describe('when there is no query text', () => {
beforeEach(() => {
setUpSpies('', '');
});
it('does nothing', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.commentLineCode(sqlEditorController);
expect(codeMirrorObj.lineComment).not.toHaveBeenCalled();
});
});
describe('when there is empty selection', () => {
beforeEach(() => {
setUpSpies('', 'a string\nddd\nsss');
sqlEditorController.gridView.query_tool_obj.getCursor = (isFrom) => {
return isFrom ? 3 : 3;
};
});
it('comments the current line', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.commentLineCode(sqlEditorController);
expect(codeMirrorObj.lineComment).toHaveBeenCalledWith(3, 3, {lineComment: '--'});
});
});
describe('when some part of the query is selected', () => {
beforeEach(() => {
setUpSpies('tring\nddd', 'a string\nddd\nsss');
});
it('comments the selection', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.commentLineCode(sqlEditorController);
expect(codeMirrorObj.lineComment).toHaveBeenCalledWith(3, 12, {lineComment: '--'});
});
});
});
describe('uncommentLineCode', () => {
describe('when there is no query text', () => {
beforeEach(() => {
setUpSpies('', '');
});
it('does nothing', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.uncommentLineCode(sqlEditorController);
expect(codeMirrorObj.uncomment).not.toHaveBeenCalled();
});
});
describe('when there is empty selection', () => {
beforeEach(() => {
setUpSpies('', 'a string\nddd\nsss');
sqlEditorController.gridView.query_tool_obj.getCursor = (isFrom) => {
return isFrom ? 3 : 3;
};
});
it('uncomments the current line', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.uncommentLineCode(sqlEditorController);
expect(codeMirrorObj.uncomment).toHaveBeenCalledWith(3, 3, {lineComment: '--'});
});
});
describe('when some part of the query is selected', () => {
beforeEach(() => {
setUpSpies('tring\nddd', 'a string\nddd\nsss');
});
it('uncomments the selection', () => {
let codeMirrorObj = sqlEditorController.gridView.query_tool_obj;
queryToolActions.uncommentLineCode(sqlEditorController);
expect(codeMirrorObj.uncomment).toHaveBeenCalledWith(3, 12, {lineComment: '--'});
});
});
});
function setUpSpies(selectedQueryString, entireQueryString) {
getValueSpy = jasmine.createSpy('getValueSpy').and.returnValue(entireQueryString);
getSelectionSpy = jasmine.createSpy('getSelectionSpy').and.returnValue(selectedQueryString);
sqlEditorController = {
gridView: {
query_tool_obj: {
getSelection: getSelectionSpy,
getValue: getValueSpy,
toggleComment: jasmine.createSpy('toggleCommentSpy'),
lineComment: jasmine.createSpy('lineCommentSpy'),
uncomment: jasmine.createSpy('uncommentSpy'),
getCursor: (isFrom) => {
return entireQueryString.indexOf(selectedQueryString) + (isFrom ? 0 : selectedQueryString.length);
},
},
},
trigger_csv_download: jasmine.createSpy('trigger_csv_download'),
trigger: jasmine.createSpy('trigger'),
table_name: 'iAmATable',
is_query_tool: true,
execute: jasmine.createSpy('execute'),
execute_data_query: jasmine.createSpy('execute_data_query'),
};
}
});