Skip to content

A platform for community discussion. Free, open, simple.

UI: Update manual data explorer query page (step 3/n) (#40190)

Natalie Tay0ea69eedea6a
diff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs
index 1a853905ec4..6f524d5597f 100644
--- a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs
+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/edit.gjs
@@ -1,10 +1,10 @@
import Component from "@glimmer/component";
-import { Input } from "@ember/component";
-import { fn, hash } from "@ember/helper";
+import { hash } from "@ember/helper";
import { on } from "@ember/modifier";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import AceEditor from "discourse/components/ace-editor";
import BackButton from "discourse/components/back-button";
+import DSegmentedControl from "discourse/components/d-segmented-control";
import MultiSelect from "discourse/select-kit/components/multi-select";
import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
@@ -18,6 +18,7 @@ import ExplorerSchema from "discourse/plugins/discourse-data-explorer/discourse/
import ParamInputForm from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";
import QueryResultDownloadButtons from "discourse/plugins/discourse-data-explorer/discourse/components/query-result-download-buttons";
import QueryResultsWrapper from "discourse/plugins/discourse-data-explorer/discourse/components/query-results-wrapper";
+import QueryRunSplitButton from "discourse/plugins/discourse-data-explorer/discourse/components/query-run-split-button";
export default class QueriesEdit extends Component {
get showDestroyQuery() {
@@ -92,27 +93,26 @@ export default class QueriesEdit extends Component {
<div class="clear"></div>
- {{#if @controller.editingQuery}}
- <div class="query-editor {{if @controller.hideSchema 'no-schema'}}">
+ <div class="query-editor">
+ <div class="query-editor__header">
+ <h3 class="query-editor__label">{{i18n "explorer.sql_label"}}</h3>
+ </div>
+
+ {{#if @controller.editingQuery}}
<div class="panels-flex">
<div class="editor-panel">
<AceEditor
- {{on "click" @controller.setDirty}}
@content={{@controller.model.sql}}
- @onChange={{fn (mut @controller.model.sql)}}
+ @onChange={{@controller.updateSql}}
@mode="sql"
@disabled={{@controller.editorDisabled}}
@save={{@controller.save}}
- @submit={{@controller.saveAndRun}}
+ @submit={{@controller.run}}
/>
</div>
<div class="right-panel">
- <ExplorerSchema
- @schema={{@controller.schema}}
- @hideSchema={{@controller.hideSchema}}
- @updateHideSchema={{@controller.updateHideSchema}}
- />
+ <ExplorerSchema @schema={{@controller.schema}} />
</div>
</div>
@@ -128,16 +128,16 @@ export default class QueriesEdit extends Component {
</div>
<div class="clear"></div>
- </div>
- {{else}}
- <div class="sql">
- <CodeView
- @value={{@controller.model.sql}}
- @codeClass="sql"
- @setDirty={{@controller.setDirty}}
- />
- </div>
- {{/if}}
+ {{else}}
+ <div class="sql">
+ <CodeView
+ @value={{@controller.model.sql}}
+ @codeClass="sql"
+ @setDirty={{@controller.setDirty}}
+ />
+ </div>
+ {{/if}}
+ </div>
<div class="clear"></div>
@@ -148,125 +148,75 @@ export default class QueriesEdit extends Component {
{{/if}}
</div>
- <form class="query-run" {{on "submit" @controller.run}}>
- {{#if @controller.model.hasParams}}
+ {{#if @controller.model.hasParams}}
+ <form class="query-params-block" {{on "submit" @controller.run}}>
<ParamInputForm
@initialValues={{@controller.parsedParams}}
@paramInfo={{@controller.model.param_info}}
@onRegisterApi={{@controller.onRegisterApi}}
/>
- {{/if}}
-
- <div class="query-run-actions">
- <div class="query-run-actions__left">
- {{#if @controller.runDisabled}}
- {{#if @controller.saveDisabled}}
- <DButton
- @label="explorer.run"
- @disabled="true"
- class="btn-primary query-run__submit"
- />
- {{else}}
- <DButton
- @action={{@controller.saveAndRun}}
- @icon="play"
- @label="explorer.saverun"
- class="btn-primary query-run__save-and-run"
- />
- {{/if}}
- {{else}}
- <DButton
- {{didInsert @controller.runOnLoad}}
- @action={{@controller.run}}
- @icon="play"
- @label="explorer.run"
- @disabled={{@controller.runDisabled}}
- @type="submit"
- class="btn-primary query-run__submit"
- />
- {{/if}}
-
- {{#if @controller.editingQuery}}
- <DButton
- class="btn-save-query"
- @action={{@controller.save}}
- @label="explorer.save"
- @disabled={{@controller.saveDisabled}}
- />
- {{else}}
- {{#unless @controller.editDisabled}}
- <DButton
- class="btn-edit-query"
- @action={{@controller.editQuery}}
- @label="explorer.edit"
- @icon="pencil"
- />
- {{/unless}}
- {{/if}}
-
- {{#if @controller.editingQuery}}
- <DButton
- @action={{@controller.showHelpModal}}
- @label="explorer.help.label"
- @icon="circle-question"
- />
- {{/if}}
-
- <label class="query-plan">
- <Input
- @type="checkbox"
- @checked={{@controller.explain}}
- name="explain"
- />
- {{i18n "explorer.explain_label"}}
- </label>
- </div>
-
- <div class="query-run-actions__right">
- {{#if @controller.model.destroyed}}
- <DButton
- @action={{@controller.recover}}
- @icon="arrow-rotate-left"
- @label="explorer.recover"
- />
- {{else}}
- {{#if @controller.editingQuery}}
- <DButton
- @action={{@controller.discard}}
- @icon="arrow-rotate-left"
- @label="explorer.undo"
- @disabled={{@controller.saveDisabled}}
- />
- {{/if}}
-
- <DButton
- @action={{@controller.download}}
- @label="explorer.export"
- @disabled={{@controller.runDisabled}}
- @icon="download"
- />
+ </form>
+ {{/if}}
+
+ <div class="query-action-bar">
+ <div class="query-action-bar__left">
+ <QueryRunSplitButton
+ @onRun={{@controller.run}}
+ @disabled={{@controller.runDisabled}}
+ @label={{@controller.runButtonLabel}}
+ />
+ {{#if @controller.editingQuery}}
+ <DButton
+ @action={{@controller.discard}}
+ @icon="arrow-rotate-left"
+ @label="explorer.undo"
+ @disabled={{@controller.saveDisabled}}
+ class="btn-discard-query"
+ />
+ <DButton
+ @action={{@controller.showHelpModal}}
+ @label="explorer.help.label"
+ @icon="circle-question"
+ class="btn-transparent query-action-bar__help"
+ />
+ {{/if}}
+ </div>
- {{#if @controller.showResults}}
- <QueryResultDownloadButtons
- @query={{@controller.model}}
- @content={{@controller.results}}
- class="query-result-download-buttons--inline"
- />
- {{/if}}
+ <div class="query-action-bar__right">
+ {{#if @controller.hasResults}}
+ <DSegmentedControl
+ @name="query-result-view"
+ @value={{@controller.view}}
+ @items={{@controller.viewItems}}
+ @onSelect={{@controller.setView}}
+ @translatedLabel={{i18n "explorer.view.label"}}
+ class="query-results-modes"
+ />
+ {{/if}}
+ <QueryResultDownloadButtons
+ @query={{@controller.model}}
+ @content={{@controller.results}}
+ @includeQueryExport={{true}}
+ />
- {{#if this.showDestroyQuery}}
- <DButton
- @action={{@controller.destroyQuery}}
- @icon="trash-can"
- @label="explorer.delete"
- class="btn-danger"
- />
- {{/if}}
- {{/if}}
- </div>
+ {{#if @controller.model.destroyed}}
+ <DButton
+ @action={{@controller.recover}}
+ @icon="arrow-rotate-left"
+ @label="explorer.recover"
+ />
+ {{else if this.showDestroyQuery}}
+ <DButton
+ @action={{@controller.destroyQuery}}
+ @icon="trash-can"
+ @label="explorer.delete"
+ class="btn-danger"
+ />
+ {{/if}}
</div>
- </form>
- <hr />
+ </div>
+
+ <div hidden {{didInsert @controller.runOnLoad}}></div>
<DConditionalLoadingSpinner @condition={{@controller.loading}} />
@@ -276,8 +226,11 @@ export default class QueriesEdit extends Component {
@query={{@controller.model}}
@content={{@controller.results}}
@cachedAt={{@controller.cachedAt}}
- @showDownloads={{false}}
+ @view={{@controller.view}}
+ @onSetView={{@controller.setView}}
+ @hideHeaderActions={{true}}
/>
+
{{/if}}
</div>
</template>
diff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs
index 802fa85879e..c1c2ce60045 100644
--- a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs
+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs
@@ -151,7 +151,7 @@ export default <template>
<label class="query-new__sql-label">
{{i18n "explorer.ai.sql_label"}}
</label>
- <div class="query-editor {{if @controller.hideSchema 'no-schema'}}">
+ <div class="query-editor">
<div class="panels-flex">
<div class="editor-panel">
<AceEditor
@@ -161,11 +161,7 @@ export default <template>
/>
</div>
<div class="right-panel">
- <ExplorerSchema
- @schema={{@controller.schema}}
- @hideSchema={{@controller.hideSchema}}
- @updateHideSchema={{@controller.updateHideSchema}}
- />
+ <ExplorerSchema @schema={{@controller.schema}} />
</div>
</div>
<div class="clear"></div>
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs
index c7cd2ac9205..3cb43e3f1cd 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/explorer-schema.gjs
@@ -5,8 +5,9 @@ import { action } from "@ember/object";
import { isBlank, isEmpty } from "@ember/utils";
import withEventValue from "discourse/helpers/with-event-value";
import { debounce } from "discourse/lib/decorators";
-import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
import OneTable from "./explorer-schema/one-table";
export default class ExplorerSchema extends Component {
@@ -80,7 +81,6 @@ export default class ExplorerSchema extends Component {
continue;
}
- // Check the table name vs the filter
if (filter.source === key || filter.source + "s" === key) {
tables.unshift({
name: key,
@@ -88,14 +88,12 @@ export default class ExplorerSchema extends Component {
open: haveFilter,
});
} else if (filter.test(key)) {
- // whole table matches
tables.push({
name: key,
columns: this.transformedSchema[key],
open: haveFilter,
});
} else {
- // filter the columns
let filterCols = [];
this.transformedSchema[key].forEach((col) => {
if (filter.source === col.column_name) {
@@ -128,47 +126,27 @@ export default class ExplorerSchema extends Component {
this.updateFilter(value);
}
- @action
- collapseSchema() {
- this.args.updateHideSchema(true);
- }
-
- @action
- expandSchema() {
- this.args.updateHideSchema(false);
- }
-
<template>
- {{#if @hideSchema}}
- <DButton
- @action={{this.expandSchema}}
- @icon="chevron-left"
- class="no-text unhide"
- />
- {{else}}
- <div class="schema">
- <div class="schema-search inline-form full-width">
- <input
- type="text"
- {{on "input" (withEventValue this.filterChanged)}}
- />
- <DButton
- @action={{this.collapseSchema}}
- @icon="chevron-right"
- class="no-text"
- />
- </div>
+ <div class="schema">
+ <div class="schema-search">
+ {{dIcon "magnifying-glass" class="schema-search__icon"}}
+ <input
+ type="text"
+ class="schema-search__input"
+ placeholder={{i18n "explorer.schema.search_tables"}}
+ {{on "input" (withEventValue this.filterChanged)}}
+ />
+ </div>
- <div class="schema-container">
- <DConditionalLoadingSpinner @condition={{this.loading}}>
- <ul>
- {{#each this.filteredTables as |table|}}
- <OneTable @table={{table}} />
- {{/each}}
- </ul>
- </DConditionalLoadingSpinner>
- </div>
+ <div class="schema-container">
+ <DConditionalLoadingSpinner @condition={{this.loading}}>
+ <ul>
+ {{#each this.filteredTables as |table|}}
+ <OneTable @table={{table}} />
+ {{/each}}
+ </ul>
+ </DConditionalLoadingSpinner>
</div>
- {{/if}}
+ </div>
</template>
}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-chart-empty-state.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-chart-empty-state.gjs
new file mode 100644
index 00000000000..db75063e9da
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-chart-empty-state.gjs
@@ -0,0 +1,32 @@
+import Component from "@glimmer/component";
+import DButton from "discourse/ui-kit/d-button";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class QueryChartEmptyState extends Component {
+ get message() {
+ if (this.args.reason === "no-rows") {
+ return i18n("explorer.chart_empty.no_rows");
+ }
+ const cols = this.args.ignoredColumns ?? [];
+ if (cols.length) {
+ return i18n("explorer.chart_empty.no_numeric_with_columns", {
+ columns: cols.join(", "),
+ });
+ }
+ return i18n("explorer.chart_empty.no_numeric");
+ }
+
+ <template>
+ <div class="query-chart-empty-state">
+ {{dIcon "chart-line" class="query-chart-empty-state__icon"}}
+ <p class="query-chart-empty-state__message">{{this.message}}</p>
+ <DButton
+ @action={{@onViewAsTable}}
+ @label="explorer.chart_empty.view_as_table"
+ @icon="table"
+ class="btn-default query-chart-empty-state__view-table"
+ />
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result-download-buttons.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result-download-buttons.gjs
index c62b4d39832..e777cbcc497 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result-download-buttons.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result-download-buttons.gjs
@@ -1,28 +1,45 @@
import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
import { action } from "@ember/object";
import { schedule } from "@ember/runloop";
+import DMenu from "discourse/float-kit/components/d-menu";
import { ajax } from "discourse/lib/ajax";
import getURL from "discourse/lib/get-url";
import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
import { QUERY_RESULT_MAX_LIMIT } from "discourse/plugins/discourse-data-explorer/discourse/lib/constants";
export default class QueryResultDownloadButtons extends Component {
+ get hasResults() {
+ return !!this.args.content?.rows?.length;
+ }
+
get params() {
- return this.args.content.params;
+ return this.args.content?.params;
}
get explainText() {
- return this.args.content.explain;
+ return this.args.content?.explain;
+ }
+
+ @action
+ downloadQueryJson(dMenu) {
+ window.open(this.args.query.downloadUrl, "_blank");
+ dMenu?.close();
}
@action
- downloadResultJson() {
+ downloadResultJson(dMenu) {
this._downloadResult("json");
+ dMenu?.close();
}
@action
- downloadResultCsv() {
+ downloadResultCsv(dMenu) {
this._downloadResult("csv");
+ dMenu?.close();
}
_downloadUrl() {
@@ -76,19 +93,47 @@ export default class QueryResultDownloadButtons extends Component {
}
<template>
- <div class="query-result-download-buttons" ...attributes>
- <DButton
- @action={{this.downloadResultJson}}
- @icon="download"
- @label="explorer.download_json"
- />
-
- <DButton
- @action={{this.downloadResultCsv}}
- @icon="download"
- @label="explorer.download_csv"
- />
- </div>
+ <DMenu
+ @identifier="query-result-export"
+ @triggerClass="btn-default query-result-export__trigger query-result-download-buttons"
+ @placement="bottom-end"
+ ...attributes
+ >
+ <:trigger>
+ {{dIcon "download"}}
+ <span>{{i18n "explorer.export_as.label"}}</span>
+ {{dIcon "angle-down"}}
+ </:trigger>
+ <:content as |dMenu|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.hasResults}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.downloadResultJson dMenu}}
+ @label="explorer.export_as.results_json"
+ class="btn-transparent query-result-export__results-json"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.downloadResultCsv dMenu}}
+ @label="explorer.export_as.results_csv"
+ class="btn-transparent query-result-export__results-csv"
+ />
+ </dropdown.item>
+ {{/if}}
+ {{#if @includeQueryExport}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.downloadQueryJson dMenu}}
+ @label="explorer.export_as.query_json"
+ class="btn-transparent query-result-export__query-json"
+ />
+ </dropdown.item>
+ {{/if}}
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
</template>
}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
index 2d1208bc1cb..76305a9acb7 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-result.gjs
@@ -1,18 +1,20 @@
import Component from "@glimmer/component";
-import { tracked } from "@glimmer/tracking";
+import { cached, tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { service } from "@ember/service";
import { capitalize } from "@ember/string";
import moment from "moment";
+import DSegmentedControl from "discourse/components/d-segmented-control";
import KeyValueStore from "discourse/lib/key-value-store";
import Badge from "discourse/models/badge";
import Category from "discourse/models/category";
import DButton from "discourse/ui-kit/d-button";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import I18n, { i18n } from "discourse-i18n";
-import { isNumericColumn, looksLikeDate } from "../lib/chart-helpers";
+import { chartability, looksLikeDate } from "../lib/chart-helpers";
import DataExplorerChart from "./data-explorer-chart";
+import QueryChartEmptyState from "./query-chart-empty-state";
import QueryResultDownloadButtons from "./query-result-download-buttons";
import QueryRowContent from "./query-row-content";
import BadgeViewComponent from "./result-types/badge";
@@ -48,39 +50,46 @@ const VIEW_COMPONENTS = {
export default class QueryResult extends Component {
@service site;
- @tracked showChart;
- @tracked showTable;
+ @tracked internalView;
@tracked tableExpanded = false;
@tracked hasOverflow = false;
constructor() {
super(...arguments);
+ if (this.args.view) {
+ return;
+ }
const queryId = this.args.query?.id;
- if (queryId) {
- this.showChart = store.get(`showChart_${queryId}`) !== "false";
- this.showTable = store.get(`showTable_${queryId}`) !== "false";
+ const stored = queryId ? store.get(`view_${queryId}`) : null;
+ if (stored === "chart" || stored === "table") {
+ this.internalView = stored;
} else {
- this.showChart = true;
- this.showTable = true;
+ this.internalView = chartability(this.args.content).chartable
+ ? "chart"
+ : "table";
}
}
+ get view() {
+ return this.args.view ?? this.internalView;
+ }
+
@action
- toggleChart() {
- this.showChart = !this.showChart;
+ setView(value) {
+ if (this.args.onSetView) {
+ this.args.onSetView(value);
+ return;
+ }
+ this.internalView = value;
const queryId = this.args.query?.id;
if (queryId) {
- store.set({ key: `showChart_${queryId}`, value: this.showChart });
+ store.set({ key: `view_${queryId}`, value });
}
}
@action
- toggleTable() {
- this.showTable = !this.showTable;
- const queryId = this.args.query?.id;
- if (queryId) {
- store.set({ key: `showTable_${queryId}`, value: this.showTable });
- }
+ viewTable() {
+ this.setView("table");
}
get showExpandButton() {
@@ -101,8 +110,48 @@ export default class QueryResult extends Component {
this.tableExpanded = true;
}
+ @cached
+ get chartability() {
+ return chartability(this.args.content);
+ }
+
+ get canShowChart() {
+ return this.chartability.chartable;
+ }
+
get chartVisible() {
- return this.canShowChart && this.showChart;
+ return this.view === "chart" && this.canShowChart;
+ }
+
+ get showChartEmptyState() {
+ return this.view === "chart" && !this.canShowChart;
+ }
+
+ get showTable() {
+ return this.view === "table";
+ }
+
+ get hasResults() {
+ return this.rows?.length > 0;
+ }
+
+ get numericColumnIndices() {
+ return this.chartability.numericIndices;
+ }
+
+ get ignoredColumnNames() {
+ return this.chartability.ignoredColumns;
+ }
+
+ get ignoredColumnsText() {
+ return this.ignoredColumnNames.join(", ");
+ }
+
+ get viewItems() {
+ return [
+ { value: "chart", icon: "signal" },
+ { value: "table", icon: "table" },
+ ];
}
get colRender() {
@@ -125,25 +174,6 @@ export default class QueryResult extends Component {
return this.args.showDownloads !== false;
}
- get numericColumnIndices() {
- if (!this.rows?.length || !this.columns?.length) {
- return [];
- }
- const indices = [];
- for (let i = 1; i < this.columns.length; i++) {
- if (this.colRender[i]) {
- continue;
- }
- if (
- typeof this.rows[0][i] === "number" ||
- isNumericColumn(this.rows, i)
- ) {
- indices.push(i);
- }
- }
- return indices;
- }
-
get isMultiSeries() {
return this.numericColumnIndices.length > 1;
}
@@ -261,27 +291,6 @@ export default class QueryResult extends Component {
return transformedRelTable(this.site.groups);
}
- get hasTextColumns() {
- if (!this.rows?.length || !this.columns?.length) {
- return false;
- }
- const numericSet = new Set(this.numericColumnIndices);
- for (let i = 1; i < this.columns.length; i++) {
- if (!this.colRender[i] && !numericSet.has(i)) {
- return true;
- }
- }
- return false;
- }
-
- get canShowChart() {
- return (
- this.rows?.length > 0 &&
- this.numericColumnIndices.length > 0 &&
- !this.hasTextColumns
- );
- }
-
get chartLabels() {
const labelSelectors = {
user: (user) => user.username,
@@ -348,15 +357,31 @@ export default class QueryResult extends Component {
<template>
<article>
<div class="result-header">
- <div class="result-info">
- {{#if this.showDownloads}}
- <QueryResultDownloadButtons
- @query={{@query}}
- @content={{@content}}
- @group={{@group}}
- />
- {{/if}}
- </div>
+ {{#unless @hideHeaderActions}}
+ <div class="result-header__top">
+ <div class="result-actions">
+ {{#if this.hasResults}}
+ <DSegmentedControl
+ @name="query-result-view"
+ @value={{this.view}}
+ @items={{this.viewItems}}
+ @onSelect={{this.setView}}
+ @translatedLabel={{i18n "explorer.view.label"}}
+ class="query-results-modes"
+ />
+ {{/if}}
+
+ {{#if this.showDownloads}}
+ <QueryResultDownloadButtons
+ @query={{@query}}
+ @content={{@content}}
+ @group={{@group}}
+ @includeQueryExport={{@includeQueryExport}}
+ />
+ {{/if}}
+ </div>
+ </div>
+ {{/unless}}
<div class="result-meta">
<div class="result-about">
@@ -381,24 +406,6 @@ export default class QueryResult extends Component {
</div>
<section>
- {{#if this.canShowChart}}
- <div class="query-results-modes">
- <DButton
- @action={{this.toggleChart}}
- @icon="signal"
- @translatedTitle={{i18n "explorer.show_graph"}}
- class="btn-toggle-chart
- {{if this.showChart 'btn-primary' 'btn-default'}}"
- />
- <DButton
- @action={{this.toggleTable}}
- @icon="table"
- @translatedTitle={{i18n "explorer.show_table"}}
- class="btn-toggle-table
- {{if this.showTable 'btn-primary' 'btn-default'}}"
- />
- </div>
- {{/if}}
{{#if this.chartVisible}}
<div class="query-results-chart">
@@ -408,9 +415,25 @@ export default class QueryResult extends Component {
@chartType={{this.chartType}}
@stacked={{this.isStacked}}
/>
+ {{#if this.ignoredColumnNames.length}}
+ <p class="query-results-chart__footnote">
+ {{i18n
+ "explorer.chart_footnote.ignored"
+ columns=this.ignoredColumnsText
+ }}
+ </p>
+ {{/if}}
</div>
{{/if}}
+ {{#if this.showChartEmptyState}}
+ <QueryChartEmptyState
+ @reason={{this.chartability.reason}}
+ @ignoredColumns={{this.chartability.ignoredColumns}}
+ @onViewAsTable={{this.viewTable}}
+ />
+ {{/if}}
+
{{#if this.showTable}}
<div
class="query-results-table-wrapper
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs
index 237b37c9c90..00ecac87d40 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-results-wrapper.gjs
@@ -9,6 +9,10 @@ const QueryResultsWrapper = <template>
@content={{@results}}
@cachedAt={{@cachedAt}}
@showDownloads={{@showDownloads}}
+ @includeQueryExport={{@includeQueryExport}}
+ @view={{@view}}
+ @onSetView={{@onSetView}}
+ @hideHeaderActions={{@hideHeaderActions}}
/>
{{else}}
{{#each @results.errors as |err|}}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-run-split-button.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-run-split-button.gjs
new file mode 100644
index 00000000000..09896cc7f4e
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-run-split-button.gjs
@@ -0,0 +1,54 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { or } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+
+export default class QueryRunSplitButton extends Component {
+ @action
+ runPlain() {
+ this.args.onRun?.(false);
+ }
+
+ @action
+ runWithExplain(dMenu) {
+ this.args.onRun?.(true);
+ dMenu?.close();
+ }
+
+ <template>
+ <div class="query-run-split">
+ <DButton
+ @action={{this.runPlain}}
+ @icon="play"
+ @label={{or @label "explorer.run"}}
+ @disabled={{@disabled}}
+ class="btn-primary query-run-split__primary"
+ />
+ <DMenu
+ @identifier="query-run-options"
+ @icon="angle-down"
+ @ariaLabel={{i18n "explorer.run_options"}}
+ @triggerClass="btn-primary query-run-split__chevron"
+ @placement="bottom-end"
+ @disabled={{@disabled}}
+ >
+ <:content as |dMenu|>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.runWithExplain dMenu}}
+ @icon="list-ul"
+ @label="explorer.run_with_explain"
+ class="btn-transparent query-run-split__with-explain"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js
index 7c97f3109b6..7a9e08d085a 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/edit.js
@@ -7,36 +7,80 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { AUTO_GROUPS } from "discourse/lib/constants";
import { bind } from "discourse/lib/decorators";
+import KeyValueStore from "discourse/lib/key-value-store";
import QueryHelp from "discourse/plugins/discourse-data-explorer/discourse/components/modal/query-help";
import { ParamValidationError } from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";
+import { chartability } from "discourse/plugins/discourse-data-explorer/discourse/lib/chart-helpers";
import Query from "discourse/plugins/discourse-data-explorer/discourse/models/query";
+const viewStore = new KeyValueStore("discourse_data_explorer_");
+
export default class PluginsExplorerController extends Controller {
@service modal;
@service appEvents;
@tracked params;
@tracked editingName = false;
- @tracked editingQuery = false;
@tracked loading = false;
@tracked showResults = false;
- @tracked hideSchema = false;
@tracked results = this.model.results;
@tracked dirty = false;
@tracked isCachedResult = false;
+ @tracked view = "table";
queryParams = ["params"];
- explain = false;
order = null;
form = null;
shouldAutoRun = false;
+ _pristine = null;
+
+ constructor() {
+ super(...arguments);
+ if (this.model?.results) {
+ this.initView();
+ }
+ if (this.model) {
+ this.snapshotPristine();
+ }
+ }
+
+ snapshotPristine() {
+ if (!this.model) {
+ return;
+ }
+ this._pristine = {
+ name: this.model.name ?? "",
+ description: this.model.description ?? "",
+ sql: this.model.sql ?? "",
+ group_ids: [...(this.model.group_ids ?? [])].sort().join(","),
+ };
+ this.dirty = false;
+ }
+
+ recomputeDirty() {
+ if (!this._pristine) {
+ this.dirty = true;
+ return;
+ }
+ const current = {
+ name: this.model.name ?? "",
+ description: this.model.description ?? "",
+ sql: this.model.sql ?? "",
+ group_ids: [...(this.model.group_ids ?? [])].sort().join(","),
+ };
+ this.dirty =
+ current.name !== this._pristine.name ||
+ current.description !== this._pristine.description ||
+ current.sql !== this._pristine.sql ||
+ current.group_ids !== this._pristine.group_ids;
+ }
get saveDisabled() {
return !this.dirty;
}
get runDisabled() {
- return this.dirty;
+ return this.model.destroyed;
}
get parsedParams() {
@@ -54,6 +98,10 @@ export default class PluginsExplorerController extends Controller {
return this.model.is_default;
}
+ get editingQuery() {
+ return !this.editDisabled && !this.model.destroyed;
+ }
+
get editorDisabled() {
return this.model.destroyed;
}
@@ -66,13 +114,47 @@ export default class PluginsExplorerController extends Controller {
});
}
+ get hasResults() {
+ return !!this.results?.rows?.length;
+ }
+
+ get runButtonLabel() {
+ return this.dirty ? "explorer.saverun" : "explorer.run";
+ }
+
+ get viewItems() {
+ return [
+ { value: "chart", icon: "signal" },
+ { value: "table", icon: "table" },
+ ];
+ }
+
+ initView() {
+ const queryId = this.model?.id;
+ const stored = queryId ? viewStore.get(`view_${queryId}`) : null;
+ if (stored === "chart" || stored === "table") {
+ this.view = stored;
+ } else {
+ this.view = chartability(this.results).chartable ? "chart" : "table";
+ }
+ }
+
+ @action
+ setView(value) {
+ this.view = value;
+ const queryId = this.model?.id;
+ if (queryId) {
+ viewStore.set({ key: `view_${queryId}`, value });
+ }
+ }
+
@action
async save() {
try {
this.loading = true;
await this.model.save();
- this.dirty = false;
+ this.snapshotPristine();
this.editingName = false;
} catch (error) {
popupAjaxError(error);
@@ -82,11 +164,6 @@ export default class PluginsExplorerController extends Controller {
}
}
- @action
- saveAndRun() {
- this.save().then(() => this.run());
- }
-
async _importQuery(file) {
const json = await this._readFileAsTextAsync(file);
const query = this._parseQuery(json);
@@ -157,13 +234,8 @@ export default class PluginsExplorerController extends Controller {
@action
updateGroupIds(value) {
- this.dirty = true;
this.model.set("group_ids", value);
- }
-
- @action
- updateHideSchema(value) {
- this.hideSchema = value;
+ this.recomputeDirty();
}
@action
@@ -171,16 +243,6 @@ export default class PluginsExplorerController extends Controller {
this.editingName = true;
}
- @action
- editQuery() {
- this.editingQuery = true;
- }
-
- @action
- download() {
- window.open(this.model.downloadUrl, "_blank");
- }
-
@action
showHelpModal() {
this.modal.show(QueryHelp);
@@ -200,7 +262,7 @@ export default class PluginsExplorerController extends Controller {
if (!this.model.group_ids || !Array.isArray(this.model.group_ids)) {
this.model.set("group_ids", []);
}
- this.dirty = false;
+ this.snapshotPristine();
} catch (error) {
popupAjaxError(error);
} finally {
@@ -243,7 +305,16 @@ export default class PluginsExplorerController extends Controller {
@action
setDirty() {
- this.dirty = true;
+ this.recomputeDirty();
+ }
+
+ @action
+ updateSql(value) {
+ if (this.model.sql === value) {
+ return;
+ }
+ this.model.set("sql", value);
+ this.recomputeDirty();
}
@action
@@ -252,7 +323,19 @@ export default class PluginsExplorerController extends Controller {
}
@action
- async run() {
+ async run(explain = false) {
+ // catch any dirty state that onChange may not have flushed yet
+ this.recomputeDirty();
+
+ if (this.dirty) {
+ try {
+ await this.save();
+ } catch {
+ // save() already shows popupAjaxError
+ return;
+ }
+ }
+
let params = null;
if (this.model.hasParams) {
try {
@@ -280,7 +363,7 @@ export default class PluginsExplorerController extends Controller {
type: "POST",
data: {
params: JSON.stringify(params),
- explain: this.explain,
+ explain,
},
}
)
@@ -292,6 +375,7 @@ export default class PluginsExplorerController extends Controller {
return;
}
this.showResults = true;
+ this.initView();
})
.catch((err) => {
this.showResults = false;
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js
index de5e6a9d9fb..c3a0d9589ff 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js
@@ -27,7 +27,6 @@ export default class AdminPluginsExplorerNew extends Controller {
@tracked generatedDescription = "";
@tracked mode = "ai";
@tracked schema = null;
- @tracked hideSchema = false;
@tracked manualSql = "SELECT 1";
currentGenerationId = null;
@@ -51,11 +50,6 @@ export default class AdminPluginsExplorerNew extends Controller {
this.mode = value;
}
- @action
- updateHideSchema(value) {
- this.hideSchema = value;
- }
-
@action
updateManualSql(value) {
this.manualSql = value;
@@ -219,7 +213,6 @@ export default class AdminPluginsExplorerNew extends Controller {
this.generatedDescription = "";
this.mode = "ai";
this.schema = null;
- this.hideSchema = false;
this.manualSql = "SELECT 1";
this.loading = false;
this.manualFormData = { name: "", description: "" };
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
index 33722edb248..28470e0c2a8 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/lib/chart-helpers.js
@@ -23,3 +23,53 @@ export function isNumericColumn(rows, colIndex) {
}
return false;
}
+
+export function chartability(content) {
+ const { rows, columns, colrender = {} } = content ?? {};
+ if (!rows?.length) {
+ return {
+ chartable: false,
+ numericIndices: [],
+ ignoredColumns: [],
+ reason: "no-rows",
+ };
+ }
+ if (!columns?.length || columns.length < 2) {
+ return {
+ chartable: false,
+ numericIndices: [],
+ ignoredColumns: [],
+ reason: "no-numeric",
+ };
+ }
+
+ const numericIndices = [];
+ const ignoredColumns = [];
+ for (let i = 1; i < columns.length; i++) {
+ if (colrender[i]) {
+ ignoredColumns.push(columns[i]);
+ continue;
+ }
+ if (typeof rows[0][i] === "number" || isNumericColumn(rows, i)) {
+ numericIndices.push(i);
+ } else {
+ ignoredColumns.push(columns[i]);
+ }
+ }
+
+ if (numericIndices.length === 0) {
+ return {
+ chartable: false,
+ numericIndices,
+ ignoredColumns,
+ reason: "no-numeric",
+ };
+ }
+
+ return {
+ chartable: true,
+ numericIndices,
+ ignoredColumns,
+ reason: ignoredColumns.length ? "chartable-with-ignored" : "chartable",
+ };
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js
index 3a6dba558a8..1991e4dbb8d 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/edit.js
@@ -63,8 +63,9 @@ export default class AdminPluginsExplorerQueriesDetails extends DiscourseRoute {
results: showCachedResult ? cachedResult : null,
showResults: showCachedResult,
isCachedResult: showCachedResult,
- dirty: false,
shouldAutoRun,
});
+ controller.snapshotPristine();
+ controller.initView();
}
}
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index 34a1311eddb..bd529c5e2da 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -37,28 +37,21 @@ table.group-reports {
.query-editor {
margin-bottom: 15px;
+ .query-editor__header {
+ margin-bottom: 0.5em;
+ }
+
+ .query-editor__label {
+ margin: 0;
+ font-size: var(--font-up-2);
+ }
+
.panels-flex {
display: flex;
height: 400px;
border: 1px solid var(--primary-very-low);
}
- &.no-schema {
- .editor-panel {
- width: 100%;
- }
-
- .right-panel {
- width: 0;
-
- button.unhide {
- position: absolute;
- margin-left: -53px;
- z-index: 1;
- }
- }
- }
-
.editor-panel {
flex-grow: 1;
@@ -97,6 +90,27 @@ table.group-reports {
background-color: var(--secondary);
top: 0;
z-index: 1;
+ display: flex;
+ align-items: center;
+ gap: 0.4em;
+ border-bottom: 1px solid var(--primary-very-low);
+
+ .schema-search__icon {
+ color: var(--primary-medium);
+ }
+
+ .schema-search__input {
+ flex: 1;
+ margin: 0;
+ border: none;
+ background: transparent;
+ padding: 0.25em 0;
+
+ &:focus {
+ outline: none;
+ box-shadow: none;
+ }
+ }
}
.schema-table-name {
@@ -299,6 +313,44 @@ table.group-reports {
}
}
+.query-action-bar {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 0.75em;
+ flex-wrap: wrap;
+}
+
+.query-action-bar__left,
+.query-action-bar__right {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5em;
+ flex-wrap: wrap;
+}
+
+.query-run-split {
+ display: inline-flex;
+ align-items: stretch;
+ gap: 1px;
+
+ .query-run-split__primary,
+ .query-run-split__chevron {
+ margin: 0;
+ }
+
+ .query-run-split__primary {
+ border-top-right-radius: 0;
+ border-bottom-right-radius: 0;
+ }
+
+ .query-run-split__chevron {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
+ padding: 0 0.6em;
+ }
+}
+
.clear {
clear: both;
}
@@ -359,8 +411,10 @@ table.group-reports {
.query-edit,
.query-results,
.query-params,
+.query-action-bar,
+.result-header,
.https-warning {
- margin: 10px 0;
+ margin-bottom: 2em;
}
.query-new__top-bar {
@@ -504,6 +558,12 @@ table.group-reports {
color: var(--tertiary);
}
+.query-result-export__trigger {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+}
+
.query-results {
.query-result-download-buttons {
display: inline-flex;
@@ -514,12 +574,45 @@ table.group-reports {
}
}
- .result-meta {
+ .result-header {
+ display: flex;
+ flex-direction: column;
+ gap: 0.4em;
+ }
+
+ .result-header__top {
display: flex;
justify-content: space-between;
+ align-items: center;
+ gap: 0.75em 1.25em;
+ flex-wrap: wrap;
+ }
+
+ .result-meta {
+ display: flex;
align-items: baseline;
gap: 0.75em 1.25em;
flex-wrap: wrap;
+ color: var(--primary-medium);
+ }
+
+ .result-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5em;
+ }
+
+ .query-results-modes {
+ display: inline-flex;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-button-border-radius, 0.25em);
+ overflow: hidden;
+
+ .btn {
+ margin: 0;
+ border-radius: 0;
+ box-shadow: none;
+ }
}
section {
@@ -529,16 +622,46 @@ table.group-reports {
}
.query-results-chart {
- height: clamp(200px, 50vh, 350px);
min-width: 0;
margin-bottom: 1rem;
animation: fadein 2s;
+ canvas {
+ height: clamp(200px, 50vh, 350px) !important;
+ }
+
@media (prefers-reduced-motion) {
animation-duration: 0s;
}
}
+ .query-results-chart__footnote {
+ margin: 0.5em 0 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ .query-chart-empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 2em 1em;
+ color: var(--primary-medium);
+ text-align: center;
+ border: 1px dashed var(--primary-low);
+ border-radius: var(--d-button-border-radius, 0.25em);
+
+ .query-chart-empty-state__icon {
+ font-size: 2em;
+ margin-bottom: 0.5em;
+ }
+
+ .query-chart-empty-state__message {
+ margin: 0 0 1em;
+ }
+ }
+
table {
width: 100%;
margin-top: 10px;
@@ -570,16 +693,6 @@ table.group-reports {
.query-results-expand-btn {
width: 100%;
}
-
- .query-results-modes {
- display: inline-flex;
- gap: 0.35em;
- margin: 0.75em 0;
-
- .btn {
- margin: 0;
- }
- }
}
.discourse-data-explorer-query-list {
@@ -711,20 +824,14 @@ table.group-reports {
}
}
-.result-info {
- float: left;
-}
-
.result-about {
color: var(--primary-high);
- float: right;
}
.cached-result-notice {
color: var(--primary-medium);
font-size: var(--font-down-1);
- clear: both;
- float: right;
+ margin-left: auto;
}
.result-explain {
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index b0b03344778..f4b864da9de 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -81,26 +81,37 @@ en:
schema:
title: "Database Schema"
filter: "Search..."
+ search_tables: "Search tables"
sensitive: "The contents of this column may contain particularly sensitive or private information. Please exercise caution when using the contents of this column."
types:
bool:
yes: "Yes"
no: "No"
null_: "Null"
- export: "Export"
view_json: "View JSON"
- view: "View"
save: "Save changes"
saverun: "Save changes and run"
run: "Run"
undo: "Discard changes"
- edit: "Edit"
delete: "Delete"
recover: "Undelete query"
- download_json: "JSON"
- download_csv: "CSV"
- show_table: "Table"
- show_graph: "Graph"
+ sql_label: "SQL"
+ run_with_explain: "Run with query plan"
+ run_options: "More run options"
+ view:
+ label: "Result view"
+ chart_empty:
+ no_rows: "No rows to chart."
+ no_numeric: "This query has no numeric columns to chart."
+ no_numeric_with_columns: "This query has no numeric columns to chart (ignored: %{columns})."
+ view_as_table: "View as table"
+ chart_footnote:
+ ignored: "Columns not charted: %{columns}"
+ export_as:
+ label: "Export as…"
+ results_json: "Results (JSON)"
+ results_csv: "Results (CSV)"
+ query_json: "Query definition (JSON)"
others_dirty: "A query has unsaved changes that will be lost if you navigate away."
run_time: "Query completed in %{value} ms."
cached_result_notice: "Showing cached results from %{relative_time}."
@@ -118,7 +129,6 @@ en:
query_time: "Last run"
query_user: "Created by"
column: "Column %{number}"
- explain_label: "Include query plan?"
save_params: "Set defaults"
reset_params: "Reset"
search_placeholder: "Search..."
diff --git a/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb b/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb
index b307824a1c1..19b9223571c 100644
--- a/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb
+++ b/plugins/discourse-data-explorer/spec/system/page_objects/pages/data_explorer_query_runner.rb
@@ -21,7 +21,7 @@ module PageObjects
end
def run_query
- page.find(".query-run .query-run__submit").click
+ page.find(".query-run-split__primary").click
self
end
@@ -36,8 +36,10 @@ module PageObjects
end
def click_save_and_run
- page.find(".query-run .query-run__save-and-run").click
- self
+ # Run auto-saves when dirty. Wait for the label to morph to "Save
+ # changes and run" so we know the debounced dirty flag has fired.
+ page.find(".query-run-split__primary", text: /Save changes and run/i)
+ run_query
end
def has_query_name?(text)
@@ -52,7 +54,22 @@ module PageObjects
page.has_css?(".query-results .result-header")
end
+ def show_table
+ # Chart is the default view when chartable; some assertions need rows.
+ # The input is a hidden radio inside a label, so click the label.
+ page.execute_script(<<~JS)
+ const input = document.querySelector(
+ ".query-results-modes input[value='table']"
+ );
+ if (input && !input.checked) {
+ input.closest("label").click();
+ }
+ JS
+ self
+ end
+
def has_result_row_count?(count)
+ show_table
page.has_css?(".query-results .query-result-row", count: count)
end
diff --git a/plugins/discourse-data-explorer/spec/system/query_runner_spec.rb b/plugins/discourse-data-explorer/spec/system/query_runner_spec.rb
index afc06352f1d..2730c27a56e 100644
--- a/plugins/discourse-data-explorer/spec/system/query_runner_spec.rb
+++ b/plugins/discourse-data-explorer/spec/system/query_runner_spec.rb
@@ -22,9 +22,8 @@ RSpec.describe "Data explorer query runner" do
it "clears results from a previously run query" do
visit("/admin/plugins/discourse-data-explorer/queries/#{query_a.id}")
- find(".query-run .btn-primary").click
+ find(".query-run-split__primary").click
expect(page).to have_css(".query-results .result-header")
- expect(page).to have_css(".query-results-table-wrapper.--expanded")
find(".back-button").click
first("a[href='/admin/plugins/discourse-data-explorer/queries/#{query_b.id}']").click
@@ -32,6 +31,59 @@ RSpec.describe "Data explorer query runner" do
end
end
+ context "with the edit page layout" do
+ fab!(:query) { Fabricate(:query, name: "Layout query", sql: "SELECT 1", user: admin) }
+
+ it "shows the SQL editor with Help in the action bar (no Edit toggle)" do
+ visit("/admin/plugins/discourse-data-explorer/queries/#{query.id}")
+
+ expect(page).to have_no_css(".btn-edit-query")
+ expect(page).to have_css(".query-action-bar__left .query-action-bar__help")
+ expect(page).to have_css(".query-action-bar__left .query-run-split__primary")
+ end
+
+ it "puts Discard on the left and Delete on the right of the action bar" do
+ visit("/admin/plugins/discourse-data-explorer/queries/#{query.id}")
+
+ expect(page).to have_css(".query-action-bar__left .btn-discard-query[disabled]")
+ expect(page).to have_css(".query-action-bar__right .btn-danger")
+ expect(page).to have_no_css(".btn-save-query")
+ expect(page).to have_no_css(".query-footer-actions")
+ end
+
+ it "switches the Run button label to 'Save changes and run' when dirty" do
+ visit("/admin/plugins/discourse-data-explorer/queries/#{query.id}")
+
+ expect(page).to have_css(".query-run-split__primary", text: I18n.t("js.explorer.run"))
+
+ PageObjects::Components::AceEditor.new.set_input("SELECT 2")
+
+ expect(page).to have_css(".query-run-split__primary", text: I18n.t("js.explorer.saverun"))
+ end
+
+ it "renders the chart/table toggle + Export-as dropdown in the action bar after results load" do
+ visit("/admin/plugins/discourse-data-explorer/queries/#{query.id}")
+ find(".query-run-split__primary").click
+
+ expect(page).to have_css(".query-action-bar__right .query-results-modes")
+ expect(page).to have_css(".query-action-bar__right .query-result-download-buttons")
+
+ find(".query-action-bar__right .query-result-download-buttons").click
+
+ expect(page).to have_css(".query-result-export__results-json")
+ expect(page).to have_css(".query-result-export__results-csv")
+ expect(page).to have_css(".query-result-export__query-json")
+ end
+
+ it "hides Edit/Save/Discard on default queries" do
+ visit("/admin/plugins/discourse-data-explorer/queries/-1")
+
+ expect(page).to have_no_css(".btn-edit-query")
+ expect(page).to have_no_css(".btn-save-query")
+ expect(page).to have_no_css(".btn-discard-query")
+ end
+ end
+
context "with a query using a default param" do
fab!(:query_1) do
Fabricate(
diff --git a/plugins/discourse-data-explorer/spec/system/reports_spec.rb b/plugins/discourse-data-explorer/spec/system/reports_spec.rb
index c67a2677f62..1e0fbac6b12 100644
--- a/plugins/discourse-data-explorer/spec/system/reports_spec.rb
+++ b/plugins/discourse-data-explorer/spec/system/reports_spec.rb
@@ -34,7 +34,6 @@ RSpec.describe "Reports" do
expect(page).not_to have_css(".query-results .result-header")
find(".query-run .btn-primary").click
expect(page).to have_css(".query-results .result-header")
- expect(page).to have_css(".query-results-table-wrapper.--expanded")
find(".group-reports-nav-item-outlet a").click
all(".group-reports a ").last.click
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js
index cd952c1f34f..f18263eeb2b 100644
--- a/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/param-input-test.js
@@ -5,7 +5,7 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import selectKit from "discourse/tests/helpers/select-kit-helper";
async function runQuery() {
- await click("form.query-run button");
+ await click(".query-run-split__primary, form.query-run button");
}
acceptance("Param Input", function (needs) {
@@ -325,6 +325,21 @@ acceptance("Param Input", function (needs) {
});
});
+ server.post("/admin/plugins/discourse-data-explorer/queries/3/run", () => {
+ return helper.response({
+ success: true,
+ errors: [],
+ duration: 1.0,
+ result_count: 1,
+ params: { months_ago: "1" },
+ columns: ["?column?"],
+ default_limit: 1000,
+ relations: {},
+ colrender: {},
+ rows: [[1]],
+ });
+ });
+
server.get("/admin/plugins/discourse-data-explorer/queries/4", () => {
return helper.response({
query: {
@@ -383,13 +398,13 @@ acceptance("Param Input", function (needs) {
'/admin/plugins/discourse-data-explorer/queries/-7?params={"user":null}'
);
assert.dom(".query-params .user-chooser").exists();
- assert.dom(".query-run .btn.btn-primary").exists();
+ assert.dom(".query-run-split__primary").exists();
});
test("loads the page if one of the parameter is null for group reports", async function (assert) {
await visit('/g/discourse/reports/-8?params={"months_ago":null}');
assert.dom(".query-params input").exists();
- assert.dom(".query-run .btn.btn-primary").exists();
+ assert.dom(".query-run__submit").exists();
});
test("applies params when running a report", async function (assert) {
@@ -403,13 +418,11 @@ acceptance("Param Input", function (needs) {
test("creates input boxes if has parameters when save", async function (assert) {
await visit("/admin/plugins/discourse-data-explorer/queries/3");
assert.dom(".query-params input").doesNotExist();
- await click(".query-run-actions .btn-edit-query");
await fillIn(
".query-editor .ace_text-input",
"-- [params]\n-- int :months_ago = 1\n\nSELECT 1"
);
- await click(".query-editor .ace_text-input"); // enables `Save Changes` button
- await click(".query-run-actions .btn-save-query");
+ await click(".query-run-split__primary");
assert.dom(".query-params input").exists();
});
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js
index 83540df54af..e4c1eabc71b 100644
--- a/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/run-query-test.js
@@ -296,16 +296,19 @@ acceptance("Run Query", function (needs) {
assert.dom("div.query-edit").exists("the query code was rendered");
assert
- .dom("form.query-run button span")
+ .dom(".query-run-split__primary span")
.hasText(i18n("explorer.run"), "the run button was rendered");
- await click("form.query-run button");
+ await click(".query-run-split__primary");
+
+ assert.dom("canvas").exists("the chart was rendered by default");
+
+ await click(".query-results-modes input[value='table']");
assert
.dom("div.query-results table tbody tr")
.exists({ count: 2 }, "the table with query results was rendered");
- assert.dom("canvas").exists("the chart was rendered");
assert
.dom(".query-results-modes")
.exists("the chart/table toggle buttons were rendered");
@@ -314,7 +317,7 @@ acceptance("Run Query", function (needs) {
test("runs query and is able to download the results", async function (assert) {
await visit("/admin/plugins/discourse-data-explorer/queries/-6");
- await click("form.query-run button");
+ await click(".query-run-split__primary");
const createElement = document.createElement.bind(document);
const appendChild = document.body.appendChild.bind(document.body);
@@ -357,9 +360,8 @@ acceptance("Run Query", function (needs) {
}
});
- await click(
- ".query-run-actions__right .query-result-download-buttons button:nth-child(1)"
- );
+ await click(".query-action-bar__right .query-result-download-buttons");
+ await click(".query-result-export__results-json");
await finishedForm;
@@ -392,10 +394,15 @@ acceptance("Run Query", function (needs) {
.hasText("What about 0?", "the query name was rendered");
assert
- .dom("form.query-run button span")
+ .dom(".query-run-split__primary span")
.hasText(i18n("explorer.run"), "the run button was rendered");
- await click("form.query-run button");
+ await click(".query-run-split__primary");
+
+ // Default view is chart for chartable data; switch to table to inspect cells.
+ if (document.querySelector(".query-results-modes input[value='table']")) {
+ await click(".query-results-modes input[value='table']");
+ }
assert
.dom("div.query-results tbody td:nth-child(1)")
@@ -413,9 +420,7 @@ acceptance("Run Query", function (needs) {
test("automatically runs query when run query parameter is present", async function (assert) {
await visit("/admin/plugins/discourse-data-explorer/queries/2?run");
- assert
- .dom("div.query-results table tbody tr")
- .exists({ count: 1 }, "query results should be displayed");
+ assert.dom("div.query-results").exists("query results should be displayed");
});
test("automatically runs query when run query parameter is present on group report route", async function (assert) {
diff --git a/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs b/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs
index 210ac6ae580..23fe0bed90d 100644
--- a/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs
+++ b/plugins/discourse-data-explorer/test/javascripts/components/explorer-schema-test.gjs
@@ -40,20 +40,10 @@ module("Component | explorer-schema", function (hooks) {
setupRenderingTest(hooks);
test("will automatically convert to lowercase", async function (assert) {
- this.setProperties({
- schema,
- hideSchema: false,
- updateHideSchema: () => {},
- });
+ this.setProperties({ schema });
await render(
- <template>
- <ExplorerSchema
- @schema={{this.schema}}
- @hideSchema={{this.hideSchema}}
- @updateHideSchema={{this.updateHideSchema}}
- />
- </template>
+ <template><ExplorerSchema @schema={{this.schema}} /></template>
);
await fillIn(`.schema-search input`, "Cat");
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
index fb94046fb3a..f5fceb461d8 100644
--- a/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/query-result-test.gjs
@@ -20,20 +20,26 @@ module("Integration | Component | query-result", function (hooks) {
await render(<template><QueryResult @content={{content}} /></template>);
+ await click(".result-actions .query-result-download-buttons");
+
assert
- .dom(
- ".result-info .query-result-download-buttons button:nth-child(1) span"
- )
- .hasText(i18n("explorer.download_json"), "renders the JSON button");
+ .dom(".query-result-export__results-json")
+ .hasText(
+ i18n("explorer.export_as.results_json"),
+ "renders the Results (JSON) item"
+ );
assert
- .dom(
- ".result-info .query-result-download-buttons button:nth-child(2) span"
- )
- .hasText(i18n("explorer.download_csv"), "renders the CSV button");
+ .dom(".query-result-export__results-csv")
+ .hasText(
+ i18n("explorer.export_as.results_csv"),
+ "renders the Results (CSV) item"
+ );
assert.dom("div.result-about").exists("renders a query summary");
- assert.dom("canvas").exists("renders the chart above the table");
+ assert.dom("canvas").exists("renders the chart by default");
+
+ await click(".query-results-modes input[value='table']");
assert.dom("table thead tr th:nth-child(1)").hasText("user_name");
assert.dom("table thead tr th:nth-child(2)").hasText("like_count");
@@ -132,7 +138,7 @@ module("Integration | Component | query-result", function (hooks) {
module("Integration | Component | query-result | chart", function (hooks) {
setupRenderingTest(hooks);
- test("renders the chart above the table for chartable results", async function (assert) {
+ test("renders the chart by default and the toggle for chartable results", async function (assert) {
const content = {
colrender: [],
result_count: 2,
@@ -145,11 +151,14 @@ module("Integration | Component | query-result | chart", function (hooks) {
await render(<template><QueryResult @content={{content}} /></template>);
- assert.dom("canvas").exists("the chart was rendered");
- assert.dom("table").exists("the table was rendered");
+ assert.dom("canvas").exists("the chart was rendered by default");
assert
.dom(".query-results-modes")
- .exists("the chart/table toggle buttons are rendered");
+ .exists("the chart/table toggle is rendered");
+
+ await click(".query-results-modes input[value='table']");
+
+ assert.dom("table").exists("table renders after switching view");
});
test("renders a chart when data has two columns and numbers in the second column", async function (assert) {
@@ -284,7 +293,7 @@ module("Integration | Component | query-result | chart", function (hooks) {
assert.dom("canvas").exists("renders a chart canvas for multi-series");
});
- test("doesn't render a chart when there are text columns alongside numeric columns", async function (assert) {
+ test("charts numeric columns and ignores text columns alongside them", async function (assert) {
const content = {
colrender: [],
result_count: 2,
@@ -297,10 +306,15 @@ module("Integration | Component | query-result | chart", function (hooks) {
await render(<template><QueryResult @content={{content}} /></template>);
- assert.dom("canvas").doesNotExist();
+ await click(".query-results-modes input[value='chart']");
+
+ assert.dom("canvas").exists("renders the chart for numeric columns");
+ assert
+ .dom(".query-results-chart__footnote")
+ .exists("shows a footnote listing ignored columns");
});
- test("toggle buttons independently show and hide chart and table", async function (assert) {
+ test("chart/table toggle switches the view (XOR)", async function (assert) {
const content = {
colrender: [],
result_count: 2,
@@ -313,23 +327,21 @@ module("Integration | Component | query-result | chart", function (hooks) {
await render(<template><QueryResult @content={{content}} /></template>);
- assert.dom("canvas").exists("chart is visible by default");
- assert.dom("table").exists("table is visible by default");
-
- await click(".query-results-modes .btn:first-child");
- assert.dom("canvas").doesNotExist("chart is hidden after toggle");
- assert.dom("table").exists("table remains visible");
+ assert
+ .dom("canvas")
+ .exists("chart is visible by default for chartable data");
+ assert.dom("table").doesNotExist("table hidden when chart is shown");
- await click(".query-results-modes .btn:last-child");
- assert.dom("canvas").doesNotExist("chart stays hidden");
- assert.dom("table").doesNotExist("table is hidden after toggle");
+ await click(".query-results-modes input[value='table']");
+ assert.dom("table").exists("table shown after switching");
+ assert.dom("canvas").doesNotExist("chart hidden when table is shown");
- await click(".query-results-modes .btn:first-child");
- assert.dom("canvas").exists("chart is visible again");
- assert.dom("table").doesNotExist("table stays hidden");
+ await click(".query-results-modes input[value='chart']");
+ assert.dom("canvas").exists("chart shown after switching back");
+ assert.dom("table").doesNotExist("table hidden again");
});
- test("persists toggle state per query in localStorage", async function (assert) {
+ test("persists view per query in localStorage", async function (assert) {
const query = { id: 42 };
const content = {
colrender: [],
@@ -345,27 +357,19 @@ module("Integration | Component | query-result | chart", function (hooks) {
<template><QueryResult @content={{content}} @query={{query}} /></template>
);
- assert.dom(".query-results-chart").exists("chart is visible by default");
- assert.dom(".query-results-table").exists("table is visible by default");
-
- await click(".btn-toggle-chart");
- assert
- .dom(".query-results-chart")
- .doesNotExist("chart is hidden after toggle");
+ await click(".query-results-modes input[value='table']");
+ assert.dom("table").exists("table shown after switching");
+ assert.dom("canvas").doesNotExist("chart is hidden");
await render(
<template><QueryResult @content={{content}} @query={{query}} /></template>
);
- assert
- .dom(".query-results-chart")
- .doesNotExist("chart state is restored from localStorage");
- assert
- .dom(".query-results-table")
- .exists("table state is restored from localStorage");
+ assert.dom("table").exists("table view restored from localStorage");
+ assert.dom("canvas").doesNotExist("chart still hidden after rerender");
});
- test("toggle buttons are not shown for non-chartable data", async function (assert) {
+ test("toggle is always visible when rows exist (even for non-chartable data)", async function (assert) {
const content = {
colrender: [],
result_count: 2,
@@ -375,7 +379,12 @@ module("Integration | Component | query-result | chart", function (hooks) {
await render(<template><QueryResult @content={{content}} /></template>);
- assert.dom(".query-results-modes").doesNotExist();
+ assert.dom(".query-results-modes").exists("toggle is always shown");
+
+ await click(".query-results-modes input[value='chart']");
+ assert
+ .dom(".query-chart-empty-state")
+ .exists("shows empty state for non-chartable data");
});
test("handles no results", async function (assert) {