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

105 lines
2.6 KiB
JavaScript
Raw Normal View History

import utils from '../services/utils.js';
2018-03-28 10:42:46 +08:00
import libraryLoader from '../services/library_loader.js';
import server from '../services/server.js';
2018-03-26 09:29:35 +08:00
import infoService from "../services/info.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) {
2018-03-28 10:42:46 +08:00
await libraryLoader.requireLibrary(libraryLoader.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) {
2018-03-26 09:29:35 +08:00
infoService.showError(result.error);
return;
}
else {
2018-03-26 09:29:35 +08:00
infoService.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
$query.bind('keydown', 'ctrl+return', execute);
$executeButton.click(execute);
2017-12-15 09:38:56 +08:00
export default {
showDialog
};