The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Check Metabot's chart types against the query's columns
Andrei Simionescub53ef0701621
diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljcindex ce073b6f4b6..bb2cd882431 100644--- a/src/metabase/lib/core.cljc+++ b/src/metabase/lib/core.cljc@@ -1709,7 +1709,8 @@temporal-bucketwith-temporal-bucket][lib.underlying- aggregation-sourced?]+ aggregation-sourced?+ breakout-sourced?][lib.utilclause?clause-of-type?diff --git a/src/metabase/metabot/tools/charts/create.clj b/src/metabase/metabot/tools/charts/create.cljindex d92d97d4aff..ed00aed8e89 100644--- a/src/metabase/metabot/tools/charts/create.clj+++ b/src/metabase/metabot/tools/charts/create.clj@@ -2,6 +2,7 @@"Tool for creating charts from queries."(:require[metabase.metabot.agent.links :as links]+ [metabase.metabot.tools.charts.fit :as fit][metabase.metabot.tools.recoverable.common :as recoverable.common][metabase.util.log :as log]))@@ -36,7 +37,8 @@- :query-id - ID of the source query- :reactions - Navigation action to show the chart- Throws [[recoverable.common/unknown-query-id!]] for a query ID that `queries-state` doesn't hold."+ Throws [[recoverable.common/unknown-query-id!]] for a query ID that `queries-state` doesn't hold, and+ [[fit/incompatible-chart-type!]] for a chart type that can't show the query's columns."[{:keys [query-id chart-type queries-state]}](log/info "Creating chart" {:query-id query-id:chart-type chart-type@@ -48,6 +50,7 @@(when-not query(recoverable.common/unknown-query-id! {:query-id query-id:available (sort (keys queries-state))}))+ (fit/check-chart-type! chart-type query);; Create the chart and generate navigation URL(let [chart-id (str (random-uuid))results-url (links/query-and-viz-link query chart-type)diff --git a/src/metabase/metabot/tools/charts/edit.clj b/src/metabase/metabot/tools/charts/edit.cljindex 280665f2719..1e47fd54f1b 100644--- a/src/metabase/metabot/tools/charts/edit.clj+++ b/src/metabase/metabot/tools/charts/edit.clj@@ -1,6 +1,7 @@(ns metabase.metabot.tools.charts.edit"Tool for editing chart visualization settings."(:require+ [metabase.metabot.tools.charts.fit :as fit][metabase.metabot.tools.recoverable.common :as recoverable.common][metabase.util.log :as log]))@@ -45,7 +46,8 @@- :chart-link - Metabase link to the chart- :chart-type - Type of chart created- Throws [[recoverable.common/unknown-chart-id!]] for a chart ID that `charts-state` doesn't hold."+ Throws [[recoverable.common/unknown-chart-id!]] for a chart ID that `charts-state` doesn't hold, and+ [[fit/incompatible-chart-type!]] for a chart type that can't show the columns of the chart's query."[{:keys [chart-id new-chart-type charts-state query]}](log/info "Editing chart" {:chart-id chart-id :new-chart-type new-chart-type})@@ -62,6 +64,7 @@new-chart-data (-> chart-data(assoc :chart_id (str (random-uuid)))(assoc :visualization_settings {:chart_type new-chart-type}))]+ (fit/check-chart-type! new-chart-type (first (:queries chart-data))){:new-chart-data new-chart-data:result {:chart-id (:chart_id new-chart-data);; Carry the source chart's query-id/query through. `extract-charts` onlydiff --git a/src/metabase/metabot/tools/charts/fit.clj b/src/metabase/metabot/tools/charts/fit.cljnew file mode 100644index 00000000000..5da1f09088a--- /dev/null+++ b/src/metabase/metabot/tools/charts/fit.clj@@ -0,0 +1,191 @@+(ns metabase.metabot.tools.charts.fit+ "Whether a chart type can show the columns that a query returns.++ The frontend draws a Metabot chart with its default settings, and some chart types can't be drawn from some columns:+ a pie chart needs a number to measure, so over two text columns the user sees `Which columns do you want to use?`+ instead of a chart. The checks here classify columns the way `isDimension` and `isMetric` in+ `frontend/src/metabase-lib/v1/types/utils/isa.ts` do, and each one holds when the visualization's `checkRenderable`+ passes with its default settings."+ (:require+ [clojure.string :as str]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib.core :as lib]+ [metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]+ [metabase.lib.types.isa :as lib.types.isa]+ [metabase.metabot.tools.core :as tools]+ [metabase.metabot.tools.shared :as shared]+ [metabase.util :as u]+ [metabase.util.log :as log]))++(set! *warn-on-reflection* true)++(defn- aggregation? [col]+ (= :source/aggregations (:lib/source col)))++(defn- binned? [col]+ (some? ((some-fn :lib/binning :lib/original-binning) col)))++(defn- dimension? [col]+ (or (not (aggregation? col)) (binned? col)))++(defn- id-name? [col]+ (let [col-name (u/lower-case-en (:name col))]+ (or (= "id" col-name) (str/ends-with? col-name "_id") (str/ends-with? col-name "-id"))))++(defn- metric?+ "Whether `col` is a number to measure."+ [col]+ (and (not (:lib/breakout? col))+ (lib.types.isa/summable? col)+ (not (id-name? col))+ (not (binned? col))))++(defn- grouping?+ "Whether `col` is a column to group by: one that the frontend picks for a chart's categories or x-axis."+ [col]+ (and (dimension? col) (not (metric? col))))++(defn- n-of [pred cols]+ (count (filter pred cols)))++(defn- groupings-and-metrics+ "A requirement for 1 to `max-groupings` columns to group by and at least 1 number to measure."+ [max-groupings needs]+ {:needs needs+ :fits? (fn [_query cols]+ (and (<= 1 (n-of grouping? cols) max-groupings)+ (some metric? cols)))})++(def ^:private requirements+ "What each chart type, other than `table` and `object`, needs from a query's columns.+ `:needs` says it to the model, and `:fits?` checks the query and its columns. `:counts`, when there, says what the+ columns hold in the terms that `:fits?` counts them in, for the error to print. `scalar` and `gauge` show the first+ value of the first column, so they also need that column not to come from a breakout, in the last stage or an earlier+ one: a breakout's first value is one group's label rather than a result. `smartscalar` compares values over time, so+ it also needs a date as its only column to group by."+ (let [axes (groupings-and-metrics 2 "1 or 2 columns to group by and at least 1 number to measure")+ rings (groupings-and-metrics 3 "1 to 3 columns to group by and at least 1 number to measure")]+ {"bar" axes+ "line" axes+ "area" axes+ "combo" axes+ "row" axes+ "boxplot" axes+ "pie" rings+ ;; The frontend draws a pie chart with 2 or 3 columns to group by as a sunburst+ "sunburst" rings+ "waterfall" (groupings-and-metrics 1 "exactly 1 column to group by and at least 1 number to measure")+ "treemap" {:needs "a column to group by and a number to measure"+ :fits? (fn [_query cols] (and (some grouping? cols) (some metric? cols)))}+ "funnel" {:needs "exactly 1 column to group by and exactly 1 number to measure"+ :fits? (fn [_query cols] (= 1 (n-of grouping? cols) (n-of metric? cols)))}+ "scatter" {:needs (str "1 number to measure and 1 or 2 columns to plot it against, counting the number "+ "itself, or 2 or 3 numbers to measure")+ :counts (fn [cols]+ (let [metrics (n-of metric? cols)+ axes (n-of dimension? cols)]+ (str metrics " " (u/format-plural metrics "number") " to measure and " axes " "+ (u/format-plural axes "column") " to plot against, counting "+ (u/format-plural metrics "the number" "the numbers") " to measure")))+ :fits? (fn [_query cols]+ (let [metrics (n-of metric? cols)]+ (or (<= 2 metrics 3)+ (and (= 1 metrics) (<= 1 (n-of dimension? cols) 2)))))}+ "sankey" {:needs "2 columns to group by that are neither dates nor coordinates, and a number to measure"+ :fits? (fn [_query cols]+ (and (<= 2 (n-of (every-pred grouping?+ (complement lib.types.isa/temporal?)+ (complement lib.types.isa/coordinate?))+ cols))+ (some metric? cols)))}+ "pivot" {:needs "at least 2 columns, each one a breakout or an aggregation"+ :fits? (fn [_query cols]+ (and (<= 2 (count cols)) (every? (some-fn aggregation? :lib/breakout?) cols)))}+ "scalar" {:needs "a first column that isn't a breakout, since it shows that column's first value"+ :fits? (fn [query [col]] (not (lib/breakout-sourced? query col)))}+ "smartscalar" {:needs "a date as the only column to group by, and a number to measure"+ :fits? (fn [_query cols]+ (let [[grouping :as groupings] (filter grouping? cols)]+ (and (= 1 (count groupings))+ (lib.types.isa/temporal? grouping)+ (some metric? cols))))}+ "gauge" {:needs "a numeric first column that isn't a breakout, since it shows that column's first value"+ :fits? (fn [query [col]]+ (and (lib.types.isa/numeric? col)+ (not (lib.types.isa/temporal? col))+ (not (lib/breakout-sourced? query col))))}+ "progress" {:needs "a numeric column"+ :fits? (fn [_query cols] (some lib.types.isa/numeric? cols))}+ "map" {:needs "latitude and longitude columns, or a state or country column and a number to measure"+ :fits? (fn [_query cols]+ (or (and (some lib.types.isa/latitude? cols) (some lib.types.isa/longitude? cols))+ (and (some (some-fn lib.types.isa/state? lib.types.isa/country?) cols)+ (some metric? cols))))}}))++(def ^:private suggested-chart-types+ "The chart types that the error can suggest. Not `sunburst`: the frontend has no visualization of that name and+ draws a `sunburst` card as a table, while a `pie` chart draws the same rings."+ (remove #{"sunburst"} shared/chart-types))++(defn- fits?+ [chart-type query cols]+ (if-let [requirement (requirements chart-type)]+ (boolean ((:fits? requirement) query cols))+ true))++(tools/defrecoverable incompatible-chart-type!+ "The frontend can't draw the chart type from the columns that the query returns."+ {:payload [:map {:closed true}+ [:chart-type (into [:enum] (keys requirements))]+ [:columns [:int {:min 0}]]+ [:counts :string]+ [:fitting [:sequential {:min 1} (into [:enum] shared/chart-types)]]]}+ [{:keys [chart-type columns counts fitting]}]+ {:message (str "Chart type \"" chart-type "\" can't show this query's columns. "+ "It needs " (:needs (requirements chart-type)) ". "+ "The query returns " columns " " (u/format-plural columns "column") ": " counts ". "+ "Chart types that fit these columns: " (str/join ", " fitting) ".")+ :recovery [{:uses #{"construct_notebook_query"}+ :text (str "To keep this chart type, call `construct_notebook_query` with a query that returns the "+ "columns it needs.")}]})++(defn- with-result-type+ "`col` with the type of the values that the query returns in it.+ A temporal extraction such as `:month-of-year` returns integers, but lib's column metadata can keep the type of the+ date that it comes from."+ [col]+ (cond-> col+ (some lib.schema.temporal-bucketing/datetime-integer-extraction-units+ ((juxt :lib/temporal-unit :inherited-temporal-unit) col))+ (assoc :effective-type :type/Integer)))++(defn- with-returned-columns+ "`[query cols]`: `query` normalized, and the columns that it returns, or nil when they can't be worked out without+ running it."+ [query]+ (try+ (let [query (lib-be/normalize-query query)]+ (when-let [cols (when (seq query)+ (not-empty (mapv with-result-type (lib/returned-columns query))))]+ [query cols]))+ (catch Exception e+ (log/debug e "Could not work out the columns that a chart's query returns")+ nil)))++(defn- groupings-and-metrics-counts+ "What `cols` hold, as most errors print it: the columns to group by and the numbers to measure."+ [cols]+ (let [metrics (n-of metric? cols)]+ (str (n-of grouping? cols) " to group by and " metrics " " (u/format-plural metrics "number") " to measure")))++(defn check-chart-type!+ "Throw [[incompatible-chart-type!]] when the frontend can't draw `chart-type` from the columns that `query` returns.+ A query whose columns can't be known without running it, such as a SQL query, passes."+ [chart-type query]+ (when-let [[query cols] (with-returned-columns query)]+ (let [chart-type (name chart-type)]+ (when-not (fits? chart-type query cols)+ (incompatible-chart-type! {:chart-type chart-type+ :columns (count cols)+ :counts ((:counts (requirements chart-type) groupings-and-metrics-counts) cols)+ :fitting (filterv #(fits? % query cols) suggested-chart-types)})))))diff --git a/test/metabase/metabot/agent/links_test.clj b/test/metabase/metabot/agent/links_test.cljindex d4ec04249b3..2d96c589ad4 100644--- a/test/metabase/metabot/agent/links_test.clj+++ b/test/metabase/metabot/agent/links_test.clj@@ -160,7 +160,7 @@(is (= expected(-> (binding [shared/*memory-atom* (atom {:state {:queries {"q-1" query}}})](test-util/call-tool charts/create-chart-tool {:data_source {:query_id "q-1"}- :viz_settings {:chart_type "bar"}+ :viz_settings {:chart_type "table"}:title "Check-ins in July":description "Check-ins during July 2014."}))(get-in [:data-parts 0 :data :query :query :parameters])diff --git a/test/metabase/metabot/tools/charts/fit_test.clj b/test/metabase/metabot/tools/charts/fit_test.cljnew file mode 100644index 00000000000..e3f8f4e0b0a--- /dev/null+++ b/test/metabase/metabot/tools/charts/fit_test.clj@@ -0,0 +1,145 @@+(ns metabase.metabot.tools.charts.fit-test+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [medley.core :as m]+ [metabase.lib-be.core :as lib-be]+ [metabase.lib.core :as lib]+ [metabase.lib.test-metadata :as meta]+ [metabase.metabot.tools.charts.fit :as fit]+ [metabase.metabot.tools.error :as tools.error]+ [metabase.metabot.tools.shared :as shared]))++(defn- fitting-chart-types!+ "The chart types that [[fit/check-chart-type!]] accepts for `query`, separated by spaces."+ [query]+ (str/join " " (filter (fn [chart-type]+ (try+ (fit/check-chart-type! chart-type query)+ true+ (catch clojure.lang.ExceptionInfo e+ (if (= ::fit/incompatible-chart-type (:code (tools.error/classify e)))+ false+ (throw e)))))+ shared/chart-types)))++(defn- query [table]+ (lib/query meta/metadata-provider (meta/table-metadata table)))++(defn- count-by [table & columns]+ (reduce lib/breakout (lib/aggregate (query table) (lib/count)) columns))++(defn- month [column]+ (lib/with-temporal-bucket column :month))++(defn- binned [column]+ (lib/with-binning column {:strategy :default}))++(defn- with-more-than-100+ "The groups of `query` whose count is more than 100, which a second stage keeps with a filter."+ [query]+ (let [query (lib/append-stage query)]+ (lib/filter query (lib/> (m/find-first #(= "count" (:name %)) (lib/filterable-columns query)) 100))))++(def ^:private count-by-category-and-month-of-year+ "Built from MBQL 4, as the frontend sends a query, for which lib's metadata gives the month the type of its date."+ (lib-be/normalize-query meta/metadata-provider+ {:database (meta/id)+ :type :query+ :query {:source-table (meta/id :products)+ :aggregation [[:count]]+ :breakout [[:field (meta/id :products :category) nil]+ [:field (meta/id :products :created-at) {:temporal-unit :month-of-year}]]}}))++(deftest chart-type-fits-when-the-frontend-can-draw-it-test+ (testing "a chart type fits a query when the frontend draws it from the query's columns with its default settings"+ (are [q fitting] (= fitting (fitting-chart-types! q))+ (count-by :orders)+ "table scalar gauge progress object"++ (lib/aggregate (count-by :orders) (lib/sum (meta/field-metadata :orders :total)))+ "table pivot scatter scalar gauge progress object"++ (lib/aggregate (query :orders) (lib/max (meta/field-metadata :orders :created-at)))+ "table scalar object"++ (count-by :products (meta/field-metadata :products :category))+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter waterfall progress funnel object"++ (count-by :orders (month (meta/field-metadata :orders :created-at)))+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter waterfall smartscalar progress funnel object"++ (lib/aggregate (count-by :orders (month (meta/field-metadata :orders :created-at)))+ (lib/max (meta/field-metadata :orders :created-at)))+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter waterfall smartscalar progress funnel object"++ (count-by :products+ (meta/field-metadata :products :category)+ (month (meta/field-metadata :products :created-at)))+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter progress object"++ (count-by :products+ (meta/field-metadata :products :category)+ (meta/field-metadata :products :vendor)+ (month (meta/field-metadata :products :created-at)))+ "table pie sunburst treemap pivot sankey progress object"++ (count-by :products+ (meta/field-metadata :products :category)+ (meta/field-metadata :products :vendor)+ (meta/field-metadata :products :title)+ (month (meta/field-metadata :products :created-at)))+ "table treemap pivot sankey progress object"++ (reduce lib/aggregate+ (count-by :products (meta/field-metadata :products :category))+ [(lib/sum (meta/field-metadata :products :price))+ (lib/avg (meta/field-metadata :products :rating))+ (lib/max (meta/field-metadata :products :price))])+ "table bar line pie sunburst treemap boxplot area combo row pivot waterfall progress object"++ (-> (query :products)+ (lib/breakout (meta/field-metadata :products :category))+ (lib/breakout (month (meta/field-metadata :products :created-at))))+ "table pivot object"++ (lib/append-stage (count-by :products (meta/field-metadata :products :category)))+ "table bar line pie sunburst treemap boxplot area combo row scatter waterfall progress funnel object"++ (with-more-than-100 (count-by :orders (meta/field-metadata :orders :quantity)))+ "table scatter progress object"++ (query :orders)+ "table treemap sankey scalar gauge progress object"++ (lib/with-fields (query :orders) [(meta/field-metadata :orders :subtotal)+ (meta/field-metadata :orders :tax)])+ "table scatter scalar gauge progress object"++ (lib/with-fields (query :orders) [(meta/field-metadata :orders :created-at)+ (meta/field-metadata :orders :total)])+ "table bar line pie sunburst treemap boxplot area combo row scatter waterfall scalar smartscalar progress funnel object"++ (count-by :people (meta/field-metadata :people :state))+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter waterfall progress funnel object map"++ (count-by :people+ (binned (meta/field-metadata :people :latitude))+ (binned (meta/field-metadata :people :longitude)))+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter progress object map"++ (lib/with-fields (query :people) [(meta/field-metadata :people :latitude)+ (meta/field-metadata :people :longitude)+ (meta/field-metadata :people :name)])+ "table bar line pie sunburst treemap boxplot area combo row scatter waterfall scalar gauge progress object map"++ count-by-category-and-month-of-year+ "table bar line pie sunburst treemap boxplot area combo row pivot scatter sankey progress object"++ (lib/append-stage count-by-category-and-month-of-year)+ "table bar line pie sunburst treemap boxplot area combo row scatter waterfall progress object")))++(deftest any-chart-type-fits-a-sql-query-test+ (testing "the columns of a SQL query aren't known until it runs, so any chart type passes"+ (is (= (str/join " " shared/chart-types)+ (fitting-chart-types! (lib/native-query meta/metadata-provider "SELECT 1"))))))diff --git a/test/metabase/metabot/tools/charts_test.clj b/test/metabase/metabot/tools/charts_test.cljindex a99532259c0..790d02836bb 100644--- a/test/metabase/metabot/tools/charts_test.clj+++ b/test/metabase/metabot/tools/charts_test.clj@@ -5,33 +5,35 @@(:require[clojure.string :as str][clojure.test :refer :all]+ [medley.core :as m][metabase.api-scope.core :as api-scope][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.test-metadata :as meta]+ [metabase.metabot.agent.links :as links][metabase.metabot.scope :as scope][metabase.metabot.test-util :as test-util][metabase.metabot.tools :as metabot.tools][metabase.metabot.tools.charts :as charts][metabase.metabot.tools.charts.create :as create-chart-tools][metabase.metabot.tools.charts.edit :as edit-chart-tools]+ [metabase.metabot.tools.charts.fit :as fit][metabase.metabot.tools.construct :as construct][metabase.metabot.tools.recoverable.common :as recoverable.common][metabase.metabot.tools.shared :as shared][metabase.test :as mt][metabase.util.json :as json]))-;; create-chart only needs the query present in queries-state; the link builder-;; json-encodes it and `->frontend-query` passes a non-MBQL 5 value through unchanged,-;; so a stub query is enough to exercise the emission branch without a database.-(def ^:private stub-query- {:database 1 :type "query" :query {:source-table 1}})+(def ^:private count-by-category+ (-> (lib/query meta/metadata-provider (meta/table-metadata :products))+ (lib/aggregate (lib/count))+ (lib/breakout (meta/field-metadata :products :category))))(defn- run-create-chart([](run-create-chart "bar"))([chart-type]- (let [memory (atom {:state {:queries {"q-1" stub-query}}})]+ (let [memory (atom {:state {:queries {"q-1" count-by-category}}})](binding [shared/*memory-atom* memory](test-util/call-tool charts/create-chart-tool {:data_source {:query_id "q-1"}:viz_settings {:chart_type chart-type}@@ -54,7 +56,7 @@(is (= "q-1" (get-in entity [:query :id])))(is (some? (get-in entity [:query :query]))))(testing "keeps the query in structured-output so chart memory stores it for later edits"- (is (= stub-query (get-in result [:structured-output :query])))))))+ (is (= count-by-category (get-in result [:structured-output :query])))))))(deftest chart-tools-keep-mbql5-temporal-filter-test(testing "the generated_entity part carries a during filter through JSON intact (BOT-1972)"@@ -68,12 +70,12 @@:visualization_settings {:chart_type :bar}}}}](doseq [[tool-name run-tool] [["create_chart"#(test-util/call-tool charts/create-chart-tool {:data_source {:query_id "q-1"}- :viz_settings {:chart_type "bar"}+ :viz_settings {:chart_type "table"}:title "Check-ins in July":description "Check-ins during July 2026."})]["edit_chart"#(test-util/call-tool charts/edit-chart-tool {:chart_id "c-1"- :new_viz_settings {:chart_type "line"}+ :new_viz_settings {:chart_type "table"}:title "Check-ins in July":description "Check-ins during July 2026."})]]](testing tool-name@@ -115,7 +117,7 @@(deftest edit-chart-query-fallback-test(testing "edit_chart resolves the query from queries-state when chart memory has no query"- (let [memory (atom {:state {:queries {"q-1" stub-query}+ (let [memory (atom {:state {:queries {"q-1" count-by-category}:charts {"c-1" {:chart_id "c-1":query_id "q-1":queries [nil]@@ -130,14 +132,14 @@entity (:data (first parts))](is (= 1 (count parts)))(is (= "generated_entity" (:data-type (first parts))))- (is (= stub-query (get-in entity [:query :query])))+ (is (= (links/->frontend-query count-by-category) (get-in entity [:query :query])))(is (= "pie" (:display entity)))(testing "structured-output also carries the resolved query, not just data-parts";; Regression: edit-chart-tool's :query var (used for data-parts above) came;; from queries-state, but edit-chart's :result — which becomes;; structured-output and is what extract-charts stores into :charts state —;; only looked at the chart's own (here empty) :queries, landing on nil.- (is (= {:query-id "q-1" :query stub-query}+ (is (= {:query-id "q-1" :query count-by-category}(select-keys (:structured-output result) [:query-id :query])))))))(defn- invoke@@ -164,10 +166,10 @@:error {:class :recoverable :code ::recoverable.common/unknown-query-id}}(invoke "create_chart"(assoc chart-args :data_source {:query_id "q-9"} :viz_settings {:chart_type "bar"})- {:queries {"q-1" stub-query}})))))+ {:queries {"q-1" count-by-category}})))))(deftest edit-chart-unknown-chart-id-test- (let [chart (fn [chart-id] {:chart_id chart-id :query_id "q-1" :queries [stub-query]})+ (let [chart (fn [chart-id] {:chart_id chart-id :query_id "q-1" :queries [count-by-category]})args (assoc chart-args :chart_id "c-9" :new_viz_settings {:chart_type "pie"})steps ["To make a new chart, call `construct_notebook_query` and use the chart ID that it returns.""To chart a query from this conversation, call `create_chart` with its query ID."]]@@ -188,7 +190,9 @@(let [steps (str "To make a new chart, call `construct_notebook_query` and use the chart ID that it returns.\n""To chart a query from this conversation, call `create_chart` with its query ID.")charts (fn [ids]- {:charts (into {} (map (fn [id] [id {:chart_id id :query_id "q-1" :queries [stub-query]}])) ids)})+ {:charts (into {}+ (map (fn [id] [id {:chart_id id :query_id "q-1" :queries [count-by-category]}]))+ ids)})uuids (map #(format "%08d-0000-4000-8000-000000000000" %) (range 120))long-id (apply str (repeat 4100 "x"))output (fn [chart-id state]@@ -225,6 +229,155 @@{}))))(is (false? @ran?)))))+(deftest chart-tools-incompatible-chart-type-test+ (let [orders-count (lib/aggregate (lib/query meta/metadata-provider (meta/table-metadata :orders)) (lib/count))+ failure (fn [& message]+ {:output (str (apply str message)+ "\nTo keep this chart type, call `construct_notebook_query` with a query that "+ "returns the columns it needs.")+ :error {:class :recoverable :code ::fit/incompatible-chart-type}})+ line-failure (failure "Chart type \"line\" can't show this query's columns. It needs 1 or 2 columns to group "+ "by and at least 1 number to measure. The query returns 1 column: 0 to group by and 1 "+ "number to measure. Chart types that fit these columns: table, scalar, gauge, progress, "+ "object.")]+ (testing "create_chart fails on a chart type that can't show the query's columns, and names the ones that can"+ (is (= line-failure+ (invoke "create_chart"+ (assoc chart-args :data_source {:query_id "q-1"} :viz_settings {:chart_type "line"})+ {:queries {"q-1" orders-count}}))))+ (testing "edit_chart checks a chart that the user is viewing, whose query arrives as MBQL 4"+ (is (= line-failure+ (invoke "edit_chart"+ (assoc chart-args :chart_id "c-1" :new_viz_settings {:chart_type "line"})+ {:charts {"c-1" {:chart_id "c-1"+ :query_id "c-1"+ :queries [{:database (mt/id)+ :type "query"+ :query {:source-table (mt/id :orders)+ :aggregation [["count"]]}}]}}}))))+ (testing "edit_chart checks the new chart type against the query of the chart that it edits"+ (is (= (failure "Chart type \"scalar\" can't show this query's columns. It needs a first column that isn't a "+ "breakout, since it shows that column's first value. The query returns 2 columns: 1 to group by "+ "and 1 number to measure. Chart types that fit these columns: "+ "table, bar, line, pie, treemap, boxplot, area, combo, row, pivot, scatter, waterfall, progress, "+ "funnel, object.")+ (invoke "edit_chart"+ (assoc chart-args :chart_id "c-1" :new_viz_settings {:chart_type "scalar"})+ {:charts {"c-1" {:chart_id "c-1" :query_id "q-1" :queries [count-by-category]}}}))))+ (testing "a number chart of categories with more than 100 orders would show a category, the first stage's breakout"+ (let [by-category (-> (lib/aggregate (lib/query meta/metadata-provider (meta/table-metadata :products)) (lib/count))+ (lib/breakout (meta/field-metadata :products :category))+ lib/append-stage)+ query (lib/filter by-category+ (lib/> (m/find-first #(= "count" (:name %)) (lib/filterable-columns by-category)) 100))]+ (is (= (failure "Chart type \"scalar\" can't show this query's columns. It needs a first column that isn't "+ "a breakout, since it shows that column's first value. The query returns 2 columns: 1 to group "+ "by and 1 number to measure. Chart types that fit these columns: table, bar, line, pie, "+ "treemap, boxplot, area, combo, row, scatter, waterfall, progress, funnel, object.")+ (invoke "create_chart"+ (assoc chart-args :data_source {:query_id "q-1"} :viz_settings {:chart_type "scalar"})+ {:queries {"q-1" query}})))))+ (testing "a scatter error counts what the scatter check counts, so the model sees which column is one too many"+ (is (= (failure "Chart type \"scatter\" can't show this query's columns. It needs 1 number to measure and 1 "+ "or 2 columns to plot it against, counting the number itself, or 2 or 3 numbers to measure. The "+ "query returns 3 columns: 1 number to measure and 3 columns to plot against, counting the number "+ "to measure. Chart types that fit these columns: table, bar, line, pie, treemap, boxplot, area, "+ "combo, row, sankey, scalar, progress, object.")+ (invoke "create_chart"+ (assoc chart-args :data_source {:query_id "q-1"} :viz_settings {:chart_type "scatter"})+ {:queries {"q-1" (lib/with-fields (lib/query meta/metadata-provider (meta/table-metadata :products))+ [(meta/field-metadata :products :category)+ (meta/field-metadata :products :vendor)+ (meta/field-metadata :products :price)])}}))))+ (testing "construct_notebook_query checks its chart type against the query that it builds"+ (mt/with-dynamic-fn-redefs [construct/execute-representations-query+ (fn [_ & _]+ {:structured-output {:query-id "q-1" :query orders-count :result-columns []}})]+ (is (= (failure "Chart type \"pie\" can't show this query's columns. It needs 1 to 3 columns to group by "+ "and at least 1 number to measure. The query returns 1 column: 0 to group by and 1 number "+ "to measure. Chart types that fit these columns: table, scalar, gauge, progress, object.")+ (invoke "construct_notebook_query"+ (assoc chart-args+ :query {:lib/type "mbql/query" :stages []}+ :visualization {:chart_type "pie"})+ {})))))))++(deftest single-value-charts-of-several-aggregations-test+ (testing "scalar and gauge charts show the first column of a one-row result, so several aggregations fit"+ (let [count-and-sum (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))+ (lib/aggregate (lib/count))+ (lib/aggregate (lib/sum (meta/field-metadata :orders :total))))]+ (doseq [chart-type ["scalar" "gauge"]]+ (testing chart-type+ (is (=? {:data-parts [{:data {:display chart-type}}]}+ (invoke "create_chart"+ (assoc chart-args :data_source {:query_id "q-1"} :viz_settings {:chart_type chart-type})+ {:queries {"q-1" count-and-sum}})))+ (is (=? {:data-parts [{:data {:display chart-type}}]}+ (invoke "edit_chart"+ (assoc chart-args :chart_id "c-1" :new_viz_settings {:chart_type chart-type})+ {:charts {"c-1" {:chart_id "c-1" :query_id "q-1" :queries [count-and-sum]}}}))))))))++(deftest month-of-year-sankey-test+ (testing "a month of the year comes back as a number, so a sankey chart can flow from a category to it"+ (testing "for a chart that the user is viewing, whose query arrives as MBQL 4"+ (is (=? {:data-parts [{:data {:display "sankey"}}]}+ (invoke "edit_chart"+ (assoc chart-args :chart_id "c-1" :new_viz_settings {:chart_type "sankey"})+ {:charts {"c-1" {:chart_id "c-1"+ :query_id "c-1"+ :queries [{:database (mt/id)+ :type "query"+ :query {:source-table (mt/id :products)+ :aggregation [["count"]]+ :breakout [["field" (mt/id :products :category) nil]+ ["field" (mt/id :products :created_at)+ {:temporal-unit "month-of-year"}]]}}]}}}))))+ (testing "for a query that construct_notebook_query builds"+ (mt/with-current-user (mt/user->id :crowberto)+ (let [db-name (:name (mt/db))]+ (is (=? {:data-parts [{:data {:display "sankey"}}]}+ (invoke "construct_notebook_query"+ (assoc chart-args+ :query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table [db-name "PUBLIC" "PRODUCTS"]+ :aggregation [["count" {}]]+ :breakout [["field" {} [db-name "PUBLIC" "PRODUCTS" "CATEGORY"]]+ ["field" {"temporal-unit" "month-of-year"}+ [db-name "PUBLIC" "PRODUCTS" "CREATED_AT"]]]}]}+ :visualization {:chart_type "sankey"})+ {}))))))))++(deftest smartscalar-with-a-date-aggregation-test+ (testing "a trend groups by its one date, and a date aggregation beside the number to measure isn't a second grouping"+ (let [created-at (meta/field-metadata :orders :created-at)+ query (-> (lib/query meta/metadata-provider (meta/table-metadata :orders))+ (lib/aggregate (lib/count))+ (lib/aggregate (lib/max created-at))+ (lib/breakout (lib/with-temporal-bucket created-at :month)))]+ (is (=? {:data-parts [{:data {:display "smartscalar"}}]}+ (invoke "create_chart"+ (assoc chart-args :data_source {:query_id "q-1"} :viz_settings {:chart_type "smartscalar"})+ {:queries {"q-1" query}})))+ (is (=? {:data-parts [{:data {:display "smartscalar"}}]}+ (invoke "edit_chart"+ (assoc chart-args :chart_id "c-1" :new_viz_settings {:chart_type "smartscalar"})+ {:charts {"c-1" {:chart_id "c-1" :query_id "q-1" :queries [query]}}})))+ (mt/with-current-user (mt/user->id :crowberto)+ (let [db-name (:name (mt/db))+ created-at [db-name "PUBLIC" "ORDERS" "CREATED_AT"]]+ (is (=? {:data-parts [{:data {:display "smartscalar"}}]}+ (invoke "construct_notebook_query"+ (assoc chart-args+ :query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table [db-name "PUBLIC" "ORDERS"]+ :aggregation [["count" {}] ["max" {} ["field" {} created-at]]]+ :breakout [["field" {"temporal-unit" "month"} created-at]]}]}+ :visualization {:chart_type "smartscalar"})+ {}))))))))+(deftest chart-tools-undeclared-failure-test(testing "a failure that no error declares ends the turn instead of reaching the model"(mt/with-dynamic-fn-redefs [create-chart-tools/create-chart (fn [_] (throw (ex-info "boom" {})))@@ -232,7 +385,7 @@(is (=? {:error {:class :unrecoverable :code :internal}}(invoke "create_chart"(assoc chart-args :data_source {:query_id "q-1"} :viz_settings {:chart_type "bar"})- {:queries {"q-1" stub-query}})))+ {:queries {"q-1" count-by-category}})))(is (=? {:error {:class :unrecoverable :code :internal}}(invoke "edit_chart"(assoc chart-args :chart_id "c-1" :new_viz_settings {:chart_type "pie"})