Notes/src/public/app/widgets/sql_result.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

2021-05-22 12:35:41 +02:00
import NoteContextAwareWidget from "./note_context_aware_widget.js";
const TPL = `
<div class="sql-result-widget">
<style>
.sql-result-widget {
padding: 15px;
}
</style>
2021-07-27 22:08:41 +02:00
<div class="sql-query-no-rows alert alert-info" style="display: none;">
No rows have been returned for this query.
</div>
<div class="sql-console-result-container"></div>
</div>`;
2021-05-22 12:35:41 +02:00
export default class SqlResultWidget extends NoteContextAwareWidget {
isEnabled() {
return this.note
&& this.note.mime === 'text/x-sqlite;schema=trilium'
&& super.isEnabled();
}
doRender() {
this.$widget = $(TPL);
2021-07-27 22:08:41 +02:00
this.$resultContainer = this.$widget.find('.sql-console-result-container');
this.$noRowsAlert = this.$widget.find('.sql-query-no-rows');
}
2021-05-22 12:26:45 +02:00
async sqlQueryResultsEvent({ntxId, results}) {
2021-05-22 12:42:34 +02:00
if (!this.isNoteContext(ntxId)) {
2021-02-15 20:44:55 +01:00
return;
}
2021-07-27 22:08:41 +02:00
this.$noRowsAlert.toggle(results.length === 1 && results[0].length === 0);
this.$resultContainer.toggle(results.length > 1 || results[0].length > 0);
this.$resultContainer.empty();
for (const rows of results) {
2021-10-03 10:42:46 +02:00
if (typeof rows === 'object' && !Array.isArray(rows)) {
// inserts, updates
this.$resultContainer.empty().show().append(
$("<pre>").text(JSON.stringify(rows, null, '\t'))
);
continue;
}
2021-02-15 20:44:55 +01:00
if (!rows.length) {
continue;
}
const $table = $('<table class="table table-striped">');
2021-07-27 22:08:41 +02:00
this.$resultContainer.append($table);
const result = rows[0];
const $row = $("<tr>");
for (const key in result) {
2023-03-26 20:50:37 +02:00
$row.append($("<th>").text(key));
}
$table.append($row);
for (const result of rows) {
const $row = $("<tr>");
for (const key in result) {
2023-03-26 20:50:37 +02:00
$row.append($("<td>").text(result[key]));
}
$table.append($row);
}
}
}
}