trilium/src/public/javascripts/dialogs/sql_console.js

106 lines
2.8 KiB
JavaScript
Raw Normal View History

2017-12-15 09:38:56 +08:00
"use strict";
const sqlConsole = (function() {
const $dialog = $("#sql-console-dialog");
const $query = $('#sql-console-query');
const $executeButton = $('#sql-console-execute');
const $resultHead = $('#sql-console-results thead');
const $resultBody = $('#sql-console-results tbody');
2017-12-15 09:38:56 +08:00
2018-02-10 22:14:18 +08:00
let codeEditor;
2017-12-15 09:38:56 +08:00
function showDialog() {
glob.activeDialog = $dialog;
2017-12-15 09:38:56 +08:00
$dialog.dialog({
2017-12-15 09:38:56 +08:00
modal: true,
width: $(window).width(),
2018-02-10 22:14:18 +08:00
height: $(window).height(),
open: function() {
initEditor();
}
});
}
2018-02-10 22:14:18 +08:00
async function initEditor() {
if (!codeEditor) {
await requireLibrary(CODE_MIRROR);
2018-02-10 22:14:18 +08:00
CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";
CodeMirror.keyMap.default["Tab"] = "indentMore";
2018-02-10 22:14:18 +08:00
// removing Escape binding so that Escape will propagate to the dialog (which will close on escape)
delete CodeMirror.keyMap.basic["Esc"];
CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';
2018-02-10 22:14:18 +08:00
codeEditor = CodeMirror($query[0], {
value: "",
viewportMargin: Infinity,
indentUnit: 4,
highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false}
});
codeEditor.setOption("mode", "text/x-sqlite");
CodeMirror.autoLoadMode(codeEditor, "sql");
}
codeEditor.focus();
2017-12-15 09:38:56 +08:00
}
async function execute(e) {
// stop from propagating upwards (dangerous especially with ctrl+enter executable javascript notes)
e.preventDefault();
e.stopPropagation();
2018-02-10 22:14:18 +08:00
const sqlQuery = codeEditor.getValue();
2017-12-15 09:38:56 +08:00
const result = await server.post("sql/execute", {
2017-12-15 09:38:56 +08:00
query: sqlQuery
});
if (!result.success) {
showError(result.error);
return;
}
else {
showMessage("Query was executed successfully.");
}
const rows = result.rows;
$resultHead.empty();
$resultBody.empty();
2017-12-15 09:38:56 +08:00
if (rows.length > 0) {
const result = rows[0];
2017-12-15 09:38:56 +08:00
const rowEl = $("<tr>");
for (const key in result) {
rowEl.append($("<th>").html(key));
}
$resultHead.append(rowEl);
2017-12-15 09:38:56 +08:00
}
for (const result of rows) {
2017-12-15 09:38:56 +08:00
const rowEl = $("<tr>");
for (const key in result) {
rowEl.append($("<td>").html(result[key]));
}
$resultBody.append(rowEl);
2017-12-15 09:38:56 +08:00
}
}
$(document).bind('keydown', 'alt+o', showDialog);
$query.bind('keydown', 'ctrl+return', execute);
$executeButton.click(execute);
2017-12-15 09:38:56 +08:00
return {
showDialog
};
})();