Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

QP limit middleware => Lib (#62379)

Cam Saul35522222e5bb
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 6cbe6a69e18..ac3ff0e5705 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -604,6 +604,7 @@
metabase.lib.schema.actions
metabase.lib.schema.binning
metabase.lib.schema.common
+ metabase.lib.schema.constraints
metabase.lib.schema.expression
metabase.lib.schema.expression.temporal
metabase.lib.schema.expression.window
@@ -614,9 +615,11 @@
metabase.lib.schema.mbql-clause
metabase.lib.schema.metadata
metabase.lib.schema.metadata.fingerprint
+ metabase.lib.schema.middleware-options
metabase.lib.schema.order-by
metabase.lib.schema.parameter
metabase.lib.schema.ref
+ metabase.lib.schema.settings
metabase.lib.schema.template-tag
metabase.lib.schema.temporal-bucketing
metabase.lib.schema.util
diff --git a/modules/drivers/sparksql/src/metabase/driver/sparksql.clj b/modules/drivers/sparksql/src/metabase/driver/sparksql.clj
index bcd64a5bb38..f52a1d50ef4 100644
--- a/modules/drivers/sparksql/src/metabase/driver/sparksql.clj
+++ b/modules/drivers/sparksql/src/metabase/driver/sparksql.clj
@@ -158,7 +158,7 @@
(let [inner-query (-> (assoc inner-query
:remark (driver-api/query->remark :sparksql outer-query)
:query sql
- :max-rows (driver-api/query->max-rows-limit outer-query))
+ :max-rows #_{:clj-kondo/ignore [:deprecated-var]} (driver-api/query->max-rows-limit outer-query))
(dissoc :params))
query (assoc outer-query :native inner-query)]
((get-method driver/execute-reducible-query :sql-jdbc) driver query context respond)))
diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.clj
index 5fa6d197a9a..f66d0c86c1a 100644
--- a/src/metabase/driver_api/core.clj
+++ b/src/metabase/driver_api/core.clj
@@ -142,6 +142,8 @@
premium-features/is-hosted?
qp.compile/compile
qp.debug/debug>
+ ;; TODO (Cam 8/19/25) -- importing dynamic vars doesn't really work because the copies here don't pick up changes to
+ ;; the original value. We need to make these functions instead.
qp.i/*disable-qp-logging*
qp.preprocess/preprocess
qp.reducible/reducible-rows
diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljc
index c9fa681d879..685c676305b 100644
--- a/src/metabase/legacy_mbql/schema.cljc
+++ b/src/metabase/legacy_mbql/schema.cljc
@@ -12,6 +12,7 @@
[metabase.lib.schema.actions :as lib.schema.actions]
[metabase.lib.schema.binning :as lib.schema.binning]
[metabase.lib.schema.common :as lib.schema.common]
+ [metabase.lib.schema.constraints :as lib.schema.constraints]
[metabase.lib.schema.expression.temporal :as lib.schema.expression.temporal]
[metabase.lib.schema.expression.window :as lib.schema.expression.window]
[metabase.lib.schema.id :as lib.schema.id]
@@ -20,6 +21,8 @@
[metabase.lib.schema.literal :as lib.schema.literal]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.lib.schema.metadata.fingerprint :as lib.schema.metadata.fingerprint]
+ [metabase.lib.schema.middleware-options :as lib.schema.middleware-options]
+ [metabase.lib.schema.settings :as lib.schema.settings]
[metabase.lib.schema.template-tag :as lib.schema.template-tag]
[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
[metabase.util.i18n :as i18n]
@@ -1555,16 +1558,6 @@
(mr/def ::OrderBys
(helpers/distinct [:sequential {:min 1} [:ref ::OrderBy]]))
-(mr/def ::Page
- "`page` = page num, starting with 1. `items` = number of items per page.
- e.g.
-
- {:page 1, :items 10} = items 1-10
- {:page 2, :items 10} = items 11-20"
- [:map
- [:page pos-int?]
- [:items pos-int?]])
-
(mr/def ::MBQLQuery
[:and
[:map
@@ -1577,7 +1570,7 @@
[:filter {:optional true} Filter]
[:limit {:optional true} ::lib.schema.common/int-greater-than-or-equal-to-zero]
[:order-by {:optional true} [:ref ::OrderBys]]
- [:page {:optional true} [:ref ::Page]]
+ [:page {:optional true} [:ref :metabase.lib.schema/page]]
[:joins {:optional true} [:ref ::Joins]]
[:source-metadata
@@ -1656,100 +1649,6 @@
"Schema for a list of `:parameters` as passed in to a query."
[:ref ::ParameterList])
-;;; ---------------------------------------------------- Options -----------------------------------------------------
-
-(mr/def ::Settings
- "Options that tweak the behavior of the query processor."
- [:map
- [:report-timezone
- {:optional true
- :description "The timezone the query should be ran in, overriding the default report timezone for the instance."}
- TimezoneId]])
-
-(mr/def ::Constraints
- "Additional constraints added to a query limiting the maximum number of rows that can be returned. Mostly useful
- because native queries don't support the MBQL `:limit` clause. For MBQL queries, if `:limit` is set, it will
- override these values."
- [:and
- [:map
- [:max-results
- {:optional true
- :description
- "Maximum number of results to allow for a query with aggregations. If `max-results-bare-rows` is unset, this
- applies to all queries"}
- ::lib.schema.common/int-greater-than-or-equal-to-zero]
-
- [:max-results-bare-rows
- {:optional true
- :description
- "Maximum number of results to allow for a query with no aggregations. If set, this should be LOWER than
- `:max-results`."}
- ::lib.schema.common/int-greater-than-or-equal-to-zero]]
-
- [:fn
- {:error/message "max-results-bare-rows must be less or equal to than max-results"}
- (fn [{:keys [max-results max-results-bare-rows]}]
- (if-not (core/and max-results max-results-bare-rows)
- true
- (core/>= max-results max-results-bare-rows)))]])
-
-(mr/def ::MiddlewareOptions
- "Additional options that can be used to toggle middleware on or off."
- [:map
- [:skip-results-metadata?
- {:optional true
- :description
- "Should we skip adding `results_metadata` to query results after running the query? Used by
- `metabase.query-processor.middleware.results-metadata`; default `false`. (Note: we may change the name of this
- column in the near future, to `result_metadata`, to fix inconsistencies in how we name things.)"}
- :boolean]
-
- [:format-rows?
- {:optional true
- :description
- "Should we skip converting datetime types to ISO-8601 strings with appropriate timezone when post-processing
- results? Used by `metabase.query-processor.middleware.format-rows`default `false`."}
- :boolean]
-
- [:disable-mbql->native?
- {:optional true
- :description
- "Disable the MBQL->native middleware. If you do this, the query will not work at all, so there are no cases where
- you should set this yourself. This is only used by the `metabase.query-processor.preprocess/preprocess` function to
- get the fully pre-processed query without attempting to convert it to native."}
- :boolean]
-
- [:disable-max-results?
- {:optional true
- :description
- "Disable applying a default limit on the query results. Handled in the `add-default-limit` middleware. If true,
- this will override the `:max-results` and `:max-results-bare-rows` values in `Constraints`."}
- :boolean]
-
- [:userland-query?
- {:optional true
- :description
- "Userland queries are ones ran as a result of an API call, Pulse, or the like. Special handling is done in
- certain userland-only middleware for such queries -- results are returned in a slightly different format, and
- QueryExecution entries are normally saved, unless you pass `:no-save` as the option."}
- [:maybe :boolean]]
-
- [:add-default-userland-constraints?
- {:optional true
- :description
- "Whether to add some default `max-results` and `max-results-bare-rows` constraints. By default, none are added,
- although the functions that ultimately power most API endpoints tend to set this to `true`. See
- `add-constraints` middleware for more details."}
- [:maybe :boolean]]
-
- [:process-viz-settings?
- {:optional true
- :description
- "Whether to process a question's visualization settings and include them in the result metadata so that they can
- incorporated into an export. Used by `metabase.query-processor.middleware.visualization-settings`; default
- `false`."}
- [:maybe :boolean]]])
-
;;; --------------------------------------------- Metabase [Outer] Query ---------------------------------------------
;; To the reader: yes, this seems sort of hacky, but one of the goals of the Nested Query Initiative™ was to minimize
@@ -1816,9 +1715,9 @@
;;
;; These keys are used to tweak behavior of the Query Processor.
;;
- [:settings {:optional true} [:maybe [:ref ::Settings]]]
- [:constraints {:optional true} [:maybe [:ref ::Constraints]]]
- [:middleware {:optional true} [:maybe [:ref ::MiddlewareOptions]]]
+ [:settings {:optional true} [:maybe [:ref ::lib.schema.settings/settings]]]
+ [:constraints {:optional true} [:maybe [:ref ::lib.schema.constraints/constraints]]]
+ [:middleware {:optional true} [:maybe [:ref ::lib.schema.middleware-options/middleware-options]]]
;;
;; INFO
;;
diff --git a/src/metabase/legacy_mbql/util.cljc b/src/metabase/legacy_mbql/util.cljc
index 34783e77f9b..ffaa0cf88c8 100644
--- a/src/metabase/legacy_mbql/util.cljc
+++ b/src/metabase/legacy_mbql/util.cljc
@@ -788,7 +788,10 @@
* `:max-results-bare-rows` is returned if set and Query does not have any aggregations
* `:max-results` is returned otherwise
* If none of the above are set, returns `nil`. In this case, you should use something like the Metabase QP's
- `max-rows-limit`"
+ `max-rows-limit`
+
+ DEPRECATED: this will be removed in the near future. Prefer [[metabase.lib.limit/max-rows-limit]] for new code."
+ {:deprecated "0.57.0"}
[{{:keys [max-results max-results-bare-rows]} :constraints
{limit :limit, aggregations :aggregation, {:keys [items]} :page} :query
query-type :type}]
diff --git a/src/metabase/lib/core.cljc b/src/metabase/lib/core.cljc
index dcc9b13475e..12840df2306 100644
--- a/src/metabase/lib/core.cljc
+++ b/src/metabase/lib/core.cljc
@@ -34,6 +34,7 @@
[metabase.lib.normalize :as lib.normalize]
[metabase.lib.options]
[metabase.lib.order-by :as lib.order-by]
+ [metabase.lib.page]
[metabase.lib.parse :as lib.parse]
[metabase.lib.query :as lib.query]
[metabase.lib.ref :as lib.ref]
@@ -77,6 +78,7 @@
lib.normalize/keep-me
metabase.lib.options/keep-me
lib.order-by/keep-me
+ lib.parse/keep-me
lib.query/keep-me
lib.ref/keep-me
lib.remove-replace/keep-me
@@ -302,7 +304,8 @@
available-metrics]
[lib.limit
current-limit
- limit]
+ limit
+ max-rows-limit]
[lib.metadata.calculation
column-name
describe-query
@@ -344,6 +347,9 @@
orderable-columns]
[lib.normalize
normalize]
+ [metabase.lib.page
+ current-page
+ with-page]
[lib.parse
parse]
[lib.query
diff --git a/src/metabase/lib/limit.cljc b/src/metabase/lib/limit.cljc
index e94a53ba4b4..46856f1273e 100644
--- a/src/metabase/lib/limit.cljc
+++ b/src/metabase/lib/limit.cljc
@@ -1,8 +1,12 @@
(ns metabase.lib.limit
(:require
+ [metabase.lib.aggregation :as lib.aggregation]
[metabase.lib.metadata.calculation :as lib.metadata.calculation]
+ [metabase.lib.page :as lib.page]
[metabase.lib.schema :as lib.schema]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.util :as lib.util]
+ [metabase.util :as u]
[metabase.util.i18n :as i18n]
[metabase.util.malli :as mu]))
@@ -19,15 +23,42 @@
([query :- ::lib.schema/query
stage-number :- :int
n :- [:maybe pos-int?]]
- (lib.util/update-query-stage query stage-number (fn [stage]
- (if n
- (assoc stage :limit n)
- (dissoc stage :limit))))))
+ (lib.util/update-query-stage query stage-number u/assoc-dissoc :limit n)))
-(mu/defn ^:export current-limit :- [:maybe pos-int?]
+(mu/defn ^:export current-limit :- [:maybe ::lib.schema.common/int-greater-than-or-equal-to-zero]
"Get the maximum number of rows to be returned by a stage of a query. `nil` indicates there is no limit"
([query :- ::lib.schema/query]
(current-limit query -1))
([query :- ::lib.schema/query
stage-number :- :int]
(:limit (lib.util/query-stage query stage-number))))
+
+(mu/defn max-rows-limit :- [:maybe ::lib.schema.common/int-greater-than-or-equal-to-zero]
+ "Calculate the absolute maximum number of results that should be returned by this query (MBQL or native), useful for
+ doing the equivalent of
+
+ java.sql.Statement statement = ...;
+ statement.setMaxRows(<max-rows-limit>).
+
+ to ensure the DB cursor or equivalent doesn't fetch more rows than will be consumed.
+
+ This is calculated as follows:
+
+ * If query's last stage is `MBQL` and has a `:limit` or `:page` clause, returns appropriate number
+
+ * If query has `:constraints` with `:max-results-bare-rows` or `:max-results`, returns the appropriate number
+
+ * `:max-results-bare-rows` is returned if set and Query does not have any aggregations
+
+ * `:max-results` is returned otherwise
+
+ * If none of the above are set, returns `nil`. In this case, you should use something like the Metabase QP's
+ `max-rows-limit`"
+ [{{:keys [max-results max-results-bare-rows]} :constraints, :as query} :- ::lib.schema/query]
+ (let [mbql-limit (when-not (lib.util/native-stage? query -1)
+ (u/safe-min (:items (lib.page/current-page query -1))
+ (current-limit query -1)))
+ constraints-limit (or (when (empty? (lib.aggregation/aggregations query -1))
+ max-results-bare-rows)
+ max-results)]
+ (u/safe-min mbql-limit constraints-limit)))
diff --git a/src/metabase/lib/page.cljc b/src/metabase/lib/page.cljc
new file mode 100644
index 00000000000..ad49c7e54c8
--- /dev/null
+++ b/src/metabase/lib/page.cljc
@@ -0,0 +1,25 @@
+(ns metabase.lib.page
+ (:require
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.util :as lib.util]
+ [metabase.util :as u]
+ [metabase.util.malli :as mu]))
+
+(mu/defn current-page :- [:maybe ::lib.schema/page]
+ "Return the `:page` in a query stage."
+ ([query]
+ (current-page query -1))
+
+ ([query :- ::lib.schema/query
+ stage-number :- :int]
+ (:page (lib.util/query-stage query stage-number))))
+
+(mu/defn with-page :- ::lib.schema/query
+ "Set or remove the `:page` in a query stage."
+ ([query page]
+ (with-page query -1 page))
+
+ ([query :- ::lib.schema/query
+ stage-number :- :int
+ page :- [:maybe ::lib.schema/page]]
+ (lib.util/update-query-stage query stage-number u/assoc-dissoc :page page)))
diff --git a/src/metabase/lib/schema.cljc b/src/metabase/lib/schema.cljc
index a7514197d6e..853dc2fd11e 100644
--- a/src/metabase/lib/schema.cljc
+++ b/src/metabase/lib/schema.cljc
@@ -1,5 +1,5 @@
(ns metabase.lib.schema
- "Malli schema for the pMBQL query type, the version of MBQL produced and manipulated by the new Cljc
+ "Malli schema for the MBQL 5 query type, the version of MBQL produced and manipulated by the new Cljc
Metabase lib. Currently this is a little different from the version of MBQL consumed by the QP, specified
in [[metabase.legacy-mbql.schema]]. Hopefully these versions will converge in the future.
@@ -13,6 +13,7 @@
[metabase.lib.schema.actions :as actions]
[metabase.lib.schema.aggregation :as aggregation]
[metabase.lib.schema.common :as common]
+ [metabase.lib.schema.constraints :as lib.schema.constraints]
[metabase.lib.schema.expression :as expression]
[metabase.lib.schema.expression.arithmetic]
[metabase.lib.schema.expression.conditional]
@@ -25,9 +26,11 @@
[metabase.lib.schema.join :as join]
[metabase.lib.schema.literal :as literal]
[metabase.lib.schema.metadata :as lib.schema.metadata]
+ [metabase.lib.schema.middleware-options :as lib.schema.middleware-options]
[metabase.lib.schema.order-by :as order-by]
[metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.lib.schema.ref :as ref]
+ [metabase.lib.schema.settings :as lib.schema.settings]
[metabase.lib.schema.template-tag :as template-tag]
[metabase.lib.schema.util :as lib.schema.util]
[metabase.lib.util.match :as lib.util.match]
@@ -174,8 +177,13 @@
(ref-error-for-stage value))}
(complement ref-error-for-stage)])
-;;; TODO -- should `::page` have a `:lib/type`, like all the other maps in pMBQL?
+;;; TODO -- should `::page` have a `:lib/type`, like all the other maps in MBQL 5?
(mr/def ::page
+ "`page` = page num, starting with 1. `items` = number of items per page.
+ e.g.
+
+ {:page 1, :items 10} = items 1-10
+ {:page 2, :items 10} = items 11-20"
[:map
{:decode/normalize common/normalize-map}
[:page pos-int?]
@@ -204,7 +212,8 @@
[:order-by {:optional true} [:ref ::order-by/order-bys]]
[:source-table {:optional true} [:ref ::id/table]]
[:source-card {:optional true} [:ref ::id/card]]
- [:page {:optional true} [:ref ::page]]]]
+ [:page {:optional true} [:ref ::page]]
+ [:limit {:optional true} ::common/int-greater-than-or-equal-to-zero]]]
[:fn
{:error/message "A query must have exactly one of :source-table or :source-card"}
(complement (comp #(= (count %) 1) #{:source-table :source-card}))]
@@ -365,24 +374,6 @@
[:* [:schema [:ref ::stage.additional]]]]
[:ref ::stages.valid-refs]])
-;;; TODO -- move/copy this schema from the legacy schema to here
-(mr/def ::settings
- [:ref
- {:decode/normalize common/normalize-map}
- :metabase.legacy-mbql.schema/Settings])
-
-;;; TODO -- move/copy this schema from the legacy schema to here
-(mr/def ::middleware-options
- [:ref
- {:decode/normalize common/normalize-map}
- :metabase.legacy-mbql.schema/MiddlewareOptions])
-
-;;; TODO -- move/copy this schema from the legacy schema to here
-(mr/def ::constraints
- [:ref
- {:decode/normalize common/normalize-map}
- :metabase.legacy-mbql.schema/Constraints])
-
(defn- serialize-query [query]
;; this stuff all gets added in when you actually run a query with one of the QP entrypoints, and is not considered
;; to be part of the query itself. It doesn't get saved along with the query in the app DB.
@@ -417,9 +408,9 @@
;;
;; These keys are used to tweak behavior of the Query Processor.
;;
- [:settings {:optional true} [:maybe [:ref ::settings]]]
- [:constraints {:optional true} [:maybe [:ref ::constraints]]]
- [:middleware {:optional true} [:maybe [:ref ::middleware-options]]]
+ [:settings {:optional true} [:maybe [:ref ::lib.schema.settings/settings]]]
+ [:constraints {:optional true} [:maybe [:ref ::lib.schema.constraints/constraints]]]
+ [:middleware {:optional true} [:maybe [:ref ::lib.schema.middleware-options/middleware-options]]]
;; TODO -- `:viz-settings` ?
;;
;; INFO
diff --git a/src/metabase/lib/schema/constraints.cljc b/src/metabase/lib/schema/constraints.cljc
new file mode 100644
index 00000000000..af119e9f7dc
--- /dev/null
+++ b/src/metabase/lib/schema/constraints.cljc
@@ -0,0 +1,31 @@
+(ns metabase.lib.schema.constraints
+ (:require
+ [metabase.lib.schema.common :as lib.schema.common]
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::constraints
+ "Additional constraints added to a query limiting the maximum number of rows that can be returned. Mostly useful
+ because native queries don't support the MBQL `:limit` clause. For MBQL queries, if `:limit` is set, it will
+ override these values."
+ [:and
+ [:map
+ {:decode/normalize lib.schema.common/normalize-map}
+ [:max-results
+ {:optional true
+ :description
+ "Maximum number of results to allow for a query with aggregations. If `max-results-bare-rows` is unset, this
+ applies to all queries"}
+ ::lib.schema.common/int-greater-than-or-equal-to-zero]
+
+ [:max-results-bare-rows
+ {:optional true
+ :description
+ "Maximum number of results to allow for a query with no aggregations. If set, this should be LOWER than
+ `:max-results`."}
+ ::lib.schema.common/int-greater-than-or-equal-to-zero]]
+ [:fn
+ {:error/message "max-results-bare-rows must be less than or equal to than max-results"}
+ (fn [{:keys [max-results max-results-bare-rows]}]
+ (if-not (and max-results max-results-bare-rows)
+ true
+ (>= max-results max-results-bare-rows)))]])
diff --git a/src/metabase/lib/schema/middleware_options.cljc b/src/metabase/lib/schema/middleware_options.cljc
new file mode 100644
index 00000000000..a0b24af859d
--- /dev/null
+++ b/src/metabase/lib/schema/middleware_options.cljc
@@ -0,0 +1,62 @@
+(ns metabase.lib.schema.middleware-options
+ (:require
+ [metabase.lib.schema.common :as lib.schema.common]
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::middleware-options
+ "Additional options that can be used to toggle middleware on or off."
+ [:map
+ {:decode/normalize lib.schema.common/normalize-map}
+ [:skip-results-metadata?
+ {:optional true
+ :description
+ "Should we skip adding `results_metadata` to query results after running the query? Used by
+ `metabase.query-processor.middleware.results-metadata`; default `false`. (Note: we may change the name of this
+ column in the near future, to `result_metadata`, to fix inconsistencies in how we name things.)"}
+ :boolean]
+
+ [:format-rows?
+ {:optional true
+ :description
+ "Should we skip converting datetime types to ISO-8601 strings with appropriate timezone when post-processing
+ results? Used by `metabase.query-processor.middleware.format-rows`default `false`."}
+ :boolean]
+
+ [:disable-mbql->native?
+ {:optional true
+ :description
+ "Disable the MBQL->native middleware. If you do this, the query will not work at all, so there are no cases where
+ you should set this yourself. This is only used by the `metabase.query-processor.preprocess/preprocess` function to
+ get the fully pre-processed query without attempting to convert it to native."}
+ :boolean]
+
+ [:disable-max-results?
+ {:optional true
+ :description
+ "Disable applying a default limit on the query results. Handled in the `add-default-limit` middleware. If true,
+ this will override the `:max-results` and `:max-results-bare-rows` values in `Constraints`."}
+ :boolean]
+
+ [:userland-query?
+ {:optional true
+ :description
+ "Userland queries are ones ran as a result of an API call, Pulse, or the like. Special handling is done in
+ certain userland-only middleware for such queries -- results are returned in a slightly different format, and
+ QueryExecution entries are normally saved, unless you pass `:no-save` as the option."}
+ [:maybe :boolean]]
+
+ [:add-default-userland-constraints?
+ {:optional true
+ :description
+ "Whether to add some default `max-results` and `max-results-bare-rows` constraints. By default, none are added,
+ although the functions that ultimately power most API endpoints tend to set this to `true`. See
+ `add-constraints` middleware for more details."}
+ [:maybe :boolean]]
+
+ [:process-viz-settings?
+ {:optional true
+ :description
+ "Whether to process a question's visualization settings and include them in the result metadata so that they can
+ incorporated into an export. Used by `metabase.query-processor.middleware.visualization-settings`; default
+ `false`."}
+ [:maybe :boolean]]])
diff --git a/src/metabase/lib/schema/settings.cljc b/src/metabase/lib/schema/settings.cljc
new file mode 100644
index 00000000000..e93efa5fcbb
--- /dev/null
+++ b/src/metabase/lib/schema/settings.cljc
@@ -0,0 +1,14 @@
+(ns metabase.lib.schema.settings
+ (:require
+ [metabase.lib.schema.common :as lib.schema.common]
+ [metabase.lib.schema.expression.temporal :as lib.schema.expression.temporal]
+ [metabase.util.malli.registry :as mr]))
+
+(mr/def ::settings
+ "Options that tweak the behavior of the query processor."
+ [:map
+ {:decode/normalize lib.schema.common/normalize-map}
+ [:report-timezone
+ {:optional true
+ :description "The timezone the query should be ran in, overriding the default report timezone for the instance."}
+ [:ref ::lib.schema.expression.temporal/timezone-id]]])
diff --git a/src/metabase/query_processor/middleware/limit.clj b/src/metabase/query_processor/middleware/limit.clj
index 72f69796298..9cb0017257f 100644
--- a/src/metabase/query_processor/middleware/limit.clj
+++ b/src/metabase/query_processor/middleware/limit.clj
@@ -1,10 +1,13 @@
(ns metabase.query-processor.middleware.limit
"Middleware that handles limiting the maximum number of rows returned by a query."
(:require
- [metabase.legacy-mbql.util :as mbql.u]
+ [metabase.lib.core :as lib]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.query-processor.schema :as qp.schema]
[metabase.query-processor.settings :as qp.settings]
- [metabase.query-processor.util :as qp.util]
+ [metabase.query-processor.store :as qp.store]
[metabase.util :as u]
+ [metabase.util.malli :as mu]
[potemkin :as p]))
;;; provided as a convenience since this var used to live here. Prefer using directly from `qp.settings` going forward.
@@ -24,11 +27,14 @@
[query]
(assoc-in query [:middleware :disable-max-results?] true))
-(defn- add-limit [max-rows {query-type :type, {original-limit :limit}, :query, :as query}]
- (cond-> query
- (and (= query-type :query)
- (qp.util/query-without-aggregations-or-limits? query))
- (update :query assoc :limit max-rows, ::original-limit original-limit)))
+(defn- maybe-add-limit [max-rows query]
+ (let [original-limit (lib/current-limit query -1)]
+ (cond-> query
+ (and (not (lib/native-stage? query -1))
+ (not original-limit)
+ (not (lib/current-page query -1))
+ (empty? (lib/aggregations query -1)))
+ (lib/limit -1 max-rows))))
(defn determine-query-max-rows
"Given a `query`, return the max rows that should be returned. This is the minimum of:
@@ -39,24 +45,33 @@
If those three values are not set we fall back to [[metabase.query-processor.limit/absolute-max-results]],
which is also the maximum row count allowed for xlsx downloads due to Excel sheet constraints."
[query]
- (when-not (disable-max-results? query)
- (let [context (-> query :info :context)
- download-context? #{:csv-download :json-download :xlsx-download}
- attachment-context? #{:dashboard-subscription :pulse :notification}
- download-limit (when (download-context? context) (qp.settings/download-row-limit))
- attachment-limit (when (attachment-context? context) (qp.settings/attachment-row-limit))
- res (u/safe-min (mbql.u/query->max-rows-limit query)
- download-limit
- attachment-limit)]
- (if (= context :xlsx-download)
- (u/safe-min res qp.settings/absolute-max-results)
- (or res qp.settings/absolute-max-results)))))
+ (if-not (:lib/type query)
+ ;; handle legacy queries... for now.
+ ;;
+ ;; TODO (Cam 8/19/25) -- update this to be MBQL 5 only once the preprocessor spits out MBQL 5.
+ (recur (lib/query (qp.store/metadata-provider) (case (:type query)
+ ;; sometimes this is called with a compiled query that has both
+ ;; MBQL plus native.
+ :query (dissoc query :native)
+ :native query)))
+ (when-not (disable-max-results? query)
+ (let [context (-> query :info :context)
+ download-context? #{:csv-download :json-download :xlsx-download}
+ attachment-context? #{:dashboard-subscription :pulse :notification}
+ download-limit (when (download-context? context) (qp.settings/download-row-limit))
+ attachment-limit (when (attachment-context? context) (qp.settings/attachment-row-limit))
+ res (u/safe-min (lib/max-rows-limit query)
+ download-limit
+ attachment-limit)]
+ (if (= context :xlsx-download)
+ (u/safe-min res qp.settings/absolute-max-results)
+ (or res qp.settings/absolute-max-results))))))
-(defn add-default-limit
+(mu/defn add-default-limit :- ::lib.schema/query
"Pre-processing middleware. Add default `:limit` to MBQL queries without any aggregations."
- [query]
+ [query :- ::lib.schema/query]
(if-let [max-rows (determine-query-max-rows query)]
- (add-limit max-rows query)
+ (maybe-add-limit max-rows query)
query))
;;;; Post-processing
@@ -76,9 +91,10 @@
;; have to break [[determine-query-max-rows]] into two separate things in order to do that. :shrug:
((take (if-not (pos? max-rows) 1 max-rows)) rf))
-(defn limit-result-rows
+(mu/defn limit-result-rows :- ::qp.schema/rff
"Post-processing middleware. Limit the maximum number of rows that are returned in post-processing."
- [query rff]
+ [query :- ::lib.schema/query
+ rff :- ::qp.schema/rff]
(let [max-rows (determine-query-max-rows query)]
(fn limit-result-rows-rff* [metadata]
(limit-xform max-rows (rff metadata)))))
diff --git a/src/metabase/query_processor/postprocess.clj b/src/metabase/query_processor/postprocess.clj
index ba95ab0a034..233966df66e 100644
--- a/src/metabase/query_processor/postprocess.clj
+++ b/src/metabase/query_processor/postprocess.clj
@@ -53,7 +53,7 @@
#_{:clj-kondo/ignore [:deprecated-var]}
[(ensure-legacy #'format-rows/format-rows)
(ensure-legacy #'results-metadata/record-and-return-metadata!)
- (ensure-legacy #'limit/limit-result-rows)
+ (ensure-pmbql #'limit/limit-result-rows)
(ensure-legacy #'qp.middleware.enterprise/limit-download-result-rows)
(ensure-legacy #'qp.add-rows-truncated/add-rows-truncated)
(ensure-legacy #'qp.add-timezone-info/add-timezone-info)
diff --git a/src/metabase/query_processor/preprocess.clj b/src/metabase/query_processor/preprocess.clj
index 534a457c2b1..c4540b72c0b 100644
--- a/src/metabase/query_processor/preprocess.clj
+++ b/src/metabase/query_processor/preprocess.clj
@@ -146,18 +146,18 @@
(ensure-pmbql #'qp.middleware.enterprise/attach-destination-db-middleware)
(ensure-legacy #'qp.middleware.enterprise/apply-sandboxing)
(ensure-legacy #'qp.persistence/substitute-persisted-query)
- (ensure-legacy #'qp.add-implicit-clauses/add-implicit-clauses)
+ (ensure-legacy #'qp.add-implicit-clauses/add-implicit-clauses) ; #61398
;; this needs to be done twice, once before adding remaps (since we want to add remaps inside joins) and then again
;; after adding any implicit joins. Implicit joins do not need to get remaps since we only use them for fetching
;; specific columns.
- (ensure-legacy #'resolve-joins/resolve-joins)
+ (ensure-legacy #'resolve-joins/resolve-joins) ; #61398
(ensure-pmbql #'qp.add-remaps/add-remapped-columns)
#'qp.resolve-fields/resolve-fields ; this middleware actually works with either MBQL 5 or legacy
(ensure-pmbql #'binning/update-binning-strategy)
- (ensure-legacy #'desugar/desugar)
+ (ensure-legacy #'desugar/desugar) ; #62319
(ensure-legacy #'qp.add-default-temporal-unit/add-default-temporal-unit)
(ensure-pmbql #'qp.add-implicit-joins/add-implicit-joins)
- (ensure-legacy #'resolve-joins/resolve-joins)
+ (ensure-legacy #'resolve-joins/resolve-joins) ; #61398
(ensure-pmbql #'resolve-joined-fields/resolve-joined-fields)
(ensure-pmbql #'qp.remove-inactive-field-refs/remove-inactive-field-refs)
;; yes, this is called a second time, because we need to handle any joins that got added
@@ -168,7 +168,7 @@
(ensure-pmbql-for-unclean-query #'auto-parse-filter-values/auto-parse-filter-values)
(ensure-legacy #'validate-temporal-bucketing/validate-temporal-bucketing)
(ensure-legacy #'optimize-temporal-filters/optimize-temporal-filters)
- (ensure-legacy #'limit/add-default-limit)
+ (ensure-pmbql #'limit/add-default-limit)
(ensure-legacy #'qp.middleware.enterprise/apply-download-limit)
(ensure-legacy #'check-features/check-features)])
diff --git a/src/metabase/query_processor/settings.clj b/src/metabase/query_processor/settings.clj
index f7706dd2a3f..5b76ab95df4 100644
--- a/src/metabase/query_processor/settings.clj
+++ b/src/metabase/query_processor/settings.clj
@@ -39,6 +39,8 @@
:export? true
:type :positive-integer)
+;;; TODO (Cam 8/19/25) -- Make this a function backed by a dynamic variable so we can override it in tests without
+;;; `with-redefs` but also let the imported var in the driver API pick up changes.
(def absolute-max-results
"Maximum number of rows the QP should ever return.
@@ -49,7 +51,7 @@
details."
1048575)
-(def ^:dynamic *minimum-download-row-limit*
+(def ^:dynamic ^:private *minimum-download-row-limit*
"Minimum download row limit. Using dynamic so we can rebind in tests"
absolute-max-results)
diff --git a/src/metabase/query_processor/util.clj b/src/metabase/query_processor/util.clj
index 73869c04538..75593ed3204 100644
--- a/src/metabase/query_processor/util.clj
+++ b/src/metabase/query_processor/util.clj
@@ -22,13 +22,6 @@
;; TODO - I think most of the functions in this namespace that we don't remove could be moved to [[metabase.legacy-mbql.util]]
-(defn query-without-aggregations-or-limits?
- "Is the given query an MBQL query without a `:limit`, `:aggregation`, or `:page` clause?"
- [{{aggregations :aggregation, :keys [limit page]} :query}]
- (and (not limit)
- (not page)
- (empty? aggregations)))
-
(defn default-query->remark
"Generates the default query remark. Exists as a separate function so that overrides of the query->remark multimethod
can access the default value."
diff --git a/test/metabase/legacy_mbql/util_test.cljc b/test/metabase/legacy_mbql/util_test.cljc
index 4912c4228be..196c2746b94 100644
--- a/test/metabase/legacy_mbql/util_test.cljc
+++ b/test/metabase/legacy_mbql/util_test.cljc
@@ -842,6 +842,7 @@
;;; --------------------------------------------- query->max-rows-limit ----------------------------------------------
+#_{:clj-kondo/ignore [:deprecated-var]}
(t/deftest ^:parallel query->max-rows-limit-test
(doseq [[group query->expected]
{"should return `:limit` if set"
diff --git a/test/metabase/lib/limit_test.cljc b/test/metabase/lib/limit_test.cljc
index 8cfa908ec2c..1372bfc5a6a 100644
--- a/test/metabase/lib/limit_test.cljc
+++ b/test/metabase/lib/limit_test.cljc
@@ -1,7 +1,7 @@
(ns metabase.lib.limit-test
(:require
#?@(:cljs ([metabase.test-runner.assert-exprs.approximately-equal]))
- [clojure.test :refer [deftest is testing]]
+ [clojure.test :refer [are deftest is testing]]
[metabase.lib.core :as lib]
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]))
@@ -29,7 +29,9 @@
(is (nil? (lib/current-limit query)))
(is (nil? (lib/current-limit query -1)))
(is (= 100 (lib/current-limit (lib/limit query 100))))
- (is (= 100 (lib/current-limit (lib/limit query 100) -1)))))
+ (is (= 100 (lib/current-limit (lib/limit query 100) -1))))))
+
+(deftest ^:parallel current-limit-test-2
(testing "First stage"
(let [query (lib/query meta/metadata-provider {:database (meta/id)
:type :query
@@ -38,3 +40,140 @@
(is (nil? (lib/current-limit query 1)))
(is (= 100 (lib/current-limit (lib/limit query 0 100) 0)))
(is (nil? (lib/current-limit query 1))))))
+
+(deftest ^:parallel max-rows-limit-test-1
+ (testing "if `:max-results` is set return that"
+ (is (= 15
+ (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql, :source-table 1}]
+ :constraints {:max-results 15}})))))
+
+(deftest ^:parallel max-rows-limit-test-2
+ (testing "if `:max-results-bare-rows` is set AND query has no aggregations, return that"
+ (are [query expected] (= expected (lib/max-rows-limit query))
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql, :source-table 1}]
+ :constraints {:max-results 15, :max-results-bare-rows 10}}
+ 10
+
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/native
+ :native "SELECT * FROM my_table"}]
+ :constraints {:max-results 15, :max-results-bare-rows 10}}
+ 10)))
+
+(deftest ^:parallel max-rows-limit-test-3
+ (testing "if `:max-results-bare-rows` is set but query has aggregations, return `:max-results` instead"
+ (is (= 5
+ (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :aggregation [[:count {:lib/uuid "00000000-0000-0000-0000-000000000000"}]]}]
+ :constraints {:max-results 5, :max-results-bare-rows 4}})))))
+
+(deftest ^:parallel max-rows-limit-test-4
+ (testing "should return `:limit` if set"
+ (is (= 10
+ (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 10}]})))))
+
+(deftest ^:parallel max-rows-limit-test-5
+ (testing "if both `:limit` and `:constraints` are set, prefer the smaller of the two"
+ (are [query expected] (= expected (lib/max-rows-limit query))
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 5}]
+ :constraints {:max-results 10}}
+ 5
+
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 15}]
+ :constraints {:max-results 10}}
+ 10)))
+
+(deftest ^:parallel max-rows-limit-test-6
+ (testing "if both `:limit` and `:page` are set (not sure makes sense), return the smaller of the two"
+ (are [query expected] (= expected (lib/max-rows-limit query))
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 10
+ :page {:page 1, :items 5}}]}
+ 5
+
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 5
+ :page {:page 1, :items 10}}]}
+ 5)))
+
+(deftest ^:parallel max-rows-limit-test-7
+ (testing "if nothing is set return `nil`"
+ (is (nil? (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1}]})))))
+
+(deftest ^:parallel max-rows-limit-test-8
+ (testing "should return `:page` items if set"
+ (is (= 5
+ (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :page {:page 1, :items 5}}]})))))
+
+(deftest ^:parallel max-rows-limit-test-9
+ (testing "since this query doesn't have an aggregation we should be using `max-results-bare-rows`"
+ (is (= 5
+ (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 10}]
+ :constraints {:max-results 15, :max-results-bare-rows 5}})))))
+
+(deftest ^:parallel max-rows-limit-test-10
+ (testing "add an aggregation, and `:max-results` is used instead; since `:limit` is lower, return that"
+ (is (= 10
+ (lib/max-rows-limit
+ {:database 1
+ :lib/type :mbql/query
+ :lib/metadata meta/metadata-provider
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 1
+ :limit 10
+ :aggregation [[:count {:lib/uuid "00000000-0000-0000-0000-000000000000"}]]}]
+ :constraints {:max-results 15, :max-results-bare-rows 5}})))))
diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.clj
index dc6fe0ee724..ea4c69c54b4 100644
--- a/test/metabase/query_processor/api_test.clj
+++ b/test/metabase/query_processor/api_test.clj
@@ -315,7 +315,7 @@
(is (= 101
(count (csv/read-csv result)))))))))))
-(deftest export-with-remapped-fields
+(deftest ^:parallel export-with-remapped-fields
(testing "POST /api/dataset/:format"
(testing "Downloaded CSV/JSON/XLSX results should respect remapped fields (#18440)"
(let [query {:database (mt/id)
diff --git a/test/metabase/query_processor/middleware/limit_test.clj b/test/metabase/query_processor/middleware/limit_test.clj
index f3ff288d938..984e46f88ca 100644
--- a/test/metabase/query_processor/middleware/limit_test.clj
+++ b/test/metabase/query_processor/middleware/limit_test.clj
@@ -2,6 +2,8 @@
"Tests for the `:limit` clause and `:max-results` constraints."
(:require
[clojure.test :refer :all]
+ [metabase.lib.core :as lib]
+ [metabase.lib.test-metadata :as meta]
[metabase.query-processor.middleware.limit :as limit]
[metabase.query-processor.reducible :as qp.reducible]
[metabase.query-processor.settings :as qp.settings]
@@ -10,10 +12,19 @@
(def ^:private test-max-results 10000)
(defn- limit! [query]
- (with-redefs [qp.settings/absolute-max-results test-max-results]
- (let [rff (limit/limit-result-rows query qp.reducible/default-rff)
- rf (rff {})]
- (transduce identity rf (repeat (inc test-max-results) [:ok])))))
+ (if (:lib/type query)
+ (with-redefs [qp.settings/absolute-max-results test-max-results]
+ (let [rff (limit/limit-result-rows query qp.reducible/default-rff)
+ rf (rff {})]
+ (transduce identity rf (repeat (inc test-max-results) [:ok]))))
+ (recur (lib/query meta/metadata-provider query))))
+
+(defn- add-default-limit [query]
+ (if (:lib/type query)
+ (limit/add-default-limit query)
+ (-> (lib/query meta/metadata-provider query)
+ limit/add-default-limit
+ lib/->legacy-MBQL)))
(deftest limit-results-rows-test
(testing "Apply to an infinite sequence and make sure it gets capped at `qp.settings/absolute-max-results`"
@@ -22,24 +33,30 @@
(deftest ^:parallel disable-max-results-test
(testing "Apply `absolute-max-results` limit in the default case"
- (let [query {:type :query
- :query {}}]
- (is (= {:type :query
- :query {:limit qp.settings/absolute-max-results
- ::limit/original-limit nil}}
- (limit/add-default-limit query)))))
+ (let [query {:database (meta/id)
+ :type :query
+ :query {:source-table (meta/id :venues)}}]
+ (is (= {:database (meta/id)
+ :type :query
+ :query {:source-table (meta/id :venues)
+ :limit qp.settings/absolute-max-results}}
+ (add-default-limit query))))))
+
+(deftest ^:parallel disable-max-results-test-2
(testing "Don't apply the `absolute-max-results` limit when `disable-max-results` is used."
- (let [query (limit/disable-max-results {:type :query
- :query {}})]
+ (let [query (limit/disable-max-results {:database (meta/id)
+ :type :query
+ :query {:source-table (meta/id :venues)}})]
(is (= query
- (limit/add-default-limit query))))))
+ (add-default-limit query))))))
(deftest max-results-constraint-test
(testing "Apply an arbitrary max-results on the query and ensure our results size is appropriately constrained"
(is (= 1234
(-> (limit! {:constraints {:max-results 1234}
:type :query
- :query {:aggregation [[:count]]}})
+ :query {:source-table 1234
+ :aggregation [[:count]]}})
mt/rows count)))))
(deftest no-aggregation-test
@@ -54,11 +71,10 @@
(is (= 46
(:row_count result))
":row_count should match the limit added by middleware")
- (is (= {:constraints {:max-results 46}
- :type :query
- :query {:limit 46
- ::limit/original-limit nil}}
- (#'limit/add-default-limit query))
+ (is (=? {:constraints {:max-results 46}
+ :type :query
+ :query {:limit 46}}
+ (#'add-default-limit query))
"Preprocessed query should have :limit added to it"))))
(deftest ^:parallel download-row-max-results-test
@@ -66,11 +82,10 @@
(let [query {:type :query
:query {}
:info {:context :csv-download}}]
- (is (= {:type :query
- :query {:limit qp.settings/absolute-max-results
- ::limit/original-limit nil}
- :info {:context :csv-download}}
- (limit/add-default-limit query))))))
+ (is (=? {:type :query
+ :query {:limit qp.settings/absolute-max-results}
+ :info {:context :csv-download}}
+ (add-default-limit query))))))
(deftest download-row-limit-test
(testing "Apply custom download row limits when"
@@ -87,11 +102,13 @@
context)
(mt/with-temp-env-var-value! [mb-download-row-limit limit]
(is (= expected
- (get-in (limit/add-default-limit
+ (get-in (add-default-limit
{:type :query
:query {}
:info {:context context}})
- [:query :limit])))))))
+ [:query :limit]))))))))
+
+(deftest ^:parallel download-row-limit-test-2
(testing "Apply appropriate maximum when download-row-limit is unset, but `(mbql.u/query->max-rows-limit query)` returns a value above absolute-max-results"
(doseq [[limit expected context] [[1000 1000 :csv-download]
[1000 1000 :json-download]
@@ -105,11 +122,11 @@
"above")
context)
(is (= expected
- (get-in (limit/add-default-limit
+ (get-in (add-default-limit
{:type :query
:query {}
;; setting a constraint here will result in `(mbql.u/query->max-rows-limit query)` returning that limit
- ;; so we can use this to check the behaviour of `limit/add-default-limit` when download-row-limit is unset
+ ;; so we can use this to check the behaviour of `add-default-limit` when download-row-limit is unset
:constraints (when limit {:max-results-bare-rows limit})
:info {:context context}})
[:query :limit])))))))
diff --git a/test/metabase/query_processor/util_test.clj b/test/metabase/query_processor/util_test.clj
index fc2c23de0c9..40aa4ae61aa 100644
--- a/test/metabase/query_processor/util_test.clj
+++ b/test/metabase/query_processor/util_test.clj
@@ -8,17 +8,6 @@
(set! *warn-on-reflection* true)
-(deftest ^:parallel query-without-aggregations-or-limits?-test
- #_{:clj-kondo/ignore [:equals-true]}
- (are [x expected] (= expected
- (qp.util/query-without-aggregations-or-limits? x))
- {:query {:aggregation [[:count]]}} false
- {:query {}} true
- {:query {:aggregation [[:count]]
- :limit 10}} false
- {:query {:aggregation [[:count]]
- :page 1}} false))
-
(defn- query-hash-hex [query]
(codecs/bytes->hex (qp.util/query-hash query)))