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

106 lines
2.5 KiB
JavaScript
Raw Normal View History

2017-12-15 09:38:56 +08:00
"use strict";
import utils from '../utils.js';
2018-02-10 22:14:18 +08:00
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');
2018-02-10 22:14:18 +08:00
let codeEditor;
2018-02-10 22:14:18 +08:00
function showDialog() {
glob.activeDialog = $dialog;
$dialog.dialog({
modal: true,
width: $(window).width(),
height: $(window).height(),
open: function() {
initEditor();
}
});
}
2018-02-10 22:14:18 +08:00
async function initEditor() {
if (!codeEditor) {
await utils.requireLibrary(utils.CODE_MIRROR);
CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";
CodeMirror.keyMap.default["Tab"] = "indentMore";
// 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';
codeEditor = CodeMirror($query[0], {
value: "",
viewportMargin: Infinity,
indentUnit: 4,
highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false}
});
codeEditor.setOption("mode", "text/x-sqlite");
CodeMirror.autoLoadMode(codeEditor, "sql");
2017-12-15 09:38:56 +08:00
}
codeEditor.focus();
}
async function execute(e) {
// stop from propagating upwards (dangerous especially with ctrl+enter executable javascript notes)
e.preventDefault();
e.stopPropagation();
2017-12-15 09:38:56 +08:00
const sqlQuery = codeEditor.getValue();
2017-12-15 09:38:56 +08:00
const result = await server.post("sql/execute", {
query: sqlQuery
});
if (!result.success) {
utils.showError(result.error);
return;
}
else {
utils.showMessage("Query was executed successfully.");
}
const rows = result.rows;
2017-12-15 09:38:56 +08:00
$resultHead.empty();
$resultBody.empty();
2017-12-15 09:38:56 +08:00
if (rows.length > 0) {
const result = rows[0];
const rowEl = $("<tr>");
2017-12-15 09:38:56 +08:00
for (const key in result) {
rowEl.append($("<th>").html(key));
2017-12-15 09:38:56 +08:00
}
$resultHead.append(rowEl);
}
2017-12-15 09:38:56 +08:00
for (const result of rows) {
const rowEl = $("<tr>");
2017-12-15 09:38:56 +08:00
for (const key in result) {
rowEl.append($("<td>").html(result[key]));
2017-12-15 09:38:56 +08:00
}
$resultBody.append(rowEl);
2017-12-15 09:38:56 +08:00
}
}
2017-12-15 09:38:56 +08:00
$(document).bind('keydown', 'alt+o', showDialog);
2017-12-15 09:38:56 +08:00
$query.bind('keydown', 'ctrl+return', execute);
$executeButton.click(execute);
2017-12-15 09:38:56 +08:00
export default {
showDialog
};