Skip to content

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

Speed up field-values sync via UNION DISTINCT (GHY-3074) (#74533)

Eric Normand4f60b9d6576d
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index e24ebd569a5..1cedc4a2e65 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -702,8 +702,8 @@
query-processor
search
settings
- util
- warehouse-schema}
+ sync
+ util}
:model-exports #{:model/Dashboard
:model/DashboardCard
:model/DashboardCardSeries
@@ -1678,6 +1678,7 @@
query-processor
request
search
+ sync
util
view-log
warehouse-schema}
@@ -2141,6 +2142,7 @@
{:team "Graphy"
:api #{metabase.sync.api
metabase.sync.core
+ metabase.sync.field-values
metabase.sync.init
metabase.sync.schedules
metabase.sync.task.sync-databases
@@ -2502,6 +2504,7 @@
warehouse-schema
{:team "UX West"
:api #{metabase.warehouse-schema.field
+ metabase.warehouse-schema.field-values.distinct-batch
metabase.warehouse-schema.metadata-from-qp
metabase.warehouse-schema.metadata-queries
metabase.warehouse-schema.models.field
@@ -2679,8 +2682,8 @@
lib-be
models
query-processor
- util
- warehouse-schema}
+ sync
+ util}
:model-imports #{:model/Database
:model/Field
:model/FieldValues
diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj b/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj
index 0310f8ecd4e..e776336e4ec 100644
--- a/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj
+++ b/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj
@@ -10,9 +10,9 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.query-processor.core :as qp]
+ [metabase.sync.field-values :as sync.field-values]
[metabase.util :as u]
[metabase.util.queue :as queue]
- [metabase.warehouse-schema.models.field-values :as field-values]
[toucan2.core :as t2])
(:import
(java.util.concurrent ArrayBlockingQueue)))
@@ -27,11 +27,22 @@
"A layer of indirection on the actual [[field-value-invalidation-queue]], for testing."
nil)
+(def ^:private ^:dynamic *invalidate-select-batch-size*
+ "Chunk size when fetching :model/Field rows for invalidation. Keeps a single SQL `IN (…)`
+ clause well under the smallest driver parameter limit (Oracle: 1000, SQL Server: 2100)."
+ 500)
+
(defn- batch-invalidate-field-values!
- "Recalculate the field values for the given fields."
+ "Recalculate the field values for the given fields. Groups by table and uses the UNION-distinct
+ path (one warehouse query per table) on SQL drivers."
[field-batches]
- (->> (t2/select :model/Field :id [:in (into #{} cat field-batches)])
- (run! field-values/create-or-update-full-field-values!)))
+ (let [field-ids (into #{} cat field-batches)
+ fields (when (seq field-ids)
+ (->> field-ids
+ (partition-all *invalidate-select-batch-size*)
+ (mapcat (fn [batch]
+ (t2/select :model/Field :id [:in batch])))))]
+ (sync.field-values/sync-fields-grouped-by-table! fields)))
(defmethod queue/init-listener! ::FieldValueInvalidation [_]
(queue/listen! "field-value-invalidate" global-field-value-invalidate-queue batch-invalidate-field-values!
diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj
index 10677c7ce2e..845cb2754c4 100644
--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj
+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/query_processor.clj
@@ -211,6 +211,11 @@
[driver [_ value]]
(h2x/maybe-cast "STRING" (sql.qp/->honeysql driver value)))
+;; BigQuery's string type is `STRING`. Mirrors the `:text` handler above.
+(defmethod sql.qp/->honeysql [:bigquery-cloud-sdk ::sql.qp/cast-to-text]
+ [driver [_ expr]]
+ (sql.qp/->honeysql driver [::sql.qp/cast expr "string"]))
+
;; TODO -- all this [[temporal-type]] stuff below can be replaced with the more generalized
;; [[h2x/with-database-type-info]] stuff we've added. [[h2x/with-database-type-info]] was inspired by this BigQuery code
;; but uses a new record type rather than attaching metadata to everything
diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
index c3f6d7e3261..8512e1d4b80 100644
--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj
@@ -20,6 +20,7 @@
^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
[metabase.query-processor.test :as qp]
[metabase.sync.core :as sync]
+ [metabase.sync.field-values :as sync.field-values]
[metabase.test :as mt]
[metabase.test.data.bigquery-cloud-sdk :as bigquery.tx]
[metabase.test.data.impl :as data.impl]
@@ -655,6 +656,32 @@
(finally
(drop-table-if-exists! table-name)))))))))
+(deftest ^:synchronized sync-fields-grouped-by-table!-on-partitioned-bigquery-table-test
+ (testing "Partitioned BigQuery tables that require a partition filter can't go through
+ run-distinct-batch directly (it bypasses the metadata-from-qp middleware that
+ injects the partition filter). sync-fields-grouped-by-table! should detect this
+ via can-batch-distinct? and fall back to the per-field path, which does go through
+ the middleware. The distinct values must still come back correctly."
+ (mt/test-driver :bigquery-cloud-sdk
+ (mt/dataset native-dataset
+ (let [category-field-id (u/auto-retry 1
+ (try (mt/id :fv_partitioned_table :category)
+ (catch Exception e
+ (sync/sync-database! (mt/db) {:scan :schema})
+ (throw e))))
+ category-field (t2/select-one :model/Field :id category-field-id)
+ table (t2/select-one :model/Table :id (:table_id category-field))]
+ (testing "Dispatcher identifies this as a non-batch-able table"
+ (is (false? (#'sync.field-values/can-batch-distinct? table))))
+ (testing "Distinct values come back correctly via the fallback per-field path"
+ (t2/update! :model/Field category-field-id {:has_field_values :list})
+ (t2/delete! :model/FieldValues :field_id category-field-id)
+ (sync.field-values/sync-fields-grouped-by-table! [category-field])
+ (is (= #{"coffee" "tea" "matcha"}
+ (set (:values (t2/select-one :model/FieldValues
+ :field_id category-field-id
+ :type :full)))))))))))
+
(deftest search-field-from-table-requires-a-filter-test
(testing "#40673"
(mt/test-driver
diff --git a/src/metabase/dashboards/models/dashboard.clj b/src/metabase/dashboards/models/dashboard.clj
index 4125b78c7a4..1f046f01fae 100644
--- a/src/metabase/dashboards/models/dashboard.clj
+++ b/src/metabase/dashboards/models/dashboard.clj
@@ -30,7 +30,6 @@
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
- [metabase.warehouse-schema.models.field-values :as field-values]
[methodical.core :as methodical]
[toucan2.core :as t2]))
@@ -255,7 +254,7 @@
(log/info "Referenced Fields in Dashboard params have changed: Was:" old-param-field-ids
"Is Now:" new-param-field-ids
"Newly Added:" newly-added-param-field-ids)
- (field-values/update-field-values-for-on-demand-dbs! newly-added-param-field-ids))))
+ ((requiring-resolve 'metabase.sync.field-values/update-field-values-for-on-demand-dbs!) newly-added-param-field-ids))))
(defn add-dashcards!
"Add Cards to a Dashboard.
diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.clj
index 4dc700cf782..150de7c4756 100644
--- a/src/metabase/driver/mysql.clj
+++ b/src/metabase/driver/mysql.clj
@@ -447,6 +447,12 @@
[driver [_ value]]
(h2x/maybe-cast "CHAR" (sql.qp/->honeysql driver value)))
+;; MySQL/MariaDB `CAST` does not accept `TEXT` as a target type — the string cast target is
+;; `CHAR`.
+(defmethod sql.qp/->honeysql [:mysql ::sql.qp/cast-to-text]
+ [driver [_ expr]]
+ (sql.qp/->honeysql driver [::sql.qp/cast expr "char"]))
+
(defmethod sql.qp/->honeysql [:mysql :regex-match-first]
[driver [_ arg pattern]]
[:regexp_substr (sql.qp/->honeysql driver arg) (sql.qp/->honeysql driver pattern)])
diff --git a/src/metabase/parameters/field_values.clj b/src/metabase/parameters/field_values.clj
index 3bef11e8363..17d3d8448f7 100644
--- a/src/metabase/parameters/field_values.clj
+++ b/src/metabase/parameters/field_values.clj
@@ -101,20 +101,22 @@
(defn- fetch-advanced-field-values
[field constraints]
- (if (seq constraints)
- (do
- (classloader/require 'metabase.parameters.chain-filter)
- (let [{:keys [values has_more_values]} ((resolve 'metabase.parameters.chain-filter/unremapped-chain-filter)
- (:id field) constraints {})
- ;; we have a hard limit for how many values we want to store in FieldValues,
- ;; let's make sure we respect that limit here.
- ;; For a more detailed docs on this limit check out [[field-values/distinct-values]]
- limited-values (field-values/take-by-length field-values/*total-max-length* values)]
- {:values limited-values
- :has_more_values (or (> (count values)
- (count limited-values))
- has_more_values)}))
- (field-values/distinct-values field)))
+ (let [{:keys [values has_more_values]}
+ (if (seq constraints)
+ (do
+ (classloader/require 'metabase.parameters.chain-filter)
+ ((resolve 'metabase.parameters.chain-filter/unremapped-chain-filter)
+ (:id field) constraints {}))
+ ;; No constraints: pull the raw distinct values. `distinct-values` row-caps at
+ ;; `*distinct-limit*`; we treat hitting that as `has_more_values`.
+ (let [rows (-> (field-values/distinct-values field) :values)]
+ {:values rows
+ :has_more_values (= (count rows) field-values/*distinct-limit*)}))
+ ;; Apply the char-length cap and update `has_more_values` if it fires.
+ limited-values (field-values/take-by-length field-values/*total-max-length* values)]
+ {:values limited-values
+ :has_more_values (or (> (count values) (count limited-values))
+ has_more_values)}))
(defn prepare-advanced-field-values
"Fetch and construct the FieldValues for `field` with type `fv-type`. This does not do any insertion.
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 7089b8a6e17..7ba3c3e93b7 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -48,7 +48,6 @@
[metabase.util.json :as json]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
- [metabase.warehouse-schema.models.field-values :as field-values]
[methodical.core :as methodical]
[toucan2.core :as t2]
[toucan2.pipeline :as t2.pipeline]
@@ -622,7 +621,7 @@
"Is Now:" new-param-field-ids
"Newly Added:" newly-added-param-field-ids)
;; Now update the FieldValues for the Fields referenced by this Card.
- (field-values/update-field-values-for-on-demand-dbs! newly-added-param-field-ids)))))
+ ((requiring-resolve 'metabase.sync.field-values/update-field-values-for-on-demand-dbs!) newly-added-param-field-ids)))))
;; updating a model dataset query to not support implicit actions will disable implicit actions if they exist
(when (and (:dataset_query changes)
(= (:type old-card-info) :model)
@@ -802,7 +801,7 @@
(u/prog1 card
(when-let [field-ids (seq (params/card->template-tag-field-ids card))]
(log/info "Card references Fields in params:" field-ids)
- (field-values/update-field-values-for-on-demand-dbs! field-ids))
+ ((requiring-resolve 'metabase.sync.field-values/update-field-values-for-on-demand-dbs!) field-ids))
(parameter-card/upsert-or-delete-from-parameters! "card" (:id card) (:parameters card))))
(defn- apply-dashboard-question-updates [card changes]
diff --git a/src/metabase/sync/field_values.clj b/src/metabase/sync/field_values.clj
index 61e8214b319..4044e050a00 100644
--- a/src/metabase/sync/field_values.clj
+++ b/src/metabase/sync/field_values.clj
@@ -3,12 +3,15 @@
(:require
[java-time.api :as t]
[metabase.app-db.core :as mdb]
+ [metabase.driver :as driver]
+ [metabase.driver.util :as driver.u]
[metabase.sync.interface :as i]
[metabase.sync.util :as sync-util]
[metabase.tracing.core :as tracing]
[metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
+ [metabase.warehouse-schema.field-values.distinct-batch :as distinct-batch]
[metabase.warehouse-schema.models.field-values :as field-values]
[toucan2.core :as t2]))
@@ -21,50 +24,179 @@
(field-values/clear-field-values-for-field! field)
::field-values/fv-deleted))
-(mu/defn- update-field-values-for-field!
- [field :- i/FieldInstance]
- (log/debug (u/format-color 'green "Looking into updating FieldValues for %s" (sync-util/name-for-logging field)))
- (let [field-values (field-values/get-latest-full-field-values (u/the-id field))]
- (cond
- (not field-values)
- (log/infof "%s does not have FieldValues. Skipping..."
- (sync-util/name-for-logging field))
-
- (field-values/inactive? field-values)
- (log/infof "%s has not been used since %s. Skipping..."
- (sync-util/name-for-logging field) (t/format "yyyy-MM-dd" (t/local-date-time (:last_used_at field-values))))
-
- :else
- (field-values/create-or-update-full-field-values! field :field-values field-values))))
-
-(defn- update-field-value-stats-count [counts-map result]
- (if (instance? Exception result)
- (update counts-map :errors inc)
- (case result
- ::field-values/fv-created
- (update counts-map :created inc)
- ::field-values/fv-updated
- (update counts-map :updated inc)
- ::field-values/fv-deleted
- (update counts-map :deleted inc)
-
- counts-map)))
+(defn- result->delta [result]
+ (cond
+ (instance? Exception result) {:errors 1}
+ (= ::field-values/fv-created result) {:created 1}
+ (= ::field-values/fv-updated result) {:updated 1}
+ (= ::field-values/fv-deleted result) {:deleted 1}))
(defn- table->fields-to-scan
[table]
(t2/select :model/Field :table_id (u/the-id table), :active true, :visibility_type "normal"))
+(defn- can-batch-distinct?
+ "Can this `table`'s database support the UNION ALL distinct-batch query? Requires:
+
+ - A SQL-derived driver (so HoneySQL compilation works).
+ - The `:nested-queries` feature (each UNION arm is wrapped as a subquery in `FROM`).
+ - The table does not require a partition filter. Partitioned BigQuery tables fail without a
+ `WHERE` on the partition column; `metadata-from-qp/table-query` (used by the per-field path)
+ injects one via [[metabase.warehouse-schema.metadata-queries/add-required-filters-if-needed]],
+ but `run-distinct-batch` runs as a native query that bypasses that middleware.
+
+ Tables that fail any check fall back to the per-field path."
+ [table]
+ (let [database (t2/select-one :model/Database :id (:db_id table))
+ engine (:engine database)]
+ (and (isa? driver/hierarchy engine :sql)
+ (driver.u/supports? engine :nested-queries database)
+ (not (:database_require_filter table)))))
+
+(def ^:private empty-counts
+ "Initial counter map for a sync run.
+ - `:probed` fields we attempted to fetch distinct values for (active list-eligible fields)
+ - `:queries` warehouse queries actually issued (1 per UNION batch on SQL, 1 per field on non-SQL)
+ - `:created`/`:updated`/`:deleted`/`:errors` per-field outcomes (`::fv-skipped` is not counted)"
+ {:errors 0, :created 0, :updated 0, :deleted 0, :probed 0, :queries 0})
+
+(defn- fetch-distinct-for-table
+ "Run all UNION batches for `fields` from `table`. Returns
+ `{:results {field-id -> {:values [...]}}, :queries <int>, :failed-fields #{field-id ...}}`.
+
+ Per-batch failures are caught via `sync-util/with-error-handling` — recoverable errors
+ contribute the batch's field-ids to `:failed-fields` and the loop continues; non-recoverable
+ errors propagate out and abort the sync."
+ [table fields]
+ (reduce (fn [acc batch]
+ (let [batch-result (sync-util/with-error-handling
+ (format "Error fetching union distinct values for %s"
+ (sync-util/name-for-logging table))
+ (distinct-batch/run-distinct-batch table batch))
+ acc' (update acc :queries inc)]
+ (if (instance? Throwable batch-result)
+ (update acc' :failed-fields into (map :id batch))
+ (update acc' :results into batch-result))))
+ {:results {} :queries 0 :failed-fields #{}}
+ (partition-all distinct-batch/*batch-size* fields)))
+
+(defn- fetch-distinct-per-field
+ "Portable per-field fallback for non-SQL drivers (e.g. Mongo). Returns the same shape as
+ `fetch-distinct-for-table` (so the caller's persist reduce doesn't care which path produced
+ the results). One QP query per field."
+ [fields]
+ (reduce (fn [acc field]
+ (let [field-id (u/the-id field)
+ result (sync-util/with-error-handling
+ (format "Error fetching distinct values for %s"
+ (sync-util/name-for-logging field))
+ (field-values/distinct-values field))
+ acc' (update acc :queries inc)]
+ (if (or (nil? result) (instance? Throwable result))
+ (update acc' :failed-fields conj field-id)
+ (assoc-in acc' [:results field-id :values] (map first (:values result))))))
+ {:results {} :queries 0 :failed-fields #{}}
+ fields))
+
+(defn- merge-fetch-results
+ "Combine `{:results :queries :failed-fields}` maps from the batch and per-field fetchers."
+ [a b]
+ {:results (merge (:results a) (:results b))
+ :queries (+ (:queries a 0) (:queries b 0))
+ :failed-fields (into #{} cat [(:failed-fields a) (:failed-fields b)])})
+
+(defn- sync-fields-for-table!
+ "Fetch distinct values for `fields` from `table` and persist them via
+ `field-values/persist-field-values!`.
+
+ Dispatch: SQL drivers that meet `can-batch-distinct?` use the UNION ALL batch path for fields
+ without a `:parent_id`. Nested-JSON child fields (`:parent_id` set) and the entire field set
+ for non-batchable tables go through the portable per-field MBQL path — that path goes through
+ the QP, which builds correct column references for nested-JSON fields (`run-distinct-batch`'s
+ hand-rolled HoneySQL CAST does not).
+
+ Returns a counts map of outcomes."
+ [table fields fvs-map]
+ (when (seq fields)
+ (let [{nested true plain false} (group-by #(boolean (:parent_id %)) fields)
+ batch? (can-batch-distinct? table)
+ batch-fields (when batch? plain)
+ per-field-fields (concat nested (when-not batch? plain))
+ {:keys [results queries failed-fields]}
+ (merge-fetch-results
+ (when (seq batch-fields) (fetch-distinct-for-table table batch-fields))
+ (when (seq per-field-fields) (fetch-distinct-per-field per-field-fields)))]
+ (reduce (fn [counts field]
+ (let [field-id (u/the-id field)
+ delta (if (contains? failed-fields field-id)
+ {:errors 1}
+ (let [raw-values (get-in results [field-id :values] [])
+ result (sync-util/with-error-handling
+ (format "Error updating field values for %s"
+ (sync-util/name-for-logging field))
+ (field-values/persist-field-values!
+ field (get fvs-map field-id) raw-values))]
+ (result->delta result)))]
+ (merge-with + counts delta {:probed 1})))
+ (merge-with + empty-counts {:queries queries})
+ fields))))
+
+(defn sync-fields-grouped-by-table!
+ "Sync FieldValues for `fields`, grouping by `:table_id`. Filters to FV-eligible fields via
+ `field-should-have-field-values?` before dispatching. SQL drivers use the UNION batch path;
+ non-SQL drivers use the per-field path. Returns the aggregated counts across all tables.
+
+ Non-recoverable errors propagate out and abort."
+ [fields]
+ (let [eligible (filter field-values/field-should-have-field-values? fields)]
+ (when (seq eligible)
+ (let [fvs-map (field-values/batched-get-latest-full-field-values (map u/the-id eligible))
+ by-table (group-by :table_id eligible)]
+ (transduce (map (fn [[table-id table-fields]]
+ (let [table (t2/select-one :model/Table :id table-id)]
+ (sync-fields-for-table! table table-fields fvs-map))))
+ (completing (partial merge-with +))
+ empty-counts
+ by-table)))))
+
(mu/defn update-field-values-for-table!
- "Update the FieldValues for all Fields (as needed) for `table`."
+ "Update the FieldValues for all Fields (as needed) for `table`.
+ SQL drivers use a single UNION ALL query covering every list-eligible field with an active
+ FieldValues row. Non-SQL drivers fall back to sequential per-field DISTINCT queries."
[table :- i/TableInstance]
- (reduce (fn [fv-change-counts field]
- (let [result (sync-util/with-error-handling (format "Error updating field values for %s" (sync-util/name-for-logging field))
- (if (field-values/field-should-have-field-values? field)
- (update-field-values-for-field! field)
- (clear-field-values-for-field! field)))]
- (update-field-value-stats-count fv-change-counts result)))
- {:errors 0, :created 0, :updated 0, :deleted 0}
- (table->fields-to-scan table)))
+ (let [all-fields (table->fields-to-scan table)
+ {to-sync true
+ to-clear false} (group-by #(boolean (field-values/field-should-have-field-values? %))
+ all-fields)
+ clear-counts (reduce (fn [counts field]
+ (let [result (sync-util/with-error-handling
+ (format "Error clearing field values for %s"
+ (sync-util/name-for-logging field))
+ (clear-field-values-for-field! field))]
+ (merge-with + counts (result->delta result))))
+ empty-counts
+ to-clear)
+ fvs-map (field-values/batched-get-latest-full-field-values (map u/the-id to-sync))
+ fields-to-sync (filterv (fn [field]
+ (let [fv (get fvs-map (u/the-id field))]
+ (cond
+ (not fv)
+ (do (log/infof "%s does not have FieldValues. Skipping..."
+ (sync-util/name-for-logging field))
+ false)
+
+ (field-values/inactive? fv)
+ (do (log/infof "%s has not been used since %s. Skipping..."
+ (sync-util/name-for-logging field)
+ (t/format "yyyy-MM-dd"
+ (t/local-date-time (:last_used_at fv))))
+ false)
+
+ :else
+ true)))
+ to-sync)
+ sync-counts (sync-fields-for-table! table fields-to-sync fvs-map)]
+ (merge-with + clear-counts (or sync-counts empty-counts))))
(mu/defn- update-field-values-for-database!
[database :- i/DatabaseInstance]
@@ -72,13 +204,53 @@
(let [tables (sync-util/reducible-sync-tables database)]
(transduce (map update-field-values-for-table!) (partial merge-with +) tables))))
-(defn- update-field-values-summary [{:keys [created updated deleted errors]}]
- (format "Updated %d field value sets, created %d, deleted %d with %d errors"
- updated created deleted errors))
+(defn- update-field-values-summary [{:keys [created updated deleted errors probed queries]}]
+ (format "Updated %d field value sets, created %d, deleted %d with %d errors (probed %d fields in %d queries)"
+ updated created deleted errors probed queries))
(defn- delete-expired-advanced-field-values-summary [{:keys [deleted]}]
(format "Deleted %d expired advanced fieldvalues" deleted))
+(defn- table-ids->table-id->is-on-demand?
+ "Given a collection of `table-ids` return a map of Table ID to whether or not its Database is subject to 'On Demand'
+ FieldValues updating. This means the FieldValues for any Fields belonging to the Database should be updated only
+ when they are used in new Dashboard or Card parameters."
+ [table-ids]
+ (let [table-ids (set table-ids)
+ table-id->db-id (when (seq table-ids)
+ (t2/select-pk->fn :db_id 'Table :id [:in table-ids]))
+ db-id->is-on-demand? (when (seq table-id->db-id)
+ (t2/select-pk->fn :is_on_demand 'Database
+ :id [:in (set (vals table-id->db-id))]))]
+ (into {} (for [table-id table-ids]
+ [table-id (-> table-id table-id->db-id db-id->is-on-demand?)]))))
+
+(def ^:private ^:dynamic *on-demand-select-batch-size*
+ "Chunk size when fetching :model/Field rows for on-demand updates. Keeps a single SQL `IN (…)`
+ clause under the smallest driver parameter limit (Oracle: 1000, SQL Server: 2100)."
+ 500)
+
+(defn update-field-values-for-on-demand-dbs!
+ "Update the FieldValues for any Fields with `field-ids` if the Field should have FieldValues and it belongs to a
+ Database that is set to do 'On-Demand' syncing.
+
+ Groups fields by table and uses the UNION-distinct path (one warehouse query per table) on SQL
+ drivers; non-SQL drivers fall back to per-field queries."
+ [field-ids]
+ (let [fields (when (seq field-ids)
+ (->> field-ids
+ (partition-all *on-demand-select-batch-size*)
+ (mapcat (fn [batch]
+ (t2/select ['Field :name :id :base_type :effective_type :coercion_strategy
+ :semantic_type :visibility_type :table_id :has_field_values]
+ :id [:in batch])))))
+ table-id->is-on-demand? (table-ids->table-id->is-on-demand? (map :table_id fields))
+ on-demand-fields (filter #(table-id->is-on-demand? (:table_id %)) fields)]
+ (when (seq on-demand-fields)
+ (log/debugf "Updating FieldValues for %d on-demand fields across %d tables"
+ (count on-demand-fields) (count (set (map :table_id on-demand-fields))))
+ (sync-fields-grouped-by-table! on-demand-fields))))
+
(defn- delete-expired-advanced-field-values-for-field!
[field]
(sync-util/with-error-handling (format "Error deleting expired advanced field values for %s" (sync-util/name-for-logging field))
diff --git a/src/metabase/warehouse_schema/field_values/distinct_batch.clj b/src/metabase/warehouse_schema/field_values/distinct_batch.clj
new file mode 100644
index 00000000000..05a93eec46b
--- /dev/null
+++ b/src/metabase/warehouse_schema/field_values/distinct_batch.clj
@@ -0,0 +1,143 @@
+(ns metabase.warehouse-schema.field-values.distinct-batch
+ "Bulk distinct-values fetcher using SQL `UNION ALL`.
+
+ For each field in the input set, builds a flat per-field arm of the shape
+
+ SELECT '<field-name>' AS field_name, <cast-to-text>(col) AS value_out
+ FROM <table>
+ GROUP BY <cast-to-text>(col)
+ <driver-correct LIMIT clause>
+
+ Per-arm DISTINCT semantics come from `GROUP BY` rather than `SELECT DISTINCT` — both are
+ equivalent here, but `GROUP BY` composes cleanly with every driver's
+ [[sql.qp/apply-top-level-clause]] `:limit` transform (notably SQL Server's `TOP N` rewrite,
+ which reads from `:select` and doesn't see `:select-distinct`).
+
+ The cast goes through [[sql.qp/cast-to-text]] so each driver picks its native text type
+ (Oracle's `VARCHAR2`, SQL Server's `VARCHAR(MAX)`, Spark SQL's `STRING`, etc.). The LIMIT
+ goes through [[sql.qp/apply-top-level-clause]] so Oracle gets `WHERE rownum <= N` and
+ SQL Server gets `SELECT TOP N`.
+
+ Arms are then unioned via HoneySQL's `:union-all`, batched into groups so query text stays
+ below driver parameter / length limits, and decoded back to native Clojure values using the
+ field's known `base_type`.
+
+ Lives in its own namespace because it pulls in `metabase.driver.sql.query-processor` and
+ `metabase.query-processor`, and the latter's transitive load chain (actions → parameters →
+ chain-filter → params.field-values → field → field-values) would form a cycle if these
+ requires lived in `metabase.warehouse-schema.models.field-values`."
+ (:require
+ [metabase.driver.sql.query-processor :as sql.qp]
+ [metabase.query-processor :as qp]
+ [metabase.util :as u]
+ [metabase.util.honey-sql-2 :as h2x]
+ [metabase.warehouse-schema.models.field-values :as field-values]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:dynamic *batch-size*
+ "Number of per-field arms unioned into one query. Keeps query text well under driver limits."
+ 50)
+
+(defn- decode-value
+ "Coerce a string value (from `CAST(... AS <text>)`) back to a native Clojure value using the
+ field's `base_type`. NULL/`nil` passes through unchanged.
+
+ We only decode types whose Clojure representation would JSON-encode differently than a
+ string: numbers and booleans need to land in `:model/FieldValues.values` as JSON numbers /
+ booleans, not strings, to match the per-field MBQL path. Temporal types (`:type/Date`,
+ `:type/DateTime`, `:type/Time`) and `:type/UUID` are *already* JSON-encoded as strings by
+ `mi/transform-json` on the way to the DB, so leaving them as strings here matches what the
+ per-field path stores after its round-trip — no decoding needed."
+ [base-type ^String s]
+ (cond
+ (nil? s) nil
+ (isa? base-type :type/Boolean) (contains? #{"true" "t" "1"} (u/lower-case-en s))
+ (isa? base-type :type/Integer) (try (Long/parseLong s)
+ (catch NumberFormatException _
+ (try (bigint s)
+ (catch NumberFormatException _ s))))
+ ;; `:type/Decimal` derives from `:type/Float`, so it has to come first.
+ (isa? base-type :type/Decimal) (try (bigdec s)
+ (catch NumberFormatException _ s))
+ (isa? base-type :type/Float) (try (Double/parseDouble s)
+ (catch NumberFormatException _ s))
+ :else s))
+
+(defn- table-honeysql
+ "Driver-aware HoneySQL identifier for `table`. Routes through `sql.qp/->honeysql` so drivers
+ that need to qualify table identifiers further (e.g. BigQuery's project-id prefix) get their
+ chance."
+ [driver {:keys [schema name]}]
+ (sql.qp/->honeysql driver
+ (if (seq schema)
+ (h2x/identifier :table schema name)
+ (h2x/identifier :table name))))
+
+(defn- cast-to-text-honeysql
+ "Driver-correct HoneySQL fragment for `CAST(col AS <driver's text type>)`."
+ [driver col-name]
+ (sql.qp/->honeysql driver
+ (sql.qp/mbql-clause driver ::sql.qp/cast-to-text
+ (h2x/identifier :field col-name))))
+
+(defn- build-arm
+ "HoneySQL for one UNION arm."
+ [driver table field]
+ (let [cast-expr (cast-to-text-honeysql driver (:name field))
+ inner {:select [[[:inline (:name field)] :field_name]
+ [cast-expr :value_out]]
+ ;; `:from` wraps the identifier expression in an extra vector — `[[expr]]` so HoneySQL
+ ;; treats it as a single table expression rather than `[table alias …]`.
+ :from [[(table-honeysql driver table)]]
+ ;; Only `cast-expr` goes in `:group-by`. The `[:inline (:name field)]` tag is a literal in
+ ;; the SELECT list and needs no GROUP BY entry.
+ :group-by [cast-expr]}
+ limited (sql.qp/apply-top-level-clause driver :limit inner {:limit field-values/*distinct-limit*})]
+ ;; The per-field `SELECT … GROUP BY … LIMIT N` is built as an inner subquery and wrapped in an
+ ;; outer `SELECT * FROM (<inner>)`. The wrap is required. A `UNION ALL` of arms that each carry
+ ;; their own `LIMIT` is illegal SQL. The LIMIT would bind to the whole union. Nesting the
+ ;; limited query as a subquery parenthesizes it; the outer arms then carry no LIMIT and union
+ ;; cleanly.
+ {:select [:*]
+ :from [[limited :_arm]]}))
+
+(defn- build-union
+ "Build the full HoneySQL form for one batch of fields. Single field → no UNION wrapper."
+ [driver table fields]
+ (let [arms (mapv #(build-arm driver table %) fields)]
+ (if (= 1 (count arms))
+ (first arms)
+ {:union-all arms})))
+
+(defn run-distinct-batch
+ "Execute one UNION ALL query covering `fields` from one `table`. The caller is responsible for
+ ensuring `(count fields)` ≤ [[*batch-size*]] (the per-query arm cap) and that all `fields`
+ belong to `table`.
+
+ Returns `{field-id → {:values [decoded …] :raw-count N}}` with all input fields pre-seeded so
+ fields with zero distinct values still appear. Each field's `:values` is capped at
+ `field-values/*distinct-limit*` by the per-arm `LIMIT`.
+
+ Does NOT swallow exceptions — callers wrap with `metabase.sync.util/with-error-handling`
+ (or equivalent) to decide log-and-continue vs abort semantics."
+ [table fields]
+ (let [db-id (:db_id table)
+ driver (:engine (t2/select-one :model/Database :id db-id))
+ hsql (build-union driver table fields)
+ [sql & params] (sql.qp/format-honeysql driver hsql)
+ result (qp/process-query
+ {:database db-id
+ :type :native
+ :native {:query sql, :params (vec params)}})
+ rows (-> result :data :rows)
+ by-name (into {} (map (juxt :name identity)) fields)]
+ (reduce (fn [acc [field-name value-str]]
+ (let [field (get by-name field-name)
+ v (decode-value (:base_type field) value-str)]
+ (-> acc
+ (update-in [(:id field) :values] (fnil conj []) v)
+ (update-in [(:id field) :raw-count] (fnil inc 0)))))
+ (into {} (map (fn [f] [(:id f) {:values [] :raw-count 0}])) fields)
+ rows)))
diff --git a/src/metabase/warehouse_schema/models/field_values.clj b/src/metabase/warehouse_schema/models/field_values.clj
index e83d2b99c3a..39e3c2c0380 100644
--- a/src/metabase/warehouse_schema/models/field_values.clj
+++ b/src/metabase/warehouse_schema/models/field_values.clj
@@ -35,7 +35,6 @@
[metabase.models.serialization :as serdes]
[metabase.premium-features.core :refer [defenterprise]]
[metabase.query-processor.reducible :as qp.reducible]
- [metabase.query-processor.schema :as qp.schema]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.i18n :refer [tru]]
@@ -46,6 +45,8 @@
[methodical.core :as methodical]
[toucan2.core :as t2]))
+(set! *warn-on-reflection* true)
+
(def ^:private ^Long entry-max-length
"The maximum character length for a stored FieldValues entry."
100)
@@ -54,24 +55,21 @@
"Maximum total length for a FieldValues entry (combined length of all values for the field)."
(long (* analyze/auto-list-cardinality-threshold entry-max-length)))
-(def ^:dynamic ^Integer *absolute-max-distinct-values-limit*
- "The absolute maximum number of results to return for a `field-distinct-values` query. Normally Fields with 100 or
- less values (at the time of this writing) get marked as `auto-list` Fields, meaning we save all their distinct
- values in a FieldValues object, which powers a list widget in the FE when using the Field for filtering in the QB.
- Admins can however manually mark any Field as `list`, which is effectively ordering Metabase to keep FieldValues for
- the Field regardless of its cardinality.
+(def ^:dynamic ^Integer *distinct-limit*
+ "Per-column row cap for warehouse-side distinct-value fetches. Used by the UNION ALL per-arm
+ `LIMIT`, by the per-field MBQL `lib/limit` in `distinct-values`, and by `persist-field-values!`
+ to detect whether the warehouse hit that cap.
- Of course, if a User does something crazy, like mark a million-arity Field as List, we don't want Metabase to
- explode trying to make their dreams a reality; we need some sort of hard limit to prevent catastrophes. So this
- limit is effectively a safety to prevent Users from nuking their own instance for Fields that really shouldn't be
- List Fields at all. For these very-high-cardinality Fields, we're effectively capping the number of
- FieldValues that get could saved.
+ Fields with fewer distinct values than this get marked as `auto-list`, meaning we save all
+ their distinct values in a FieldValues object that powers the list widget in the FE. Admins
+ can also manually mark any Field as `list`, which keeps FieldValues regardless of cardinality.
- This number should be a balance of:
+ If a user does something crazy like marking a million-arity Field as List, this limit
+ prevents Metabase from exploding trying to fetch all values. The trade-off:
- * Not being too low, which would definitely result in GitHub issues along the lines of 'My 500-distinct-value Field
- that I marked as List is not showing all values in the List Widget'
- * Not being too high, which would result in Metabase running out of memory dealing with too many values"
+ * Too low → GitHub issues like 'My 500-distinct-value Field that I marked as List is not
+ showing all values in the List Widget'
+ * Too high → Metabase runs out of memory materialising the result set"
(int 1000))
(def ^java.time.Period advanced-field-values-max-age
@@ -353,61 +351,55 @@
;;; | CRUD fns |
;;; +----------------------------------------------------------------------------------------------------------------+
-(mu/defn- limit-max-char-len-rff :- ::qp.schema/rff
- "Returns a rff that will stop when the total character length of the values exceeds `max-char-len`."
- [rff max-char-len]
- (fn [metadata]
- (let [rf (rff metadata)
- total-char (volatile! 0)]
- (fn
- ([]
- (rf))
- ([result]
- (rf result))
- ([result row]
- (assert (= 1 (count row)))
- (vswap! total-char + (count (str (first row))))
- (if (> @total-char max-char-len)
- (reduced (assoc result ::reached-char-len-limit true))
- (rf result row)))))))
+(defn limit-values
+ "Dedup, sort, and apply the `*total-max-length*` character cap to a sequence of scalar `values`.
+ Returns `{:values sorted-vec, :has_more_values bool}` where `:has_more_values` reflects only
+ the char-length cap (i.e. there are more distinct values beyond what fit in the byte budget).
+
+ NULL values are kept as a valid distinct value — they're meaningful in parameter widgets
+ (\"no value set\") and match the per-field MBQL path's storage behavior.
+
+ Used by the bulk / UNION distinct-fetching paths to finalize per-field value sets in memory."
+ [values]
+ (loop [str-length 0
+ acc (sorted-set)
+ values values]
+ (cond
+ (empty? values)
+ {:values (vec acc) :has_more_values false}
+
+ (contains? acc (first values))
+ (recur str-length acc (rest values))
+
+ :else
+ (let [new-str-length (+ str-length (count (str (first values))))]
+ (if (> new-str-length *total-max-length*)
+ {:values (vec acc) :has_more_values true}
+ (recur new-str-length (conj acc (first values)) (rest values)))))))
;;; TODO -- move into [[metabase.warehouse-schema.metadata-from-qp]] ??
(mu/defn distinct-values
- "Fetch a sequence of distinct values for `field` that are below the [[*total-max-length*]] threshold. If the values
- are past the threshold, this returns a subset of possible values values where the total length of all items is less
- than [[*total-max-length*]]. It also returns a `has_more_values` flag, `has_more_values` = `true` when the returned
- values list is a subset of all possible values.
-
- ;; (distinct-values (Field 1))
- ;; -> {:values [[1], [2], [3]]
- :has_more_values false}
-
- (This function provides the values that normally get saved as a Field's FieldValues. You most likely should not be
- using this directly in code outside of this namespace, unless it's for a very specific reason, such as certain cases
- where we fetch ad-hoc FieldValues for GTAP-filtered Fields.)"
+ "Fetch raw distinct values for `field` from the warehouse, row-capped at
+ `*distinct-limit*`. Returns `{:values rows-as-1-tuples}`.
+
+ Callers that persist these values via `persist-field-values!` get the char-length cap +
+ `:has_more_values` computation for free. Callers that need to surface values directly
+ (e.g. parameter widgets) should apply `take-by-length` + their own `:has_more_values`
+ derivation, as `parameters/field-values` does."
[field :- [:or
(ms/InstanceOf :model/Field)
::lib.schema.metadata/column]]
(try
- (let [field (cond-> field
- (t2/model field) (lib-be/instance->metadata :metadata/column))
- result ((requiring-resolve 'metabase.warehouse-schema.metadata-from-qp/table-query)
- (:table-id field)
- (fn [query]
- (-> query
- (lib/breakout field)
- (lib/limit *absolute-max-distinct-values-limit*)))
- (limit-max-char-len-rff qp.reducible/default-rff *total-max-length*))
- distinct-values (-> result :data :rows)]
- {:values distinct-values
- ;; has_more_values=true means the list of values we return is a subset of all possible values.
- :has_more_values (or (true? (::reached-char-len-limit result))
- ;; `distinct-values` is from a query
- ;; with limit = [[*absolute-max-distinct-values-limit*]].
- ;; So, if the returned `distinct-values` has length equal to that exact limit,
- ;; we assume the returned values is just a subset of what we have in DB.
- (= (count distinct-values)
- *absolute-max-distinct-values-limit*))})
+ (let [field (cond-> field
+ (t2/model field) (lib-be/instance->metadata :metadata/column))
+ result ((requiring-resolve 'metabase.warehouse-schema.metadata-from-qp/table-query)
+ (:table-id field)
+ (fn [query]
+ (-> query
+ (lib/breakout field)
+ (lib/limit *distinct-limit*)))
+ qp.reducible/default-rff)]
+ {:values (-> result :data :rows)})
(catch Throwable e
(log/error e "Error fetching field values")
nil)))
@@ -445,6 +437,12 @@
[field-id]
(get-latest-field-values field-id :full nil))
+(def ^:private ^:dynamic *fv-select-batch-size*
+ "Chunk size when fetching FieldValues by `field_id [:in …]`. Keeps a single SQL `IN (…)` clause
+ under the smallest driver parameter limit (Oracle: 1000, SQL Server: 2100). Wide tables can
+ have thousands of list-eligible fields, so we partition before issuing the select."
+ 500)
+
(defn batched-get-latest-full-field-values
"Batched version of [[get-latest-full-field-values]] .
Takes a list of field-ids and returns a map of field-id -> full FieldValues.
@@ -452,56 +450,78 @@
[field-ids]
(delete-duplicates-and-return-latest!
(when (seq field-ids)
- (t2/select :model/FieldValues :field_id [:in field-ids] :type :full :hash_key nil))))
+ (mapcat (fn [batch]
+ (t2/select :model/FieldValues :field_id [:in batch] :type :full :hash_key nil))
+ (partition-all *fv-select-batch-size* field-ids)))))
+
+(defn persist-field-values!
+ "Persist raw distinct values for a single field. Caller passes raw values fetched from the
+ warehouse; this function applies the in-memory cap via `limit-values`, detects whether the
+ warehouse-side row LIMIT fired (by counting raw values against `*distinct-limit*`), and
+ combines both signals into `:has_more_values`. Compares the result against `existing-fv` and
+ creates / updates / skips / deletes as appropriate. Returns one of `::fv-skipped`,
+ `::fv-updated`, `::fv-created`, or `::fv-deleted`.
+
+ - `existing-fv`: the current FieldValues row for this field, or `nil` if none exists.
+ - `raw-values`: raw distinct values from the warehouse (no pre-capping required).
+
+ Note that this only persists *Full* FieldValues. Advanced FieldValues for the same field are
+ deleted as a side effect of `clear-field-values-for-field!` when the capped value set is empty."
+ [field existing-fv raw-values]
+ (let [field-name (or (:name field) (:id field))
+ row-cap-hit? (>= (count raw-values) *distinct-limit*)
+ {values :values
+ char-cap-hit? :has_more_values} (limit-values raw-values)
+ has-more-values (boolean (or row-cap-hit? char-cap-hit?))]
+ (cond
+ (empty? values)
+ (do
+ (clear-field-values-for-field! field)
+ ::fv-deleted)
+
+ ;; if FieldValues object doesn't exist create one
+ (nil? existing-fv)
+ (do
+ (log/debugf "Storing FieldValues for Field %s..." field-name)
+ (app-db/select-or-insert! :model/FieldValues {:field_id (u/the-id field), :type :full}
+ (constantly {:has_more_values has-more-values
+ :values values
+ :human_readable_values nil}))
+ ::fv-created)
+
+ ;; if existing FieldValues won't change, skip it
+ (and (= (:values existing-fv) values)
+ (= (:has_more_values existing-fv) has-more-values))
+ (do
+ (log/debugf "FieldValues for Field %s remain unchanged. Skipping..." field-name)
+ ::fv-skipped)
+
+ ;; otherwise the FieldValues object already exists; update values in it
+ :else
+ (do
+ (log/debugf "Storing updated FieldValues for Field %s..." field-name)
+ (t2/update! :model/FieldValues (u/the-id existing-fv)
+ (m/remove-vals nil?
+ {:has_more_values has-more-values
+ :values values
+ :human_readable_values (fixup-human-readable-values existing-fv values)}))
+ ::fv-updated))))
(defn create-or-update-full-field-values!
- "Create or update the full FieldValues object for `field`. If the FieldValues object already exists, then update values for
- it; otherwise create a new FieldValues object with the newly fetched values. Returns whether the field values were
- created/updated/deleted as a result of this call.
-
- Note that if the full FieldValues are create/updated/deleted, it'll delete all the Advanced FieldValues of the same `field`."
- [field & {:keys [field-values human-readable-values]}]
+ "Create or update the full FieldValues object for `field`. If the FieldValues object already
+ exists, then update values for it; otherwise create a new FieldValues object with the newly
+ fetched values. Returns whether the field values were created / updated / deleted as a result
+ of this call.
+
+ Note that if the full FieldValues are create / updated / deleted, it'll delete all the
+ Advanced FieldValues of the same `field`."
+ [field & {:keys [field-values]}]
(if (field-should-have-field-values? field)
- (let [field-values (or field-values (get-latest-full-field-values (u/the-id field)))
- {unwrapped-values :values
- :keys [has_more_values]} (distinct-values field)
- ;; unwrapped-values are 1-tuples, so we need to unwrap their values for storage
- values (seq (map first unwrapped-values))
- field-name (or (:name field) (:id field))]
- (cond
- (and values
- (= (:values field-values) values)
- (= (:has_more_values field-values) has_more_values))
- (do
- (log/debugf "FieldValues for Field %s remain unchanged. Skipping..." field-name)
- ::fv-skipped)
-
- ;; if the FieldValues object already exists then update values in it
- (and field-values values)
- (do
- (log/debugf "Storing updated FieldValues for Field %s..." field-name)
- (t2/update! :model/FieldValues (u/the-id field-values)
- (m/remove-vals nil?
- {:has_more_values has_more_values
- :values values
- :human_readable_values (fixup-human-readable-values field-values values)}))
- ::fv-updated)
-
- ;; if FieldValues object doesn't exist create one
- values
- (do
- (log/debugf "Storing FieldValues for Field %s..." field-name)
- (app-db/select-or-insert! :model/FieldValues {:field_id (u/the-id field), :type :full}
- (constantly {:has_more_values has_more_values
- :values values
- :human_readable_values human-readable-values}))
- ::fv-created)
-
- ;; otherwise this Field isn't eligible, so delete any FieldValues that might exist
- :else
- (do
- (clear-field-values-for-field! field)
- ::fv-deleted)))
+ (let [existing-fv (or field-values (get-latest-full-field-values (u/the-id field)))
+ {rows :values} (distinct-values field)
+ ;; rows are 1-tuples — unwrap for storage.
+ raw-values (seq (map first rows))]
+ (persist-field-values! field existing-fv raw-values))
(do
(clear-field-values-for-field! field)
::fv-deleted)))
@@ -509,13 +529,12 @@
(defn get-or-create-full-field-values!
"Create FieldValues for a `Field` if they *should* exist but don't already exist. Returns the existing or newly
created FieldValues for `Field`. Updates :last_used_at so sync will know this is active."
- {:arglists '([field] [field human-readable-values])}
- [{field-id :id field-values :values :as field} & [human-readable-values]]
+ [{field-id :id field-values :values :as field}]
{:pre [(integer? field-id)]}
(when (field-should-have-field-values? field)
(let [existing (or (not-empty field-values) (get-latest-full-field-values field-id))]
(if (or (not existing) (inactive? existing))
- (case (create-or-update-full-field-values! field :human-readable-values human-readable-values)
+ (case (create-or-update-full-field-values! field)
::fv-deleted
nil
@@ -530,40 +549,6 @@
(t2/update! :model/FieldValues (:id existing) {:last_used_at :%now})
existing)))))
-;;; +----------------------------------------------------------------------------------------------------------------+
-;;; | On Demand |
-;;; +----------------------------------------------------------------------------------------------------------------+
-
-(defn- table-ids->table-id->is-on-demand?
- "Given a collection of `table-ids` return a map of Table ID to whether or not its Database is subject to 'On Demand'
- FieldValues updating. This means the FieldValues for any Fields belonging to the Database should be updated only
- when they are used in new Dashboard or Card parameters."
- [table-ids]
- (let [table-ids (set table-ids)
- table-id->db-id (when (seq table-ids)
- (t2/select-pk->fn :db_id 'Table :id [:in table-ids]))
- db-id->is-on-demand? (when (seq table-id->db-id)
- (t2/select-pk->fn :is_on_demand 'Database
- :id [:in (set (vals table-id->db-id))]))]
- (into {} (for [table-id table-ids]
- [table-id (-> table-id table-id->db-id db-id->is-on-demand?)]))))
-
-(defn update-field-values-for-on-demand-dbs!
- "Update the FieldValues for any Fields with `field-ids` if the Field should have FieldValues and it belongs to a
- Database that is set to do 'On-Demand' syncing."
- [field-ids]
- (let [fields (when (seq field-ids)
- (filter field-should-have-field-values?
- (t2/select ['Field :name :id :base_type :effective_type :coercion_strategy
- :semantic_type :visibility_type :table_id :has_field_values]
- :id [:in field-ids])))
- table-id->is-on-demand? (table-ids->table-id->is-on-demand? (map :table_id fields))]
- (doseq [{table-id :table_id, :as field} fields]
- (when (table-id->is-on-demand? table-id)
- (log/debugf "Field %s '%s' should have FieldValues and belongs to a Database with On-Demand FieldValues updating."
- (u/the-id field) (:name field))
- (create-or-update-full-field-values! field)))))
-
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Serialization |
;;; +----------------------------------------------------------------------------------------------------------------+
diff --git a/test/metabase/models/on_demand_test.clj b/test/metabase/models/on_demand_test.clj
index 777d0cab9de..536d7f04ec7 100644
--- a/test/metabase/models/on_demand_test.clj
+++ b/test/metabase/models/on_demand_test.clj
@@ -3,6 +3,7 @@
(:require
[clojure.test :refer :all]
[metabase.dashboards.models.dashboard :as dashboard]
+ [metabase.sync.field-values :as sync.field-values]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
@@ -11,12 +12,20 @@
[toucan2.core :as t2]))
(defn- do-with-mocked-field-values-updating!
- "Run F the function responsible for updating FieldValues bound to a mock function that instead just records the names
- of Fields that should have been updated. Returns the set of updated Field names."
+ "Run `f` with the on-demand FieldValues update entry points stubbed out to just record which
+ field names would have been refreshed. Returns the set of updated Field names.
+
+ On-demand uses [[sync.field-values/sync-fields-grouped-by-table!]] on SQL drivers and falls
+ back to [[field-values/create-or-update-full-field-values!]] on non-SQL drivers; the mock
+ covers both so behavioural tests work regardless of the temp database's driver."
[f]
(let [updated-field-names (atom #{})]
- (mt/with-dynamic-fn-redefs [field-values/create-or-update-full-field-values! (fn [field]
- (swap! updated-field-names conj (:name field)))]
+ (mt/with-dynamic-fn-redefs [field-values/create-or-update-full-field-values!
+ (fn [field & _]
+ (swap! updated-field-names conj (:name field)))
+ sync.field-values/sync-fields-grouped-by-table!
+ (fn [fields]
+ (swap! updated-field-names into (map :name fields)))]
(f updated-field-names)
@updated-field-names)))
diff --git a/test/metabase/sync/field_values_test.clj b/test/metabase/sync/field_values_test.clj
index 20c5151fc92..e962664e600 100644
--- a/test/metabase/sync/field_values_test.clj
+++ b/test/metabase/sync/field_values_test.clj
@@ -6,10 +6,12 @@
[java-time.api :as t]
[metabase.analyze.core :as analyze]
[metabase.sync.core :as sync]
+ [metabase.sync.field-values :as sync.field-values]
[metabase.sync.util-test :as sync.util-test]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.test.data.one-off-dbs :as one-off-dbs]
+ [metabase.warehouse-schema.field-values.distinct-batch :as distinct-batch]
[metabase.warehouse-schema.models.field-values :as field-values]
[toucan2.core :as t2]))
@@ -23,6 +25,15 @@
[(sync.util-test/only-step-keys step-info)
(:task_details task-history)]))
+(defn- sync-database-counts!
+ "Like [[sync-database!']] but keeps only the create/update/delete/error counts. The
+ `:probed`/`:queries` observability counters are dropped — they're a function of how many
+ fields across the whole database have active FieldValues, which is global state these
+ whole-database sync tests don't (and shouldn't) pin down."
+ [step database]
+ (mapv #(select-keys % [:errors :created :updated :deleted])
+ (sync-database!' step database)))
+
(deftest sync-recreate-field-values-test
(testing "Test that when we delete FieldValues syncing the Table again will cause them to be re-created"
(testing "Check that we have expected field values to start with"
@@ -40,7 +51,7 @@
(venues-price-field-values))))
(testing "After the delete, a field values should not be created"
(is (= (repeat 2 {:errors 0, :created 0, :updated 0, :deleted 0})
- (sync-database!' "update-field-values" (data/db)))))
+ (sync-database-counts! "update-field-values" (data/db)))))
(testing "Now re-sync the table and make sure they're back"
;; Manually activate Field values since they are not created during sync (#53387)
(field-values/get-or-create-full-field-values! (t2/select-one :model/Field (mt/id :venues :price)))
@@ -63,7 +74,7 @@
(venues-price-field-values))))
(testing "Now re-sync the table and validate the field values updated"
(is (= (repeat 2 {:errors 0, :created 0, :updated 1, :deleted 0})
- (sync-database!' "update-field-values" (data/db)))))
+ (sync-database-counts! "update-field-values" (data/db)))))
(testing "Make sure the value is back"
(is (= [1 2 3 4]
(venues-price-field-values))))))
@@ -77,7 +88,7 @@
{:last_used_at (t/minus (t/offset-date-time) (t/days 20))
:values [1 2 3]})
(is (= (repeat 2 {:errors 0, :created 0, :updated 0, :deleted 0})
- (sync-database!' "update-field-values" (data/db))))
+ (sync-database-counts! "update-field-values" (data/db))))
(is (= [1 2 3] (venues-price-field-values)))
(testing "Fetching field values causes an on-demand update and marks Field Values as active"
(is (partial= {:values [[1] [2] [3] [4]]}
@@ -89,7 +100,7 @@
(t2/select-one-pk :model/FieldValues :field_id (mt/id :venues :price) :type :full)
{:values [1 2 3]})
(is (= (repeat 2 {:errors 0, :created 0, :updated 1, :deleted 0})
- (sync-database!' "update-field-values" (data/db))))
+ (sync-database-counts! "update-field-values" (data/db))))
(is (partial= {:values [[1] [2] [3] [4]]}
(mt/user-http-request :rasta :get 200 (format "field/%d/values" (mt/id :venues :price)))))))
(testing "If only advanced fields have been used recently, still sync"
@@ -102,7 +113,7 @@
:hash_key "random-key"
:last_used_at (t/instant)})
(is (= (repeat 2 {:errors 0, :created 0, :updated 1, :deleted 0})
- (sync-database!' "update-field-values" (data/db)))))
+ (sync-database-counts! "update-field-values" (data/db)))))
(is (= [1 2 3 4] (venues-price-field-values)))))
(finally
; clear out our changes to not mess up other tests. Changes are more than with-model-cleanup handles
@@ -240,14 +251,14 @@
:type :advanced
:hash_key "random-key"})
(testing "adding more values even if it's exceed our cardinality limit, "
- (one-off-dbs/insert-rows-and-sync! (one-off-dbs/range-str 50 (+ 100 field-values/*absolute-max-distinct-values-limit*)))
+ (one-off-dbs/insert-rows-and-sync! (one-off-dbs/range-str 50 (+ 100 field-values/*distinct-limit*)))
(testing "has_field_values shouldn't change and has_more_values should be true"
(is (= :list
(t2/select-one-fn :has_field_values :model/Field
:id (mt/id :blueberries_consumed :str)))))
- (testing "it should still have FieldValues, but the stored list has at most [metadata-queries/absolute-max-distinct-values-limit] elements"
- (is (= {:values (take field-values/*absolute-max-distinct-values-limit*
- (one-off-dbs/range-str (+ 100 field-values/*absolute-max-distinct-values-limit*)))
+ (testing "it should still have FieldValues, but the stored list has at most field-values/*distinct-limit* elements"
+ (is (= {:values (take field-values/*distinct-limit*
+ (one-off-dbs/range-str (+ 100 field-values/*distinct-limit*)))
:human_readable_values []
:has_more_values true}
(into {} (t2/select-one [:model/FieldValues :values :human_readable_values :has_more_values]
@@ -288,9 +299,107 @@
(one-off-dbs/insert-rows-and-sync! [(str/join (repeat 50 "A"))])
;; Manually activate Field values since they are not created during sync (#53387)
(field-values/get-or-create-full-field-values! (t2/select-one :model/Field (mt/id :blueberries_consumed :str)))
- ;; we throw ConnectException, which is a non-recoverable exception
- (mt/with-dynamic-fn-redefs [field-values/create-or-update-full-field-values! (fn [& _] (throw (java.net.ConnectException.)))]
+ ;; we throw ConnectException, which is a non-recoverable exception. Mock the SQL-path fetcher
+ ;; (run-distinct-batch) since that's what the H2 sync path will call.
+ (mt/with-dynamic-fn-redefs [distinct-batch/run-distinct-batch (fn [& _] (throw (java.net.ConnectException.)))]
(is (=?
{:steps [["delete-expired-advanced-field-values" {}]
["update-field-values" {:throwable #(instance? Exception %)}]]}
(sync/update-field-values! (data/db))))))))
+
+;;; ---------------------------------- can-batch-distinct? ----------------------------------
+
+(deftest can-batch-distinct?-test
+ (testing "SQL driver with :nested-queries and no required filter → batch path"
+ (mt/with-temp [:model/Database {db-id :id} {:engine :h2}
+ :model/Table table {:db_id db-id, :name "t", :database_require_filter false}]
+ (is (true? (#'sync.field-values/can-batch-distinct? table)))))
+ (testing "Tables with :database_require_filter true (e.g. partitioned BigQuery) fall back to per-field"
+ (mt/with-temp [:model/Database {db-id :id} {:engine :h2}
+ :model/Table table {:db_id db-id, :name "t", :database_require_filter true}]
+ (is (false? (#'sync.field-values/can-batch-distinct? table))
+ "Partitioned tables that require a WHERE on the partition column can't go through the
+ native UNION ALL path because it bypasses add-required-filters-if-needed middleware"))))
+
+;;; ---------------------------------- nested-JSON fields dispatch ----------------------------------
+
+(deftest ^:synchronized sync-fields-for-table!-routes-parent-id-fields-to-per-field-test
+ (testing "Fields with :parent_id (nested-JSON unfolded) go through the per-field path even when
+ the table is otherwise batch-able. Batching builds a CAST(name AS …) that doesn't
+ qualify the column with its parent, so the SQL would target the wrong column AND the
+ by-name lookup could collide if two child fields share a name across different parents
+ (e.g. JSON columns unfolded to `address.name` and `user.name`)."
+ (let [calls-to-fetch-distinct-for-table (atom [])
+ calls-to-fetch-distinct-per-field (atom [])]
+ (mt/with-temp [:model/Database {db-id :id} {:engine :h2}
+ :model/Table {tbl-id :id :as table} {:db_id db-id, :name "t"
+ :database_require_filter false}
+ :model/Field {parent-a :id} {:table_id tbl-id, :name "address"
+ :base_type :type/JSON, :has_field_values :list}
+ :model/Field {parent-b :id} {:table_id tbl-id, :name "user"
+ :base_type :type/JSON, :has_field_values :list}
+ :model/Field nested-a {:table_id tbl-id, :parent_id parent-a, :name "name"
+ :base_type :type/Text, :has_field_values :list}
+ :model/Field nested-b {:table_id tbl-id, :parent_id parent-b, :name "name"
+ :base_type :type/Text, :has_field_values :list}
+ :model/Field plain-c {:table_id tbl-id, :name "plain"
+ :base_type :type/Text, :has_field_values :list}]
+ (with-redefs [sync.field-values/fetch-distinct-for-table
+ (fn [_table fields]
+ (swap! calls-to-fetch-distinct-for-table conj (set (map :id fields)))
+ {:results (into {} (map (fn [f] [(:id f) {:values []}])) fields)
+ :queries 1
+ :failed-fields #{}})
+ sync.field-values/fetch-distinct-per-field
+ (fn [fields]
+ (swap! calls-to-fetch-distinct-per-field conj (set (map :id fields)))
+ {:results (into {} (map (fn [f] [(:id f) {:values []}])) fields)
+ :queries (count fields)
+ :failed-fields #{}})]
+ (#'sync.field-values/sync-fields-for-table! table [nested-a nested-b plain-c] {})
+ (testing "Plain field goes to batch path"
+ (is (= [#{(:id plain-c)}] @calls-to-fetch-distinct-for-table)))
+ (testing "Both nested-JSON children with the same name go to per-field, preserving each field's identity"
+ (is (= [#{(:id nested-a) (:id nested-b)}] @calls-to-fetch-distinct-per-field))))))))
+
+;;; ---------------------------------- sync-fields-grouped-by-table! ----------------------------------
+
+(deftest ^:mb/driver-tests ^:synchronized sync-fields-grouped-by-table!-test
+ (testing "End-to-end: fetches via UNION, persists via persist-field-values!, returns counts"
+ (mt/dataset test-data
+ (mt/with-temp [:model/FieldValues _ {:field_id (mt/id :people :state)
+ :type :full
+ :values ["XX" "YY"]
+ :has_more_values false}]
+ (let [field (t2/select-one :model/Field :id (mt/id :people :state))
+ counts (sync.field-values/sync-fields-grouped-by-table! [field])]
+ (is (map? counts) "Returns a counts map")
+ (is (= 1 (:probed counts)))
+ (testing "After sync, FieldValues row reflects the real distinct set"
+ (let [fv (t2/select-one :model/FieldValues
+ :field_id (mt/id :people :state)
+ :type :full)
+ states (set (:values fv))]
+ (is (contains? states "CA"))
+ (is (not (contains? states "XX")) "Stale seeded values were replaced"))))))))
+
+(deftest sync-fields-grouped-by-table!-empty-input-test
+ (testing "Empty/nil input → nil (no work)"
+ (is (nil? (sync.field-values/sync-fields-grouped-by-table! [])))
+ (is (nil? (sync.field-values/sync-fields-grouped-by-table! nil)))))
+
+(deftest ^:mb/driver-tests ^:synchronized union-batching-test
+ (testing "Field count > *batch-size* is broken into multiple queries; every field's counts are accounted for"
+ (mt/dataset test-data
+ (binding [distinct-batch/*batch-size* 2]
+ (let [fields (vec (t2/select :model/Field
+ :table_id (mt/id :people)
+ :active true
+ :visibility_type "normal"
+ {:order-by [[:name :asc]]}))
+ eligible-count (count (filter field-values/field-should-have-field-values? fields))
+ counts (sync.field-values/sync-fields-grouped-by-table! fields)]
+ (is (= eligible-count (:probed counts))
+ "Every FV-eligible field is reported as probed; sync-fields-grouped-by-table! drops the rest")
+ (is (>= (:queries counts) 2)
+ "More fields than *batch-size* should produce more than one query"))))))
diff --git a/test/metabase/warehouse_schema/models/field_values_test.clj b/test/metabase/warehouse_schema/models/field_values_test.clj
index 4e8ab423679..419f0aa04d5 100644
--- a/test/metabase/warehouse_schema/models/field_values_test.clj
+++ b/test/metabase/warehouse_schema/models/field_values_test.clj
@@ -1,10 +1,11 @@
-(ns metabase.warehouse-schema.models.field-values-test
+(ns ^:mb/driver-tests metabase.warehouse-schema.models.field-values-test
"Tests for specific behavior related to FieldValues and functions in
the [[metabase.warehouse-schema.models.field-values]] namespace."
(:require
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[java-time.api :as t]
+ [metabase.driver :as driver]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
[metabase.models.serialization :as serdes]
[metabase.sync.core :as sync]
@@ -12,6 +13,7 @@
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[metabase.util.json :as json]
+ [metabase.warehouse-schema.field-values.distinct-batch :as distinct-batch]
[metabase.warehouse-schema.models.field-values :as field-values]
[next.jdbc :as next.jdbc]
[toucan2.core :as t2])
@@ -171,22 +173,11 @@
(deftest distinct-values-test
(testing "Correctly get distinct field values for text fields"
- (is (= {:values [["Doohickey"] ["Gadget"] ["Gizmo"] ["Widget"]]
- :has_more_values false}
+ (is (= {:values [["Doohickey"] ["Gadget"] ["Gizmo"] ["Widget"]]}
(distinct-field-values (mt/id :products :category)))))
(testing "Correctly get distinct field values for non-text fields"
- (is (= {:values [[1] [2] [3] [4] [5]]
- :has_more_values false}
- (distinct-field-values (mt/id :reviews :rating)))))
- (testing "if the values of field exceeds max-char-len, return a subset of it (#2332)"
- (binding [field-values/*total-max-length* 16]
- (is (= {:values [["Doohickey"] ["Gadget"]]
- :has_more_values true}
- (distinct-field-values (mt/id :products :category)))))
- (binding [field-values/*total-max-length* 3]
- (is (= {:values [[1] [2] [3]]
- :has_more_values true}
- (distinct-field-values (mt/id :reviews :rating)))))))
+ (is (= {:values [[1] [2] [3] [4] [5]]}
+ (distinct-field-values (mt/id :reviews :rating))))))
(deftest clear-field-values-for-field!-test
(mt/with-temp [:model/Database {database-id :id} {}
@@ -489,3 +480,232 @@
(testing "Ambiguous queries are upgraded to ensure invalid rows are filtered"
(is (= {:type :full, :hash_key nil} (#'field-values/add-mismatched-hash-filter {:type :full})))
(is (= {:type :sandbox, :hash_key [:not= nil]} (#'field-values/add-mismatched-hash-filter {:type :sandbox})))))
+
+;;; ----------------------------------- limit-values ------------------------------------
+
+(deftest ^:parallel limit-values-empty-test
+ (is (= {:values [] :has_more_values false} (field-values/limit-values []))))
+
+(deftest ^:parallel limit-values-keeps-nils-test
+ (testing "nil is a meaningful distinct value (sorts first); only deduplicated, not dropped"
+ (is (= {:values [nil "a" "b"] :has_more_values false}
+ (field-values/limit-values [nil "a" nil "b" nil])))))
+
+(deftest ^:parallel limit-values-dedupes-and-sorts-test
+ (is (= {:values [1 2 3] :has_more_values false}
+ (field-values/limit-values [3 1 2 1 3 2])))
+ (is (= {:values ["a" "b" "c"] :has_more_values false}
+ (field-values/limit-values ["b" "a" "c" "a"]))))
+
+(deftest limit-values-applies-char-cap-test
+ (binding [field-values/*total-max-length* 10]
+ (testing "Values fitting under the cap come through unchanged"
+ (is (= {:values ["ab" "cd" "ef"] :has_more_values false}
+ (field-values/limit-values ["ab" "cd" "ef"]))))
+ (testing "Values exceeding the cap trigger has_more_values=true"
+ (let [{:keys [values has_more_values]} (field-values/limit-values
+ ["aaa" "bbb" "ccc" "ddddd" "eeeee" "fffff"])]
+ (is (true? has_more_values))
+ (is (< (transduce (map (comp count str)) + 0 values) 11)
+ "Returned values' total char length stays under the cap")))))
+
+;;; ----------------------------------- persist-field-values! ----------------------------
+
+(deftest persist-field-values!-creates-test
+ (testing "nil existing-fv → ::fv-created and a row is written"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {tbl-id :id} {:db_id db-id, :name "t"}
+ :model/Field {field-id :id :as field} {:table_id tbl-id, :name "f"
+ :has_field_values :list}]
+ (is (= ::field-values/fv-created
+ (field-values/persist-field-values! field nil ["a" "b"])))
+ (let [fv (t2/select-one :model/FieldValues :field_id field-id :type :full)]
+ (is (= ["a" "b"] (:values fv)))
+ (is (false? (:has_more_values fv)))))))
+
+(deftest persist-field-values!-skips-when-unchanged-test
+ (testing "Values + has_more_values both match → ::fv-skipped, no DB write"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {tbl-id :id} {:db_id db-id, :name "t"}
+ :model/Field {field-id :id :as field} {:table_id tbl-id, :name "f"
+ :has_field_values :list}
+ :model/FieldValues fv {:field_id field-id, :type :full, :values ["a" "b"], :has_more_values false}]
+ (is (= ::field-values/fv-skipped
+ (field-values/persist-field-values! field fv ["a" "b"]))))))
+
+(deftest persist-field-values!-updates-when-values-differ-test
+ (testing "Different values → ::fv-updated and the row is rewritten"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {tbl-id :id} {:db_id db-id, :name "t"}
+ :model/Field {field-id :id :as field} {:table_id tbl-id, :name "f"
+ :has_field_values :list}
+ :model/FieldValues fv {:field_id field-id, :type :full, :values ["a"], :has_more_values false}]
+ (is (= ::field-values/fv-updated
+ (field-values/persist-field-values! field fv ["a" "b" "c"])))
+ (is (= ["a" "b" "c"]
+ (:values (t2/select-one :model/FieldValues :field_id field-id :type :full)))))))
+
+(deftest persist-field-values!-updates-when-row-cap-hits-test
+ (testing "Raw count hits the warehouse row LIMIT → has_more_values flips to true → ::fv-updated"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {tbl-id :id} {:db_id db-id, :name "t"}
+ :model/Field {field-id :id :as field} {:table_id tbl-id, :name "f"
+ :has_field_values :list}
+ :model/FieldValues fv {:field_id field-id, :type :full, :values ["a" "b"], :has_more_values false}]
+ (binding [field-values/*distinct-limit* 2]
+ (is (= ::field-values/fv-updated
+ (field-values/persist-field-values! field fv ["a" "b"])))
+ (is (true? (:has_more_values (t2/select-one :model/FieldValues :field_id field-id :type :full))))))))
+
+(deftest persist-field-values!-updates-when-char-cap-hits-test
+ (testing "Char-length cap fires inside limit-values → has_more_values flips to true → ::fv-updated"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {tbl-id :id} {:db_id db-id, :name "t"}
+ :model/Field {field-id :id :as field} {:table_id tbl-id, :name "f"
+ :has_field_values :list}
+ :model/FieldValues fv {:field_id field-id, :type :full, :values ["aaa"], :has_more_values false}]
+ (binding [field-values/*total-max-length* 4]
+ (is (= ::field-values/fv-updated
+ (field-values/persist-field-values! field fv ["aaa" "bbb" "ccc"])))
+ (is (true? (:has_more_values (t2/select-one :model/FieldValues :field_id field-id :type :full))))))))
+
+(deftest persist-field-values!-deletes-when-empty-test
+ (testing "Empty raw-values → ::fv-deleted and the FieldValues row is removed"
+ (mt/with-temp [:model/Database {db-id :id} {}
+ :model/Table {tbl-id :id} {:db_id db-id, :name "t"}
+ :model/Field {field-id :id :as field} {:table_id tbl-id, :name "f"
+ :has_field_values :list}
+ :model/FieldValues _ {:field_id field-id, :type :full, :values ["a"], :has_more_values false}]
+ (is (= ::field-values/fv-deleted
+ (field-values/persist-field-values! field {:id 1 :values ["a"] :has_more_values false} [])))
+ (is (false? (t2/exists? :model/FieldValues :field_id field-id :type :full))))))
+
+;;; ---------------------------------- UNION DISTINCT primitive ----------------------------------
+
+(defn- sql-test-drivers
+ "Normal drivers that generate SQL. `run-distinct-batch` builds and runs a SQL query, so it
+ only applies to SQL drivers — non-SQL drivers (e.g. Mongo) go through the per-field fallback
+ at the sync layer and aren't exercised by these direct-call tests."
+ []
+ (into #{}
+ (filter #(isa? driver/hierarchy % :sql))
+ (mt/normal-drivers-with-feature :basic-aggregations)))
+
+(deftest decode-value-test
+ (testing "nil passes through"
+ (is (nil? (#'distinct-batch/decode-value :type/Text nil)))
+ (is (nil? (#'distinct-batch/decode-value :type/Integer nil)))
+ (is (nil? (#'distinct-batch/decode-value :type/Float nil))))
+ (testing "Text base-type → string passthrough"
+ (is (= "hello" (#'distinct-batch/decode-value :type/Text "hello")))
+ (is (= "" (#'distinct-batch/decode-value :type/Text ""))))
+ (testing "Integer base-type → Long"
+ (is (= 42 (#'distinct-batch/decode-value :type/Integer "42")))
+ (is (= -1 (#'distinct-batch/decode-value :type/Integer "-1"))))
+ (testing "BigInteger overflow → BigInteger"
+ (is (= 12345678901234567890N
+ (#'distinct-batch/decode-value :type/Integer "12345678901234567890")))
+ (is (= 12345678901234567890N
+ (#'distinct-batch/decode-value :type/BigInteger "12345678901234567890"))))
+ (testing "Boolean accepts true/t/1 (case-insensitive)"
+ (is (true? (#'distinct-batch/decode-value :type/Boolean "true")))
+ (is (true? (#'distinct-batch/decode-value :type/Boolean "TRUE")))
+ (is (true? (#'distinct-batch/decode-value :type/Boolean "True")))
+ (is (true? (#'distinct-batch/decode-value :type/Boolean "t")))
+ (is (true? (#'distinct-batch/decode-value :type/Boolean "1")))
+ (is (false? (#'distinct-batch/decode-value :type/Boolean "false")))
+ (is (false? (#'distinct-batch/decode-value :type/Boolean "FALSE")))
+ (is (false? (#'distinct-batch/decode-value :type/Boolean "f")))
+ (is (false? (#'distinct-batch/decode-value :type/Boolean "0"))))
+ (testing "Float base-type → Double"
+ (is (= 3.14 (#'distinct-batch/decode-value :type/Float "3.14")))
+ (is (= -0.5 (#'distinct-batch/decode-value :type/Float "-0.5")))
+ (is (= 0.0 (#'distinct-batch/decode-value :type/Float "0")))
+ (is (= 1.0e10 (#'distinct-batch/decode-value :type/Float "1.0E10"))))
+ (testing "Decimal base-type → BigDecimal (Decimal isa Float, so must come first in the cond)"
+ (is (= 3.14M (#'distinct-batch/decode-value :type/Decimal "3.14")))
+ (is (= 0M (#'distinct-batch/decode-value :type/Decimal "0")))
+ (is (= 1234567890.123M (#'distinct-batch/decode-value :type/Decimal "1234567890.123"))))
+ (testing "Decimal-derived semantic types (e.g. :type/Currency) → BigDecimal"
+ (is (= 19.99M (#'distinct-batch/decode-value :type/Currency "19.99"))))
+ (testing "Float-derived non-decimal types (e.g. :type/Coordinate) → Double"
+ (is (= 37.5 (#'distinct-batch/decode-value :type/Coordinate "37.5"))))
+ (testing "Malformed numeric input → string passthrough via catch"
+ (is (= "n/a" (#'distinct-batch/decode-value :type/Integer "n/a")))
+ (is (= "n/a" (#'distinct-batch/decode-value :type/Float "n/a")))
+ (is (= "n/a" (#'distinct-batch/decode-value :type/Decimal "n/a"))))
+ (testing "Types we don't decode (already JSON-encoded as strings by mi/transform-json) → string passthrough"
+ (is (= "2024-01-15" (#'distinct-batch/decode-value :type/Date "2024-01-15")))
+ (is (= "2024-01-15T10:30:00" (#'distinct-batch/decode-value :type/DateTime "2024-01-15T10:30:00")))
+ (is (= "10:30:00" (#'distinct-batch/decode-value :type/Time "10:30:00")))
+ (is (= "abc-def-1234" (#'distinct-batch/decode-value :type/UUID "abc-def-1234")))
+ (is (= "192.168.1.1" (#'distinct-batch/decode-value :type/IPAddress "192.168.1.1"))))
+ (testing "Unknown base-type → string passthrough"
+ (is (= "anything" (#'distinct-batch/decode-value :type/SomeMadeUpType "anything")))))
+
+(deftest ^:mb/driver-tests run-distinct-batch-integration-test
+ (testing "run-distinct-batch returns correct distinct values for each field"
+ (mt/test-drivers (sql-test-drivers)
+ (mt/dataset test-data
+ (let [table (t2/select-one :model/Table :id (mt/id :people))
+ fields [(t2/select-one :model/Field :id (mt/id :people :state))
+ (t2/select-one :model/Field :id (mt/id :people :source))]
+ results (distinct-batch/run-distinct-batch table fields)]
+ (is (map? results) "Returns a map keyed by field-id")
+ (is (= (set (map :id fields)) (set (keys results))))
+ (testing "people.state distinct values"
+ (let [{:keys [values raw-count]} (get results (mt/id :people :state))]
+ (is (pos? raw-count))
+ (is (every? string? values))
+ (is (every? #(= 2 (count %)) values) "US state abbreviations are 2-char")))
+ (testing "people.source distinct values"
+ (let [{:keys [values]} (get results (mt/id :people :source))]
+ (is (seq values))
+ (is (every? string? values)))))))))
+
+(deftest ^:mb/driver-tests run-distinct-batch-matches-per-field-test
+ (testing "run-distinct-batch returns the same value set per column as the per-field DISTINCT path"
+ ;; Cover Text (state), Boolean-shaped low-cardinality (source), and Float (rating). Only fields whose
+ ;; distinct count is below the per-column LIMIT — for columns that hit the cap, both paths return a
+ ;; valid subset but the warehouse is free to pick *which* 1000, and the subsets may differ across
+ ;; paths/engines without either being wrong.
+ (mt/test-drivers (sql-test-drivers)
+ (mt/dataset test-data
+ (let [people-table (t2/select-one :model/Table :id (mt/id :people))
+ products-table (t2/select-one :model/Table :id (mt/id :products))
+ text-fields (mapv #(t2/select-one :model/Field :id (mt/id :people %)) [:state :source])
+ float-fields (mapv #(t2/select-one :model/Field :id (mt/id :products %)) [:rating])
+ expected-set (fn [f] (set (map first (-> (field-values/distinct-values f) :values))))
+ per-field-results (into {} (map (fn [f] [(:id f) (expected-set f)])) (concat text-fields float-fields))
+ people-results (distinct-batch/run-distinct-batch people-table text-fields)
+ products-results (distinct-batch/run-distinct-batch products-table float-fields)
+ union-results (merge people-results products-results)]
+ (doseq [field (concat text-fields float-fields)]
+ (testing (format "field %s (%s)" (:name field) (name (:base_type field)))
+ (let [expected (get per-field-results (:id field))
+ actual (set (:values (get union-results (:id field))))]
+ (is (= expected actual)
+ (format "UNION distinct values differ from per-field DISTINCT for %s on %s"
+ (:name field) (name driver/*driver*)))))))))))
+
+(deftest ^:mb/driver-tests run-distinct-batch-cross-driver-test
+ (testing "run-distinct-batch produces correct results on every supported SQL driver"
+ (mt/test-drivers (sql-test-drivers)
+ (mt/dataset test-data
+ (let [table (t2/select-one :model/Table :id (mt/id :people))
+ state-field (t2/select-one :model/Field :id (mt/id :people :state))
+ source-field (t2/select-one :model/Field :id (mt/id :people :source))
+ results (distinct-batch/run-distinct-batch table [state-field source-field])]
+ (testing "Result map is keyed by field-id with :values / :raw-count entries"
+ (is (map? results))
+ (is (= #{(:id state-field) (:id source-field)} (set (keys results)))))
+ (testing "Returned values are non-empty Clojure values, not raw JDBC objects"
+ (let [{:keys [values]} (get results (:id state-field))]
+ (is (pos? (count values)))
+ (is (every? string? values)
+ (str "state-field values should decode to strings, got: " (pr-str (take 3 values))))))
+ (testing "Sources column returns a small distinct set"
+ (let [{:keys [values raw-count]} (get results (:id source-field))]
+ (is (< raw-count field-values/*distinct-limit*)
+ "source has few enough distinct values to not hit the LIMIT")
+ (is (every? string? values)))))))))