Skip to content

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

UX: Data explorer improvements (#40605)

Natalie Tay2598983e0245
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 9c3263f7b46..225bb2e9fec 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
@@ -200,6 +200,7 @@ export default class QueriesEdit extends Component {
@action={{@controller.showHelpModal}}
@label="explorer.help.label"
@icon="circle-question"
+ @disabled={{@controller.actionsBusy}}
class="btn-transparent query-action-bar__help"
/>
{{/if}}
@@ -227,12 +228,14 @@ export default class QueriesEdit extends Component {
@action={{@controller.recover}}
@icon="arrow-rotate-left"
@label="explorer.recover"
+ @disabled={{@controller.actionsBusy}}
/>
{{else if this.showDestroyQuery}}
<DButton
@action={{@controller.destroyQuery}}
@icon="trash-can"
@label="explorer.delete"
+ @disabled={{@controller.actionsBusy}}
class="btn-danger"
/>
{{/if}}
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 c1c2ce60045..95b6f650baf 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
@@ -1,6 +1,7 @@
import { on } from "@ember/modifier";
import AceEditor from "discourse/components/ace-editor";
import BackButton from "discourse/components/back-button";
+import DSegmentedControl from "discourse/components/d-segmented-control";
import Form from "discourse/components/form";
import { and, eq } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
@@ -11,6 +12,7 @@ import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
import ExplorerSchema from "discourse/plugins/discourse-data-explorer/discourse/components/explorer-schema";
import QueryModeSwitch from "discourse/plugins/discourse-data-explorer/discourse/components/query-mode-switch";
+import QueryResult from "discourse/plugins/discourse-data-explorer/discourse/components/query-result";
export default <template>
<div class="admin-detail">
@@ -79,17 +81,53 @@ export default <template>
{{#if @controller.hasGenerated}}
<hr class="query-new__divider" />
- <label class="query-new__field-label">
- {{i18n "explorer.ai.sql_label"}}
- </label>
- <div class="query-new__sql-editor">
- <AceEditor
- @content={{@controller.generatedSql}}
- @onChange={{@controller.updateSql}}
- @mode="sql"
+ <div class="query-new__result-bar">
+ {{#if @controller.previewSucceeded}}
+ <div class="query-new__result-about">
+ {{@controller.previewResultCount}}
+ {{@controller.previewDuration}}
+ </div>
+ {{/if}}
+
+ <DSegmentedControl
+ @name="query-result-view"
+ @value={{@controller.view}}
+ @items={{@controller.viewItems}}
+ @onSelect={{@controller.setView}}
+ @translatedLabel={{i18n "explorer.view.label"}}
+ class="query-results-modes"
/>
</div>
+ {{#if (eq @controller.view "sql")}}
+ <div class="query-new__sql-editor">
+ <AceEditor
+ @content={{@controller.generatedSql}}
+ @onChange={{@controller.updateSql}}
+ @mode="sql"
+ @resizable={{true}}
+ />
+ </div>
+ {{else}}
+ <div class="query-new__preview query-results">
+ {{#if @controller.previewLoading}}
+ <DConditionalLoadingSpinner @condition={{true}} />
+ {{else if @controller.previewSucceeded}}
+ <QueryResult
+ @content={{@controller.previewResults}}
+ @view={{@controller.view}}
+ @onSetView={{@controller.setView}}
+ @hideHeaderActions={{true}}
+ @showDownloads={{false}}
+ />
+ {{else if @controller.showPreview}}
+ {{#each @controller.previewResults.errors as |err|}}
+ <pre class="query-error"><code>{{~err}}</code></pre>
+ {{/each}}
+ {{/if}}
+ </div>
+ {{/if}}
+
<div class="query-new__fields">
<label class="query-new__field-label">
{{i18n "explorer.query_name"}}
@@ -114,11 +152,18 @@ export default <template>
</div>
<div class="query-new__actions">
+ <DButton
+ @action={{@controller.runPreview}}
+ @icon="play"
+ @label="explorer.run"
+ @disabled={{@controller.previewDisabled}}
+ class="btn-default query-new__run-btn"
+ />
<DButton
@action={{@controller.saveQuery}}
@label="explorer.ai.save_query"
@disabled={{@controller.aiGenerating}}
- class="btn-default"
+ class="btn-primary query-new__save-btn"
/>
</div>
{{/if}}
diff --git a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
index f43436b571f..4cf76ed6a3e 100644
--- a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
@@ -183,6 +183,30 @@ module DiscourseDataExplorer
render json: { generation_id: generation_id, status: "generating" }
end
+ def preview
+ rate_limit_query_runs!
+
+ sql = params.require(:sql)
+ query = DiscourseDataExplorer::Query.new(sql:, name: params[:name].presence || "preview")
+
+ explain = params[:explain] == "true"
+ limit =
+ fetch_limit_from_params(
+ default: SiteSetting.data_explorer_query_result_limit,
+ max: QUERY_RESULT_MAX_LIMIT,
+ )
+
+ result = QueryRunner.run(query, params[:params], current_user:, explain:, limit:)
+
+ if result[:error]
+ render json: format_query_error(result[:error]), status: :unprocessable_entity
+ else
+ render json: result
+ end
+ rescue MultiJson::ParseError
+ render_invalid_json_params
+ end
+
def update
sql_changed = @query.sql != params.dig(:query, :sql)
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 76305a9acb7..10b832b70c5 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
@@ -12,7 +12,7 @@ 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 { chartability, looksLikeDate } from "../lib/chart-helpers";
+import { chartability, defaultView, 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";
@@ -64,9 +64,7 @@ export default class QueryResult extends Component {
if (stored === "chart" || stored === "table") {
this.internalView = stored;
} else {
- this.internalView = chartability(this.args.content).chartable
- ? "chart"
- : "table";
+ this.internalView = defaultView(this.args.content);
}
}
@@ -98,10 +96,6 @@ export default class QueryResult extends Component {
@action
checkOverflow(element) {
- if (!this.chartVisible) {
- this.tableExpanded = true;
- return;
- }
this.hasOverflow = element.scrollHeight > element.clientHeight;
}
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 82d0c6ab213..0ac15a0aa73 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
@@ -12,7 +12,7 @@ import { i18n } from "discourse-i18n";
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 { subscribeToAiGeneration } from "discourse/plugins/discourse-data-explorer/discourse/lib/ai-generation";
-import { chartability } from "discourse/plugins/discourse-data-explorer/discourse/lib/chart-helpers";
+import { defaultView } 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_");
@@ -86,12 +86,19 @@ export default class PluginsExplorerController extends Controller {
current.group_ids !== this._pristine.group_ids;
}
+ // While a query is running (or AI is generating) the actions in the action
+ // bar shouldn't be usable — the interstitial "Save changes and run" state
+ // is confusing otherwise.
+ get actionsBusy() {
+ return this.loading || this.aiGenerating;
+ }
+
get saveDisabled() {
- return !this.dirty;
+ return !this.dirty || this.actionsBusy;
}
get runDisabled() {
- return this.model.destroyed;
+ return this.model.destroyed || this.actionsBusy;
}
get parsedParams() {
@@ -165,7 +172,7 @@ export default class PluginsExplorerController extends Controller {
} else if (this.mode === "ai" && !this.hasResults) {
this.view = "sql";
} else {
- this.view = chartability(this.results).chartable ? "chart" : "table";
+ this.view = defaultView(this.results);
}
}
@@ -496,9 +503,7 @@ export default class PluginsExplorerController extends Controller {
// After a successful run, jump out of the SQL view so the user sees
// the results they just asked for.
if (this.view === "sql") {
- this.setView(
- chartability(this.results).chartable ? "chart" : "table"
- );
+ this.setView(defaultView(this.results));
} else {
this.initView();
}
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 6aada521d51..ad79b7c6284 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
@@ -4,8 +4,9 @@ import { action } from "@ember/object";
import { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import { i18n } from "discourse-i18n";
+import I18n, { i18n } from "discourse-i18n";
import { subscribeToAiGeneration } from "discourse/plugins/discourse-data-explorer/discourse/lib/ai-generation";
+import { defaultView } from "discourse/plugins/discourse-data-explorer/discourse/lib/chart-helpers";
export default class AdminPluginsExplorerNew extends Controller {
@service store;
@@ -24,10 +25,57 @@ export default class AdminPluginsExplorerNew extends Controller {
@tracked mode = "ai";
@tracked schema = null;
@tracked manualSql = "SELECT 1";
+ @tracked previewLoading = false;
+ @tracked previewResults = null;
+ @tracked showPreview = false;
+ @tracked view = "sql";
manualFormData = { name: "", description: "" };
_teardownAiGeneration = null;
+ get previewDisabled() {
+ return (
+ this.aiGenerating || this.previewLoading || !this.generatedSql.trim()
+ );
+ }
+
+ get viewItems() {
+ return [
+ { value: "chart", icon: "signal" },
+ { value: "table", icon: "table" },
+ { value: "sql", icon: "code" },
+ ];
+ }
+
+ get previewSucceeded() {
+ return this.showPreview && this.previewResults?.success;
+ }
+
+ get previewResultCount() {
+ if (!this.previewSucceeded) {
+ return null;
+ }
+ const count = this.previewResults.result_count;
+ if (count === this.previewResults.default_limit) {
+ return i18n("explorer.max_result_count", { count });
+ }
+ return i18n("explorer.result_count", { count });
+ }
+
+ get previewDuration() {
+ if (!this.previewSucceeded) {
+ return null;
+ }
+ return i18n("explorer.run_time", {
+ value: I18n.toNumber(this.previewResults.duration, { precision: 1 }),
+ });
+ }
+
+ @action
+ setView(value) {
+ this.view = value;
+ }
+
get aiQueriesEnabled() {
return this.siteSettings.data_explorer_ai_queries_enabled;
}
@@ -83,6 +131,8 @@ export default class AdminPluginsExplorerNew extends Controller {
this._teardownAi();
this.aiGenerating = true;
+ this.showPreview = false;
+ this.previewResults = null;
try {
const response = await ajax(
@@ -105,6 +155,9 @@ export default class AdminPluginsExplorerNew extends Controller {
this.generatedDescription = data.description;
this.hasGenerated = true;
this.aiGenerating = false;
+ // prioritise the result: run straight away so the data is what the
+ // user sees, with the SQL one tab away
+ this.runPreview();
},
onError: (data) => {
this.aiGenerating = false;
@@ -127,6 +180,43 @@ export default class AdminPluginsExplorerNew extends Controller {
}
}
+ @action
+ async runPreview() {
+ if (this.previewDisabled) {
+ return;
+ }
+
+ this.previewLoading = true;
+ this.showPreview = false;
+
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-data-explorer/queries/preview.json",
+ {
+ type: "POST",
+ data: {
+ sql: this.generatedSql,
+ name: this.generatedName || undefined,
+ },
+ }
+ );
+ this.previewResults = result;
+ this.showPreview = true;
+ if (result.success && this.view === "sql") {
+ this.view = defaultView(result);
+ }
+ } catch (error) {
+ if (error.jqXHR?.status === 422 && error.jqXHR.responseJSON) {
+ this.previewResults = error.jqXHR.responseJSON;
+ this.showPreview = true;
+ } else {
+ popupAjaxError(error);
+ }
+ } finally {
+ this.previewLoading = false;
+ }
+ }
+
@action
async saveQuery() {
try {
@@ -141,9 +231,12 @@ export default class AdminPluginsExplorerNew extends Controller {
this.toasts.success({
data: { message: i18n("explorer.query_created") },
});
+ // Run the query straight away — there's nothing new to do on the edit
+ // page first, so save and show the results in one step.
this.router.transitionTo(
"adminPlugins.show.explorer.edit",
- result.target.id
+ result.target.id,
+ { queryParams: { run: true } }
);
} catch (error) {
popupAjaxError(error);
@@ -190,5 +283,9 @@ export default class AdminPluginsExplorerNew extends Controller {
this.manualSql = "SELECT 1";
this.loading = false;
this.manualFormData = { name: "", description: "" };
+ this.previewLoading = false;
+ this.previewResults = null;
+ this.showPreview = false;
+ this.view = "sql";
}
}
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 28470e0c2a8..3e0a46c21b9 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
@@ -24,6 +24,18 @@ export function isNumericColumn(rows, colIndex) {
return false;
}
+// Picks the view to show when the user hasn't expressed a preference. A chart
+// is only a good default when every non-label column can be plotted; if
+// charting would silently drop columns (e.g. "user, username, reason, sum"),
+// the table is more honest. Users can still toggle to the chart.
+export function defaultView(content) {
+ const ability = chartability(content);
+ if (!ability.chartable || ability.ignoredColumns.length > 0) {
+ return "table";
+ }
+ return "chart";
+}
+
export function chartability(content) {
const { rows, columns, colrender = {} } = content ?? {};
if (!rows?.length) {
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index fe7fd0a7be5..5a2c1744678 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -596,25 +596,45 @@ table.group-reports {
}
.query-new__sql-editor {
- height: 200px;
- border: 1px solid var(--primary-low-mid);
- border-radius: var(--d-border-radius);
+ margin-bottom: 1.5em;
- .ace-wrapper {
- position: relative;
- height: 100%;
+ .ace-wrapper,
+ .ace-wrapper > .loading-container {
width: 100%;
}
- .ace_editor {
- position: absolute;
- left: 0;
- right: 0;
- top: 0;
- bottom: 0;
+ // the grippie lets the editor grow; give it a sensible starting height
+ .ace {
+ min-height: 200px;
+ width: 100%;
}
}
+ .query-new__result-bar {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ margin-bottom: 0.75em;
+ }
+
+ .query-new__result-about {
+ margin-right: auto;
+ color: var(--primary-medium);
+ }
+
+ // the count is shown in the result bar instead, on the same line as the toggle
+ .query-new__preview .result-meta {
+ display: none;
+ }
+
+ .query-new__fields {
+ margin-top: 1.5em;
+ }
+
+ .query-new__preview {
+ margin-top: 0.5em;
+ }
+
.query-new__field-label {
display: block;
font-weight: 700;
@@ -797,7 +817,9 @@ table.group-reports {
.query-results-table-wrapper {
overflow: auto;
- max-height: 350px;
+
+ // cap a long table at the chart height so the actions below stay reachable
+ max-height: clamp(200px, 50vh, 350px);
&.--expanded {
max-height: none;
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index 6eccb7b8120..97f2f9588ca 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -44,7 +44,7 @@ en:
regenerate_placeholder: "e.g. Update the query to limit to 50 results"
prompt_label: "Prompt"
generate: "Generate"
- regenerate: "Re-generate"
+ regenerate: "Update prompt"
generating: "Generating query with AI..."
generation_timeout: "AI query generation timed out. You can write the SQL manually."
generation_error: "Something went wrong generating the query."
diff --git a/plugins/discourse-data-explorer/config/routes.rb b/plugins/discourse-data-explorer/config/routes.rb
index fed808138c8..2391d1c4697 100644
--- a/plugins/discourse-data-explorer/config/routes.rb
+++ b/plugins/discourse-data-explorer/config/routes.rb
@@ -10,6 +10,7 @@ DiscourseDataExplorer::Engine.routes.draw do
get "schema" => "query#schema"
get "groups" => "query#groups"
post "queries/generate" => "query#generate_with_ai"
+ post "queries/preview" => "query#preview"
post "queries" => "query#create"
put "queries/:id" => "query#update"
delete "queries/:id" => "query#destroy"
@@ -42,6 +43,7 @@ Discourse::Application.routes.draw do
get "/admin/plugins/explorer/groups" => "discourse_data_explorer/query#groups"
post "/admin/plugins/explorer/queries/generate" =>
"discourse_data_explorer/query#generate_with_ai"
+ post "/admin/plugins/explorer/queries/preview" => "discourse_data_explorer/query#preview"
post "/admin/plugins/explorer/queries" => "discourse_data_explorer/query#create"
put "/admin/plugins/explorer/queries/:id" => "discourse_data_explorer/query#update"
delete "/admin/plugins/explorer/queries/:id" => "discourse_data_explorer/query#destroy"
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_runner.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_runner.rb
index b47d441a57f..53e9758ed07 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_runner.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_runner.rb
@@ -15,7 +15,7 @@ module DiscourseDataExplorer
result_json =
ResultFormatConverter.convert(:json, result, query_params:, explain:, current_user:)
- if cacheable?(query, explain:) && default_limit?(limit)
+ if query.id.present? && cacheable?(query, explain:) && default_limit?(limit)
cache_key_params = resolve_params(query, raw_params)
QueryResultCache.write(query.id, cache_key_params, result_json)
end
diff --git a/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb b/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb
index 8ffcb48fdae..fb33a4de764 100644
--- a/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb
+++ b/plugins/discourse-data-explorer/spec/requests/query_controller_spec.rb
@@ -538,6 +538,45 @@ describe DiscourseDataExplorer::QueryController do
end
end
+ describe "#preview" do
+ it "runs unsaved SQL and returns the result" do
+ post "/admin/plugins/discourse-data-explorer/queries/preview.json",
+ params: {
+ sql: "SELECT 23 AS my_value",
+ }
+
+ expect(response.status).to eq(200)
+ expect(response_json["success"]).to eq(true)
+ expect(response_json["columns"]).to eq(["my_value"])
+ expect(response_json["rows"]).to eq([[23]])
+ end
+
+ it "does not persist a query" do
+ expect {
+ post "/admin/plugins/discourse-data-explorer/queries/preview.json",
+ params: {
+ sql: "SELECT 23 AS my_value",
+ }
+ }.not_to change { DiscourseDataExplorer::Query.count }
+ end
+
+ it "returns a 422 with errors for invalid SQL" do
+ post "/admin/plugins/discourse-data-explorer/queries/preview.json",
+ params: {
+ sql: "SELECT * FROM table_that_does_not_exist",
+ }
+
+ expect(response.status).to eq(422)
+ expect(response_json["success"]).to eq(false)
+ expect(response_json["errors"]).not_to be_empty
+ end
+
+ it "requires the sql parameter" do
+ post "/admin/plugins/discourse-data-explorer/queries/preview.json"
+ expect(response.status).to eq(400)
+ end
+ end
+
describe "result caching" do
def run_query(id, params = {})
params = Hash[params.map { |a| [a[0], a[1].to_s] }]
@@ -733,6 +772,14 @@ describe DiscourseDataExplorer::QueryController do
expect(response.status).to eq(403)
end
+ it "cannot preview unsaved SQL" do
+ post "/admin/plugins/discourse-data-explorer/queries/preview.json",
+ params: {
+ sql: "SELECT 1 as value",
+ }
+ expect(response.status).to eq(403)
+ end
+
describe "#group_reports_index" do
it "only returns queries that the group has access to" do
group.add(user)
diff --git a/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js b/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js
index ef7bace2283..19206971c63 100644
--- a/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js
+++ b/plugins/discourse-data-explorer/test/javascripts/acceptance/new-query-test.js
@@ -1,6 +1,9 @@
-import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
+import { click, currentURL, fillIn, settled, visit } from "@ember/test-helpers";
import { test } from "qunit";
-import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import {
+ acceptance,
+ publishToMessageBus,
+} from "discourse/tests/helpers/qunit-helpers";
acceptance("New Query", function (needs) {
needs.user();
@@ -111,3 +114,168 @@ acceptance("New Query", function (needs) {
);
});
});
+
+acceptance("New Query - AI", function (needs) {
+ needs.user();
+ needs.settings({
+ data_explorer_enabled: true,
+ data_explorer_ai_queries_enabled: true,
+ });
+
+ const GENERATION_ID = "test-generation";
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/plugins/discourse-data-explorer.json", () => {
+ return helper.response({
+ id: "discourse-data-explorer",
+ name: "discourse-data-explorer",
+ enabled: true,
+ has_settings: true,
+ humanized_name: "Data Explorer",
+ is_discourse_owned: true,
+ admin_route: {
+ label: "explorer.title",
+ location: "discourse-data-explorer",
+ use_new_show_route: true,
+ },
+ });
+ });
+
+ server.get("/admin/plugins/discourse-data-explorer/groups.json", () =>
+ helper.response([])
+ );
+ server.get("/admin/plugins/discourse-data-explorer/schema.json", () =>
+ helper.response({ topics: [] })
+ );
+ server.get("/admin/plugins/discourse-data-explorer/queries", () =>
+ helper.response({ queries: [] })
+ );
+
+ server.post(
+ "/admin/plugins/discourse-data-explorer/queries/generate.json",
+ () =>
+ helper.response({ generation_id: GENERATION_ID, status: "generating" })
+ );
+
+ server.post(
+ "/admin/plugins/discourse-data-explorer/queries/preview.json",
+ () =>
+ helper.response({
+ success: true,
+ errors: [],
+ colrender: [],
+ result_count: 1,
+ columns: ["my_value"],
+ rows: [[23]],
+ duration: 1.2,
+ default_limit: 1000,
+ })
+ );
+
+ server.post("/admin/plugins/discourse-data-explorer/queries", () =>
+ helper.response({
+ query: {
+ id: -15,
+ sql: "SELECT 23 AS my_value",
+ name: "Generated",
+ description: "",
+ param_info: [],
+ group_ids: [],
+ hidden: false,
+ user_id: -1,
+ },
+ })
+ );
+
+ server.get("/admin/plugins/discourse-data-explorer/queries/-15", () =>
+ helper.response({
+ query: {
+ id: -15,
+ sql: "SELECT 23 AS my_value",
+ name: "Generated",
+ description: "",
+ param_info: [],
+ group_ids: [],
+ hidden: false,
+ user_id: -1,
+ },
+ })
+ );
+
+ server.post("/admin/plugins/discourse-data-explorer/queries/-15/run", () =>
+ helper.response({
+ success: true,
+ errors: [],
+ colrender: [],
+ result_count: 1,
+ columns: ["my_value"],
+ rows: [[23]],
+ duration: 1.2,
+ default_limit: 1000,
+ })
+ );
+ });
+
+ async function generate(prompt) {
+ await visit("/admin/plugins/discourse-data-explorer/queries/new");
+ await fillIn(".query-new__ai-textarea", prompt);
+ await click(".query-new__generate-btn");
+ await publishToMessageBus(
+ `/discourse-data-explorer/queries/ai-generation/${GENERATION_ID}`,
+ {
+ generation_id: GENERATION_ID,
+ status: "complete",
+ sql: "SELECT 23 AS my_value",
+ name: "Generated",
+ description: "",
+ }
+ );
+ await settled();
+ }
+
+ test("save query is the primary action and the result is shown first", async function (assert) {
+ await generate("show me a value");
+
+ assert
+ .dom(".query-new__save-btn.btn-primary")
+ .exists("the save query button gets the primary treatment");
+ assert
+ .dom(".query-new__run-btn")
+ .exists("a run button is available before saving");
+ assert
+ .dom(".query-results-modes")
+ .exists("a chart/table/sql segmented control is shown");
+ assert
+ .dom(".query-new__result-bar .query-new__result-about")
+ .hasText(
+ /result/,
+ "the result count sits on the same line as the toggle"
+ );
+ assert
+ .dom(".query-new__preview .query-results-table-wrapper")
+ .exists("the result is run and shown first, not the SQL");
+
+ await click(".query-results-modes input[value='sql']");
+
+ assert
+ .dom(".query-new__sql-editor .ace-wrapper")
+ .exists("the SQL is available behind its own tab");
+ });
+
+ test("saving transitions to the edit page and runs the query", async function (assert) {
+ await generate("show me a value");
+
+ await click(".query-new__save-btn");
+
+ assert.true(
+ currentURL().startsWith(
+ "/admin/plugins/discourse-data-explorer/queries/-15"
+ ),
+ "transitions to the saved query"
+ );
+ assert.true(
+ currentURL().includes("run=true"),
+ "carries the auto-run flag so the query runs immediately"
+ );
+ });
+});
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 111075bff79..6df6e8852fa 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
@@ -228,6 +228,28 @@ module("Integration | Component | QueryResult | Chart", function (hooks) {
assert.dom("canvas").exists();
});
+ test("defaults to the table when charting would drop columns", async function (assert) {
+ const content = {
+ colrender: [],
+ result_count: 2,
+ columns: ["user", "reason", "count"],
+ rows: [
+ ["user1", "spam", 10],
+ ["user2", "off-topic", 5],
+ ],
+ };
+
+ await render(<template><QueryResult @content={{content}} /></template>);
+
+ assert
+ .dom("table")
+ .exists("table is the default when some columns can't be charted");
+ assert.dom("canvas").doesNotExist("chart is not shown by default");
+
+ await click(".query-results-modes input[value='chart']");
+ assert.dom("canvas").exists("chart is still available via the toggle");
+ });
+
test("doesn't render a chart when all non-label columns are relation types", async function (assert) {
const content = {
colrender: { 1: "user", 2: "badge" },
@@ -314,6 +336,40 @@ module("Integration | Component | QueryResult | Chart", function (hooks) {
.exists("shows a footnote listing ignored columns");
});
+ test("caps a long table and reveals it with the expand button", async function (assert) {
+ const rows = Array.from({ length: 100 }, (_, i) => [`user${i}`, i]);
+ const content = {
+ colrender: [],
+ result_count: rows.length,
+ columns: ["user_name", "like_count"],
+ rows,
+ };
+
+ await render(
+ <template>
+ <div class="query-results">
+ <QueryResult @content={{content}} @view="table" />
+ </div>
+ </template>
+ );
+
+ assert
+ .dom(".query-results-table-wrapper")
+ .doesNotHaveClass("--expanded", "the long table is capped by default");
+ assert
+ .dom(".query-results-expand-btn")
+ .exists("an expand button is offered for the overflowing table");
+
+ await click(".query-results-expand-btn");
+
+ assert
+ .dom(".query-results-table-wrapper.--expanded")
+ .exists("clicking expand removes the height cap");
+ assert
+ .dom(".query-results-expand-btn")
+ .doesNotExist("the expand button is gone once expanded");
+ });
+
test("chart/table toggle switches the view (XOR)", async function (assert) {
const content = {
colrender: [],