The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Route each module's app-DB queries through a db.clj namespace (#81824)
Alexander Polyankinff335470e724
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 24377c2fffb..34fae22741b 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -142,7 +142,6 @@metabase.activity-feed.coremetabase.activity-feed.init}:uses #{api- app-dbbatch-processingcollectionsconfig@@ -702,7 +701,7 @@modelsutil}:model-exports #{:model/ModerationReview}- :model-imports #{:model/Card :model/Dashboard}}+ :model-imports #{:model/Card :model/Dashboard :model/User}}contextual-interestingness{:team "UX West"@@ -1521,6 +1520,7 @@:model/Dashboard:model/DashboardTab:model/Database+ :model/Document:model/Field:model/Measure:model/NativeQuerySnippet@@ -1778,7 +1778,11 @@metabase.public-sharing.validation}:uses #{apisettings- util}}+ util}+ :model-imports #{:model/Action+ :model/Card+ :model/Dashboard+ :model/Document}}public-sharing-rest{:team "UX West"@@ -2246,7 +2250,8 @@premium-featuresutilenterprise/advanced-permissions}- :model-exports #{:model/Setting}}+ :model-exports #{:model/Setting}+ :model-imports #{:model/User}}settings-rest{:team "DevEx"@@ -2733,6 +2738,7 @@:model-imports #{:model/Dashboard:model/Database:model/PermissionsGroupMembership+ :model/PulseChannelRecipient:model/Tenant}}users-rest@@ -2792,7 +2798,10 @@query-permissionsutil}:model-exports #{:model/ViewLog}- :model-imports #{:model/Card :model/Dashboard :model/Table}}+ :model-imports #{:model/Card+ :model/Dashboard+ :model/Document+ :model/Table}}warehouse-schema{:team "UX West"@@ -3177,7 +3186,8 @@:uses #{apicontent-verificationutil- enterprise/api}}+ enterprise/api}+ :model-imports #{:model/Card :model/Dashboard}}enterprise/core{:team "DevEx"diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj b/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.cljindex e776336e4ec..eed28f57f20 100644--- a/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj+++ b/enterprise/backend/src/metabase_enterprise/action_v2/data_editing.clj@@ -3,6 +3,7 @@[clojure.set :as set][medley.core :as m][metabase-enterprise.action-v2.coerce :as data-editing.coerce]+ [metabase-enterprise.action-v2.db :as action-v2.db][metabase-enterprise.action-v2.models.undo :as undo][metabase.actions.core :as actions][metabase.api.common :as api]@@ -12,8 +13,7 @@[metabase.query-processor.core :as qp][metabase.sync.field-values :as sync.field-values][metabase.util :as u]- [metabase.util.queue :as queue]- [toucan2.core :as t2])+ [metabase.util.queue :as queue])(:import(java.util.concurrent ArrayBlockingQueue)))@@ -41,7 +41,7 @@(->> field-ids(partition-all *invalidate-select-batch-size*)(mapcat (fn [batch]- (t2/select :model/Field :id [:in batch])))))]+ (action-v2.db/fields batch)))))](sync.field-values/sync-fields-grouped-by-table! fields)))(defmethod queue/init-listener! ::FieldValueInvalidation [_]@@ -51,7 +51,7 @@(defn select-table-pk-fields"Given a table-id, return the :model/Field instances corresponding to its PK columns. Do not assume any ordering."[table-id]- (u/prog1 (api/check-404 (t2/select :model/Field :table_id table-id :semantic_type :type/PK :active true))+ (u/prog1 (api/check-404 (action-v2.db/pk-fields-for-table table-id))(api/check-500 (pos? (count <>)))))(defn get-row-pks@@ -86,7 +86,7 @@(assert (seq pk-fields) "Table must have at least one primary key column");; TODO pass in the db-id from above rather(when (seq rows)- (let [{:keys [db_id]} (api/check-404 (t2/select-one :model/Table table-id))+ (let [{:keys [db_id]} (api/check-404 (action-v2.db/table table-id))row-pks (seq (map (partial get-row-pks pk-fields) rows))](assert (every? valid-pks row-pks) "All rows must have valid primary keys")(let [mp (lib-be/application-database-metadata-provider db_id)@@ -118,7 +118,7 @@(let [input-keys (into #{} (mapcat keys) input-rows)field-names (map name input-keys)fields (when (seq field-names)- (t2/select :model/Field :table_id table-id :name [:in field-names]))+ (action-v2.db/fields-by-name table-id field-names))coerce-fn (->> (for [{field-name :name, :keys [coercion_strategy, semantic_type]} fields:when (not (isa? semantic_type :type/PK))][(keyword field-name)@@ -141,17 +141,10 @@ln->ids (when (seq lower-names)(u/group-by:lower_name :id- (t2/query {:select [:id [[:lower :name] :lower_name]]- :from [(t2/table-name :model/Field)]- :where [:and- [:= :table_id table-id]- [:in [:lower :name] lower-names]- [:in :has_field_values ["list" "auto-list"]]- [:= :semantic_type "type/Category"]]})))+ (action-v2.db/category-list-field-ids-by-name table-id lower-names)))stale-fields (->> (for [[lower-name field-ids] ln->ids:let [new-values (into #{} (filter some?) (ln->values lower-name))- old-values (into #{} cat (t2/select-fn-vec :values :model/FieldValues- :field_id [:in field-ids]))]]+ old-values (into #{} cat (action-v2.db/field-values-of-fields field-ids))]](when (seq (set/difference new-values old-values))field-ids))(apply concat))]diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/db.clj b/enterprise/backend/src/metabase_enterprise/action_v2/db.cljnew file mode 100644index 00000000000..84cc0182833--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/action_v2/db.clj@@ -0,0 +1,150 @@+(ns metabase-enterprise.action-v2.db+ "Application database queries for the action-v2 module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods, and transactions."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table table-id))++(defn active-table+ "The active Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id :active true))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn fields+ "The Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field :id [:in field-ids]))++(defn pk-fields-for-table+ "The active primary key Fields of the Table with `table-id`."+ [table-id]+ (t2/select :model/Field :table_id table-id :semantic_type :type/PK :active true))++(defn fields-by-name+ "The Fields of the Table with `table-id` named one of `field-names`."+ [table-id field-names]+ (t2/select :model/Field :table_id table-id :name [:in field-names]))++(defn active-fields-in-position-order+ "The active Fields of the Table with `table-id`, in position order."+ [table-id]+ (t2/select :model/Field :table_id table-id :active true {:order-by [[:position]]}))++(defn field-requirements-by-name+ "A map of name to the name, required flag, and base type of the Fields of the Table with `table-id`."+ [table-id]+ (t2/select-fn->fn :name identity [:model/Field :name :database_required :base_type] :table_id table-id))++(defn category-list-field-ids-by-name+ "The `:id` and `:lower_name` rows of the category list Fields of the Table with `table-id` whose name matches one+ of `names`, case-insensitively."+ [table-id names]+ (t2/query {:select [:id [[:lower :name] :lower_name]]+ :from [(t2/table-name :model/Field)]+ :where [:and+ [:= :table_id table-id]+ [:in [:lower :name] (map u/lower-case-en names)]+ [:in :has_field_values ["list" "auto-list"]]+ [:= :semantic_type "type/Category"]]}))++(defn field-values-of-fields+ "The value lists of the FieldValues of the Fields with `field-ids`."+ [field-ids]+ (t2/select-fn-vec :values :model/FieldValues :field_id [:in field-ids]))++(defn- scope-and-user-expr+ [scope user-id]+ [:and+ (when scope [:= :scope scope])+ (when user-id [:= :user_id user-id])])++(defn next-undo-batch+ "The Undo rows of the newest not-undone (when `undo?`) or oldest undone batch of `user-id` in `scope`."+ [undo? user-id scope]+ (t2/select :model/Undo+ :batch_num [:in+ ^:allow-subquery+ {:select [[[(if undo? :max :min) :batch_num]]]+ :from [(t2/table-name :model/Undo)]+ :where [:and+ [:= :user_id user-id]+ [:= :scope scope]+ (if undo?+ [:not :undone]+ :undone)]}]))++(defn batch-to-prune-from+ "The `:batch_num` row of the newest Undo batch beyond the `batches-to-keep` most recent ones, narrowed by the+ optional `scope` and `user-id`, or nil."+ [batches-to-keep scope user-id]+ (t2/query {:select [:batch_num]+ :from [(t2/table-name :model/Undo)]+ :where (scope-and-user-expr scope user-id)+ :group-by :batch_num+ :order-by [[:batch_num :desc]]+ :limit 1+ :offset batches-to-keep}))++(defn batch-to-prune-from-for-rows+ "The `:batch_num` row of the Undo row beyond the `rows-to-keep` most recent ones, or nil."+ [rows-to-keep]+ (t2/query {:select [:batch_num]+ :from [(t2/table-name :model/Undo)]+ :order-by [[:id :desc]]+ :limit 1+ :offset rows-to-keep}))++(defn delete-undo-batches-up-to!+ "Delete the Undo rows of batches up to `batch-num`, narrowed by the optional `scope` and `user-id`."+ [batch-num scope user-id]+ (t2/delete! :model/Undo :batch_num [:<= batch-num] {:where (scope-and-user-expr scope user-id)}))++(defn delete-undone-batches-from!+ "Delete the undone Undo rows in `scope` from batch `batch-num` onwards."+ [batch-num scope]+ (t2/delete! :model/Undo :batch_num [:>= batch-num] :scope scope :undone true))++(defn insert-undos!+ "Insert the Undo `undos`."+ [undos]+ (t2/insert! :model/Undo undos))++(defn mark-batch-undone!+ "Set the undone flag of the Undo batch `batch-num` to `undone?`."+ [batch-num undone?]+ (t2/update! :model/Undo {:batch_num batch-num} {:undone undone?}))++(defn superseding-change-exists?+ "Whether a later (when `undo?`) or earlier Undo row for the rows `row-pks` of the Tables `table-ids` exists beyond+ batch `batch-num` with the opposite undone state."+ [undo? table-ids row-pks batch-num]+ (t2/exists? :model/Undo+ :table_id [:in table-ids]+ :row_pk [:in row-pks]+ :batch_num [(if undo? :> :<) batch-num]+ :undone (not undo?)))++(defn lock-sequence-next-val+ "The next value of the raw sequence row named `sequence-name`, locked for update, or nil."+ [sequence-name]+ (t2/select-one-fn :next_val [:sequences :next_val] :name sequence-name {:for :update}))++(defn set-sequence-next-val!+ "Set the next value of the raw sequence row named `sequence-name`."+ [sequence-name next-val]+ (t2/update! :sequences {:name sequence-name} {:next_val next-val}))++(defn insert-sequence!+ "Insert a raw sequence row named `sequence-name` whose next value is `next-val`."+ [sequence-name next-val]+ (t2/insert! :sequences {:name sequence-name :next_val next-val}))diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.clj b/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.cljindex 7f9aa9ebfc6..481c16cb355 100644--- a/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.clj+++ b/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.action-v2.execute-form(:require+ [metabase-enterprise.action-v2.db :as action-v2.db][metabase.actions.core :as actions][metabase.api.common :as api][metabase.util :as u]@@ -89,13 +90,11 @@row-data]}](when-not table-id(throw (ex-info "Must provide table-id" {:status-code 400})))- (let [table (api/read-check (t2/select-one :model/Table :id table-id :active true))- database (t2/select-one :model/Database :id (:db_id table))+ (let [table (api/read-check (action-v2.db/active-table table-id))+ database (action-v2.db/database (:db_id table))_ (actions/check-data-editing-enabled-for-database! database)- fields (-> (t2/select :model/Field :table_id table-id :active true {:order-by [[:position]]})- (t2/hydrate :dimensions- :has_field_values- :values))+ fields (-> (action-v2.db/active-fields-in-position-order table-id)+ (t2/hydrate :dimensions :has_field_values :values));; TODO get this from action configuration, when we add it, or inherit from table configurationcolumn-editable? (constantly true);; TODO get this from action configuration, when we add it, or inherit from table configurationdiff --git a/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj b/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.cljindex ce6def7965f..e165cfb7798 100644--- a/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj+++ b/enterprise/backend/src/metabase_enterprise/action_v2/models/undo.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.action-v2.models.undo(:require[clojure.walk :as walk]+ [metabase-enterprise.action-v2.db :as action-v2.db][metabase.actions.core :as actions][metabase.models.interface :as mi][metabase.util :as u]@@ -40,64 +41,39 @@;; For now, we assume all the changes are to the same table.;; In the future, we might want to skip multi-table changes when using cmd-Z.;; We may also want to filter based on the type of interaction that caused the change (e.g., grid, workflow, etc)- (t2/select :model/Undo- :batch_num [:in- ^:allow-subquery- {:select [[[(if undo? :max :min) :batch_num]]]- :from [(t2/table-name :model/Undo)]- :where [:and- [:= :user_id user-id]- [:= :scope (serialize-scope scope)]- (if undo?- [:not :undone]- :undone)]}]))+ (action-v2.db/next-undo-batch undo? user-id (serialize-scope scope)))(defn- batch-to-prune-from"Return the largest batch_num that we should no longer retain, if we only want to keep a certain number of batches- matching the given where clause. Returns 0 if we do not need to prune anything."- [batches-to-keep & [where]]- (-> {:select [:batch_num]- :from [(t2/table-name :model/Undo)]- :where (or where true)- :group-by :batch_num- :order-by [[:batch_num :desc]]- :limit 1- :offset batches-to-keep}- t2/query+ in the optional `scope` or belonging to the optional `user-id`. Returns 0 if we do not need to prune anything."+ [batches-to-keep & {:keys [scope user-id]}]+ (-> (action-v2.db/batch-to-prune-from batches-to-keep scope user-id)first:batch_num(or 0)))(defn- batch-to-prune-from-for-rows"This is like [[batch-to-prune-from], except that we're enforcing a max on the row count."- [rows-to-keep & [where]]- (-> {:select [:batch_num]- :from [(t2/table-name :model/Undo)]- :where (or where true)- :order-by [[:id :desc]]- :limit 1- :offset rows-to-keep}- t2/query+ [rows-to-keep]+ (-> (action-v2.db/batch-to-prune-from-for-rows rows-to-keep)first:batch_num(or 0)))-(defn- prune-from-batch! [batch-num & [where]]- (t2/delete! :model/Undo- :batch_num [:<= batch-num]- {:where (or where true)}))+(defn- prune-from-batch! [batch-num & {:keys [scope user-id]}]+ (action-v2.db/delete-undo-batches-up-to! batch-num scope user-id))-(defn- prune-batches! [batches-to-keep & [where]]- (prune-from-batch! (batch-to-prune-from batches-to-keep where) where))+(defn- prune-batches! [batches-to-keep & {:keys [scope user-id] :as narrowing}]+ (prune-from-batch! (batch-to-prune-from batches-to-keep :scope scope :user-id user-id) narrowing))(defn- next-sequence![seq-name]- (if-let [batch-num (t2/select-one-fn :next_val [:sequences :next_val] :name seq-name {:for :update})]+ (if-let [batch-num (action-v2.db/lock-sequence-next-val seq-name)](do- (t2/update! :sequences {:name seq-name} {:next_val (inc batch-num)})+ (action-v2.db/set-sequence-next-val! seq-name (inc batch-num))batch-num)(do- (t2/insert! :sequences {:name seq-name :next_val 2})+ (action-v2.db/insert-sequence! seq-name 2)1)))(defn track-change!@@ -106,8 +82,7 @@(let [scope (serialize-scope scope)](t2/with-transaction [_conn](let [next-batch-num (next-sequence! "undo_batch_num")]- (t2/insert!- :model/Undo+ (action-v2.db/insert-undos!(for [[table-id table-updates] table-id->row-pk->values[row-pk values] table-updates](merge {:batch_num next-batch-num@@ -120,15 +95,12 @@values)))));; Delete snapshots that have been undone, as we keep a linear history and will no longer be able to "redo" them.(when-let [{:keys [batch_num]} (first (next-batch false user-id scope))]- (t2/delete! :model/Undo- :batch_num [:>= batch_num]- :scope scope- :undone true))+ (action-v2.db/delete-undone-batches-from! batch_num scope));; Pruning. Fairly naive implementation. Doesn't assume we were fully pruned before this update.(prune-from-batch! (max (batch-to-prune-from-for-rows retention-total-rows)(batch-to-prune-from retention-total-batches)))- (prune-batches! retention-batches-per-scope [:= :scope scope])- (prune-batches! retention-batches-per-user [:= :user_id user-id])))+ (prune-batches! retention-batches-per-scope :scope scope)+ (prune-batches! retention-batches-per-user :user-id user-id)));; This will be used to fix conflict false positives#_{:clj-kondo/ignore [:unused-private-var]}@@ -150,11 +122,7 @@;; Can store a precalculated [[diff-keys]] on each :model/Undo row, or even normalize into its own table and do;; conflict detection completely in SQL.;; This normal form may make maintenance of the history a bit too expensive however.- (t2/exists? :model/Undo- :table_id [:in table-ids]- :row_pk [:in row-pks]- :batch_num [(if undo? :> :<) batch_num]- :undone (not undo?))))+ (action-v2.db/superseding-change-exists? undo? table-ids row-pks batch_num)))(defn- categorize [{:keys [raw_before raw_after]}](cond@@ -225,9 +193,7 @@:scope scope})):else(do (update-table-data! undo-or-redo context batch)- (t2/update! :model/Undo- {:batch_num (:batch_num (first batch))}- {:undone undo?})+ (action-v2.db/mark-batch-undone! (:batch_num (first batch)) undo?)(for [[table-id sub-batch] (u/group-by :table_id batch):let [rows (batch->rows undo? sub-batch)][delta row] (map vector sub-batch rows)diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/validation.clj b/enterprise/backend/src/metabase_enterprise/action_v2/validation.cljindex 0af95f43303..b60ffb2f00c 100644--- a/enterprise/backend/src/metabase_enterprise/action_v2/validation.clj+++ b/enterprise/backend/src/metabase_enterprise/action_v2/validation.clj@@ -7,8 +7,8 @@Though we do want to have a light validation to gives users nice error messages."(:require[java-time.api :as t]- [metabase.util :as u]- [toucan2.core :as t2])+ [metabase-enterprise.action-v2.db :as action-v2.db]+ [metabase.util :as u])(:import(java.time OffsetDateTime LocalDate LocalTime LocalDateTime)(java.time.format DateTimeParseException)))@@ -136,7 +136,7 @@"Validate rows of a given table"[table-id-or-fields inputs](let [fields (if (int? table-id-or-fields)- (t2/select-fn->fn :name identity [:model/Field :name :database_required :base_type] :table_id table-id-or-fields)+ (action-v2.db/field-requirements-by-name table-id-or-fields)(u/index-by :name table-id-or-fields))errors (mapv #(validate-input % fields) inputs)](when (some some? errors)diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.cljindex 6cdb88c564f..2bd6b4bb8aa 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/api/logs.clj@@ -9,28 +9,18 @@[clojure.string :as str][malli.core :as mc][malli.transform :as mtx]+ [metabase-enterprise.advanced-config.db :as advanced-config.db][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.app-db.core :as mdb][metabase.util.i18n :refer [deferred-tru]][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(mu/defn query-execution-logs"Query to fetch the rows within the specified `month` of `year` from the `query_execution` table."[year :- ms/PositiveIntmonth :- ms/PositiveInt]- (let [date-part (fn [part-key part-value]- (if (= (mdb/db-type) :postgres)- [:= [:date_part ^:allow-raw-sql [:inline (name part-key)] :started_at] [:inline part-value]]- [:= [part-key :started_at] [:inline part-value]]))- results (t2/select :query_execution- {:order-by [[:started_at :desc]]- :where [:and- (date-part :year year)- (date-part :month month)]})]- results))+ (advanced-config.db/query-executions-in-month year month));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/db.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/db.cljnew file mode 100644index 00000000000..797afb4ef81--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/db.clj@@ -0,0 +1,79 @@+(ns metabase-enterprise.advanced-config.db+ "Application database queries for the advanced-config module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself."+ (:require+ [metabase.app-db.core :as mdb]+ [toucan2.core :as t2]))++(defn query-executions-in-month+ "The raw query execution rows started in `month` of `year`, newest first."+ [year month]+ (let [date-part (fn [part-key part-value]+ (if (= (mdb/db-type) :postgres)+ [:= [:date_part ^:allow-raw-sql [:inline (name part-key)] :started_at] part-value]+ [:= [part-key :started_at] part-value]))]+ (t2/select :query_execution+ {:order-by [[:started_at :desc]]+ :where [:and+ (date-part :year year)+ (date-part :month month)]})))++(defn api-key-by-name+ "The ApiKey named `api-key-name`, or nil."+ [api-key-name]+ (t2/select-one :model/ApiKey :name api-key-name))++(defn api-key-prefix-exists?+ "Whether an ApiKey with `prefix` exists."+ [prefix]+ (t2/exists? :model/ApiKey :key_prefix prefix))++(defn insert-api-key!+ "Insert `api-key` and return the new instance."+ [api-key]+ (t2/insert-returning-instance! :model/ApiKey api-key))++(defn user-by-email+ "The User with `email`, or nil."+ [email]+ (t2/select-one :model/User :email email))++(defn user-columns-by-email+ "The `columns` of the User with `email`, or nil."+ [columns email]+ (t2/select-one (into [:model/User] columns) :email email))++(defn insert-user!+ "Insert `user` and return the new instance."+ [user]+ (t2/insert-returning-instance! :model/User user))++(defn update-user!+ "Apply `changes` to the User with `user-id`."+ [user-id changes]+ (t2/update! :model/User user-id changes))++(defn sample-database-exists?+ "Whether the sample Database exists."+ []+ (t2/exists? :model/Database :is_sample true))++(defn database-id-by-engine-and-name+ "The ID of the Database of `engine` named `database-name`, or nil."+ [engine database-name]+ (t2/select-one-pk :model/Database :engine engine :name database-name))++(defn insert-database!+ "Insert `database` and return the new instance."+ [database]+ (t2/insert-returning-instance! :model/Database database))++(defn update-database!+ "Apply `changes` to the Database with `database-id`."+ [database-id changes]+ (t2/update! :model/Database database-id changes))++(defn delete-database!+ "Delete the Database with `database-id`."+ [database-id]+ (t2/delete! :model/Database database-id))diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.cljindex 5ef394e445f..f183e65b028 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/api_keys.clj@@ -2,14 +2,14 @@"Support for initializing API keys from a `config.yml` file."(:require[clojure.spec.alpha :as s]+ [metabase-enterprise.advanced-config.db :as advanced-config.db][metabase-enterprise.advanced-config.file.interface :as advanced-config.file.i][metabase.api-keys.core :as api-key][metabase.permissions.core :as perms][metabase.users.models.user :as user][metabase.util :as u][metabase.util.log :as log]- [metabase.util.secret :as u.secret]- [toucan2.core :as t2]))+ [metabase.util.secret :as u.secret]))(set! *warn-on-reflection* true)@@ -37,12 +37,12 @@(defn- select-api-key[name]- (t2/select-one :model/ApiKey :name name))+ (advanced-config.db/api-key-by-name name))(defn- get-admin-user-by-email"Find an admin user by email. Throws an exception if the user doesn't exist or isn't an admin."[email]- (let [user (t2/select-one :model/User :email email)]+ (let [user (advanced-config.db/user-by-email email)](when-not user(throw (ex-info (format "User with email %s not found" email){:email email})))@@ -70,28 +70,25 @@prefix (api-key/prefix (u.secret/expose unhashed-key))creator (get-admin-user-by-email creator)];; Check if there's an existing API key with the same prefix- (when (t2/exists? :model/ApiKey :key_prefix prefix)+ (when (advanced-config.db/api-key-prefix-exists? prefix)(throw (ex-info (format "API key with prefix '%s' already exists. Keys must have unique prefixes." prefix){:name name :prefix prefix})))(log/info (u/format-color :green "Creating new API key"));; Create a user for the API key(let [email (format "api-key-user-%[email protected]" (random-uuid))- user (first- (t2/insert-returning-instances! :model/User- {:email email+ user (advanced-config.db/insert-user! {:email email:first_name name:last_name "":type :api-key- :password (str (random-uuid))}))]+ :password (str (random-uuid))})];; Set permissions groups for the user(user/set-permissions-groups! user [(perms/all-users-group) {:id group-id}]);; Create the API key- (t2/insert-returning-instance! :model/ApiKey- {:user_id (u/the-id user)- :name name- ::api-key/unhashed-key unhashed-key- :creator_id (u/the-id creator)- :updated_by_id (u/the-id creator)}))))))+ (advanced-config.db/insert-api-key! {:user_id (u/the-id user)+ :name name+ ::api-key/unhashed-key unhashed-key+ :creator_id (u/the-id creator)+ :updated_by_id (u/the-id creator)}))))))(defmethod advanced-config.file.i/initialize-section! :api-keys[_section-name api-keys]diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.cljindex 8a54b51ed51..3182e16e441 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/databases.clj@@ -3,14 +3,14 @@[clojure.set :as set][clojure.spec.alpha :as s][medley.core :as m]+ [metabase-enterprise.advanced-config.db :as advanced-config.db][metabase-enterprise.advanced-config.file.interface :as advanced-config.file.i][metabase-enterprise.advanced-config.settings :as advanced-config.settings][metabase.driver.util :as driver.u][metabase.sample-data.core :as sample-data][metabase.util :as u][metabase.util.log :as log]- [metabase.util.quick-task :as quick-task]- [toucan2.core :as t2]))+ [metabase.util.quick-task :as quick-task]))(s/def :metabase-enterprise.advanced-config.file.databases.config-file-spec/namestring?)@@ -86,7 +86,7 @@{:status-code 400:name (:name database):engine (:engine database)})))- (if (t2/exists? :model/Database :is_sample true)+ (if (advanced-config.db/sample-database-exists?)(log/info "Sample Database already present; ignoring is_sample config entry")(do(log/info (u/format-color :green "Recreating Sample Database from is_sample config entry"))@@ -104,9 +104,9 @@(when (not= magic-request (:delete database))(throw (ex-info (format "To delete database %s set `delete` to %s" (pr-str (:name database)) (pr-str magic-request)){:database-name (:name database)})))- (when-let [existing-database-id (t2/select-one-pk :model/Database :engine (:engine database), :name (:name database))]+ (when-let [existing-database-id (advanced-config.db/database-id-by-engine-and-name (:engine database) (:name database))](log/info (u/format-color :blue "Deleting Database %s with ID %s" (:engine database) existing-database-id))- (t2/delete! :model/Database existing-database-id)))+ (advanced-config.db/delete-database! existing-database-id)))(:is_sample database)(init-sample-database! database)@@ -118,7 +118,7 @@(when-not (:is_stub database)(driver.u/with-database-network-policy database(driver.u/can-connect-with-details? (keyword (:engine database)) (:details database) :throw-exceptions)))- (if-let [existing-database-id (t2/select-one-pk :model/Database :engine (:engine database), :name (:name database))]+ (if-let [existing-database-id (advanced-config.db/database-id-by-engine-and-name (:engine database) (:name database))](if (:is_stub database);; A stub entry is just a placeholder to satisfy serdes references. If a real database;; with this name+engine already exists, leave it alone — overwriting it with `:details {}`@@ -128,10 +128,10 @@(let [database (cond-> database(:is_attached_dwh database) strip-attached-dwh-update-ks)](log/info (u/format-color :blue "Updating Database %s with ID %s" (:engine database) existing-database-id))- (t2/update! :model/Database existing-database-id (normalize-settings database))))+ (advanced-config.db/update-database! existing-database-id (normalize-settings database))))(do(log/info (u/format-color :green "Creating new %s Database" (:engine database)))- (let [db (first (t2/insert-returning-instances! :model/Database (normalize-settings database)))]+ (let [db (advanced-config.db/insert-database! (normalize-settings database))](cond(:is_stub database)(log/info "Created stub database; skipping sync.")diff --git a/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj b/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.cljindex 70e9771116c..77ec1e7fbde 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_config/file/users.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.advanced-config.file.users(:require[clojure.spec.alpha :as s]+ [metabase-enterprise.advanced-config.db :as advanced-config.db][metabase-enterprise.advanced-config.file.interface:as advanced-config.file.i][metabase.auth-identity.core :as auth-identity]@@ -34,7 +35,7 @@(defn- select-user[email]- (t2/select-one (vec (cons :model/User user/admin-or-self-visible-columns)) :email email))+ (advanced-config.db/user-columns-by-email user/admin-or-self-visible-columns email))(defn- init-from-config-file![user]@@ -48,14 +49,14 @@(log/info (u/format-color :blue "Updating User %d" (:id existing-user)))(let [new-user (update user :login_attributes#(merge % (:login_attributes existing-user)))]- (t2/update! :model/User (:id existing-user) new-user))+ (advanced-config.db/update-user! (:id existing-user) new-user))(:id existing-user));; create a new user. If they are the first non-internal User, force them to be an admin.(let [user (cond-> user(not (setup/has-user-setup)) (assoc :is_superuser true))](log/info (u/colorize :green "Creating the first User for this instance. The first user is always created as an admin."))(log/info (u/colorize :green "Creating new User"))- (u/the-id (t2/insert-returning-instance! :model/User user))))]+ (u/the-id (advanced-config.db/insert-user! user))))];; passwords live in the AuthIdentity, not on the User row(auth-identity/set-password! user-id password))))diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.cljindex 58070bffb4c..708aaa78fe6 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/common.clj@@ -1,13 +1,13 @@(ns metabase-enterprise.advanced-permissions.common(:require+ [metabase-enterprise.advanced-permissions.db :as advanced-permissions.db][metabase.api.common :as api][metabase.audit-app.core :as audit][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.remote-sync.core :as remote-sync][metabase.util :as u]- [metabase.warehouses.models.database :as database]- [toucan2.core :as t2]))+ [metabase.warehouses.models.database :as database]))(defenterprise current-user-can-write-field?"Enterprise version. Returns a boolean whether the current user can write the given field.@@ -16,7 +16,7 @@:feature :advanced-permissions[instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (advanced-permissions.db/table (:table_id instance)))](and (remote-sync/table-editable? table)(let [db-id (or (:db_id table)(database/table-id->database-id (:table_id instance)))]@@ -91,8 +91,7 @@(defn current-user-is-manager-of-group?"Return true if current-user is a manager of `group-or-id`."[group-or-id]- (t2/select-one-fn :is_group_manager :model/PermissionsGroupMembership- :user_id api/*current-user-id* :group_id (u/the-id group-or-id)))+ (advanced-permissions.db/group-manager? api/*current-user-id* (u/the-id group-or-id)))(defn filter-tables-by-data-model-perms"Given a list of tables, removes the ones for which `*current-user*` does not have data model editing permissions."@@ -172,23 +171,11 @@(if (empty? db-ids){}(let [all-users-group-id (u/the-id (perms/all-users-group))- blocked-db-ids (t2/select-fn-set :db_id :model/DataPermissions- :perm_type :perms/view-data- :perm_value :blocked- :group_id all-users-group-id- :db_id [:in db-ids]- {:select-distinct [:db_id]})- impersonation-db-ids (t2/select-fn-set :db_id :model/ConnectionImpersonation- :group_id all-users-group-id- :db_id [:in db-ids])+ blocked-db-ids (advanced-permissions.db/blocked-database-ids-for-group all-users-group-id db-ids)+ impersonation-db-ids (advanced-permissions.db/impersonated-database-ids-for-group all-users-group-id db-ids)sandbox-db-ids (into #{}(map :db_id)- (t2/query {:select [[:t.db_id :db_id]]- :from [[(t2/table-name :model/Sandbox) :s]]- :join [[(t2/table-name :model/Table) :t] [:= :s.table_id :t.id]]- :where [:and- [:= :s.group_id all-users-group-id]- [:in :t.db_id db-ids]]}))+ (advanced-permissions.db/sandboxed-database-ids-for-group all-users-group-id db-ids))blocked-dbs (into (or blocked-db-ids #{})(concat impersonation-db-ids sandbox-db-ids))](zipmap db-ids (map #(if (blocked-dbs %) :blocked :unrestricted) db-ids)))))@@ -199,15 +186,9 @@[group-ids](if (empty? group-ids){}- (let [blocked-group-ids (t2/select-fn-set :group_id :model/DataPermissions- :perm_type :perms/view-data- :perm_value :blocked- :group_id [:in group-ids]- {:select-distinct [:group_id]})- impersonation-group-ids (t2/select-fn-set :group_id :model/ConnectionImpersonation- :group_id [:in group-ids])- sandbox-group-ids (t2/select-fn-set :group_id :model/Sandbox- :group_id [:in group-ids])+ (let [blocked-group-ids (advanced-permissions.db/blocked-group-ids group-ids)+ impersonation-group-ids (advanced-permissions.db/impersonated-group-ids group-ids)+ sandbox-group-ids (advanced-permissions.db/sandboxed-group-ids group-ids)blocked-groups (into (or blocked-group-ids #{})(concat impersonation-group-ids sandbox-group-ids))](zipmap group-ids (map #(if (blocked-groups %) :blocked :unrestricted) group-ids)))))@@ -220,20 +201,10 @@{};; We don't check for connection impersonations here, because impersonations are set at the;; DB-level, so a new table should get `:unrestricted` and inherit the DB-level impersonation policy.- (let [blocked-group-ids (t2/select-fn-set :group_id :model/DataPermissions- :db_id db-id- :perm_type :perms/view-data- :perm_value :blocked- :group_id [:in group-ids]- {:select-distinct [:group_id]})+ (let [blocked-group-ids (advanced-permissions.db/blocked-group-ids-for-database db-id group-ids)sandbox-group-ids (into #{}(map :group_id)- (t2/query {:select [[:s.group_id :group_id]]- :from [[(t2/table-name :model/Sandbox) :s]]- :join [[(t2/table-name :model/Table) :t] [:= :t.id :s.table_id]]- :where [:and- [:in :s.group_id group-ids]- [:= :t.db_id db-id]]}))+ (advanced-permissions.db/sandboxed-group-ids-for-database db-id group-ids))blocked-groups (into (or blocked-group-ids #{})sandbox-group-ids)](zipmap group-ids (map #(if (blocked-groups %) :blocked :unrestricted) group-ids)))))diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/db.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/db.cljnew file mode 100644index 00000000000..499eebdc7c2--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/db.clj@@ -0,0 +1,98 @@+(ns metabase-enterprise.advanced-permissions.db+ "Application database queries for the advanced-permissions module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself."+ (:require+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn group-manager?+ "Whether the User with `user-id` manages the PermissionsGroup with `group-id`."+ [user-id group-id]+ (t2/select-one-fn :is_group_manager :model/PermissionsGroupMembership :user_id user-id :group_id group-id))++(defn blocked-database-ids-for-group+ "The subset of `database-ids` the group with `group-id` is blocked from viewing."+ [group-id database-ids]+ (t2/select-fn-set :db_id :model/DataPermissions+ :perm_type :perms/view-data+ :perm_value :blocked+ :group_id group-id+ :db_id [:in database-ids]+ {:select-distinct [:db_id]}))++(defn impersonated-database-ids-for-group+ "The subset of `database-ids` the group with `group-id` accesses through connection impersonation."+ [group-id database-ids]+ (t2/select-fn-set :db_id :model/ConnectionImpersonation :group_id group-id :db_id [:in database-ids]))++(defn sandboxed-database-ids-for-group+ "The `:db_id` rows of the Databases among `database-ids` the group with `group-id` has a sandbox on."+ [group-id database-ids]+ (t2/query {:select [[:t.db_id :db_id]]+ :from [[(t2/table-name :model/Sandbox) :s]]+ :join [[(t2/table-name :model/Table) :t] [:= :s.table_id :t.id]]+ :where [:and+ [:= :s.group_id group-id]+ [:in :t.db_id database-ids]]}))++(defn blocked-group-ids+ "The subset of `group-ids` blocked from viewing some Database."+ [group-ids]+ (t2/select-fn-set :group_id :model/DataPermissions+ :perm_type :perms/view-data+ :perm_value :blocked+ :group_id [:in group-ids]+ {:select-distinct [:group_id]}))++(defn impersonated-group-ids+ "The subset of `group-ids` with a connection impersonation."+ [group-ids]+ (t2/select-fn-set :group_id :model/ConnectionImpersonation :group_id [:in group-ids]))++(defn sandboxed-group-ids+ "The subset of `group-ids` with a sandbox."+ [group-ids]+ (t2/select-fn-set :group_id :model/Sandbox :group_id [:in group-ids]))++(defn blocked-group-ids-for-database+ "The subset of `group-ids` blocked from viewing the Database with `database-id`."+ [database-id group-ids]+ (t2/select-fn-set :group_id :model/DataPermissions+ :db_id database-id+ :perm_type :perms/view-data+ :perm_value :blocked+ :group_id [:in group-ids]+ {:select-distinct [:group_id]}))++(defn sandboxed-group-ids-for-database+ "The `:group_id` rows of the groups among `group-ids` with a sandbox on the Database with `database-id`."+ [database-id group-ids]+ (t2/query {:select [[:s.group_id :group_id]]+ :from [[(t2/table-name :model/Sandbox) :s]]+ :join [[(t2/table-name :model/Table) :t] [:= :t.id :s.table_id]]+ :where [:and+ [:in :s.group_id group-ids]+ [:= :t.db_id database-id]]}))++(defn application-permissions+ "The Permissions rows for the root object and every application object."+ []+ (t2/select :model/Permissions+ {:where [:or+ [:= :object "/"]+ [:like :object (h2x/literal "/application/%")]]}))++(defn user-group-memberships+ "The group ID (as `:id`) and manager flag of the memberships of the User with `user-id`."+ [user-id]+ (t2/select [:model/PermissionsGroupMembership [:group_id :id] :is_group_manager] :user_id user-id))++(defn managed-group-ids+ "The IDs of the PermissionsGroups the User with `user-id` manages."+ [user-id]+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id :is_group_manager true))diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.cljindex 0d00522338f..700ce7af48d 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/application_permissions.clj@@ -3,8 +3,8 @@for more details and for the code for generating and updating the *data* permissions graph."(:require[clojure.data :as data]+ [metabase-enterprise.advanced-permissions.db :as advanced-permissions.db][metabase.permissions.core :as perms]- [metabase.util.honey-sql-2 :as h2x][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -34,10 +34,7 @@"Returns a map of group-id -> application permissions paths.Only groups that has at least one application permission enabled will be included."[]- (let [application-permissions (t2/select :model/Permissions- {:where [:or- [:= :object "/"]- [:like :object (h2x/literal "/application/%")]]})]+ (let [application-permissions (advanced-permissions.db/application-permissions)](into {} (for [[group-id perms] (group-by :group_id application-permissions)]{group-id (set (map :object perms))}))))diff --git a/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/group_manager.clj b/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/group_manager.cljindex 3e35b376528..a6e01ad1eb3 100644--- a/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/group_manager.clj+++ b/enterprise/backend/src/metabase_enterprise/advanced_permissions/models/permissions/group_manager.clj@@ -2,6 +2,7 @@(:require[clojure.data :as data][clojure.set :as set]+ [metabase-enterprise.advanced-permissions.db :as advanced-permissions.db][metabase.api.common :as api][metabase.permissions.core :as perms][metabase.util :as u]@@ -13,7 +14,7 @@Group Membership is a map with 2 keys [:id :is_group_manager]."[user-or-id](when user-or-id- (t2/select [:model/PermissionsGroupMembership [:group_id :id] :is_group_manager] :user_id (u/the-id user-or-id))))+ (advanced-permissions.db/user-group-memberships (u/the-id user-or-id))))(defn- user-group-memberships->map"Transform user-group-memberships to a map in which keys are group-ids and values are maps containing membership info.@@ -51,8 +52,7 @@;; prevent groups manager from update membership of groups that they're not manager of(when-not (and api/*is-group-manager?*(set/subset? (set (concat to-remove-group-ids to-add-group-ids))- (t2/select-fn-set :group_id :model/PermissionsGroupMembership- :user_id api/*current-user-id* :is_group_manager true)))+ (advanced-permissions.db/managed-group-ids api/*current-user-id*)))(throw (ex-info (tru "Not allowed to edit group memberships"){:status-code 403}))))(t2/with-transaction [_conn]diff --git a/enterprise/backend/src/metabase_enterprise/agent_api/db.clj b/enterprise/backend/src/metabase_enterprise/agent_api/db.cljnew file mode 100644index 00000000000..925968bf48b--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/agent_api/db.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.agent-api.db+ "Application database queries for the agent-api module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn insert-call-log!+ "Insert the AgentApiCallLog `row`."+ [row]+ (t2/insert! :model/AgentApiCallLog row))++(defn delete-call-logs-created-before!+ "Delete the AgentApiCallLogs created before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/AgentApiCallLog {:where [:< :created_at cutoff]}))diff --git a/enterprise/backend/src/metabase_enterprise/agent_api/task/agent_api_usage_trimmer.clj b/enterprise/backend/src/metabase_enterprise/agent_api/task/agent_api_usage_trimmer.cljindex fae514aac17..c9f8d476b5c 100644--- a/enterprise/backend/src/metabase_enterprise/agent_api/task/agent_api_usage_trimmer.clj+++ b/enterprise/backend/src/metabase_enterprise/agent_api/task/agent_api_usage_trimmer.clj@@ -9,10 +9,10 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.agent-api.db :as agent-api.db][metabase.metabot.settings :as metabot.settings][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(org.quartz DisallowConcurrentExecution)))@@ -28,7 +28,7 @@(log/info "Skipping Agent API usage log cleanup; ai-usage-max-retention-days is 0 (infinite retention).")(let [cutoff (t/minus (t/offset-date-time) (t/days (long retention-days)))](log/infof "Trimming Agent API usage log rows older than %d days." (long retention-days))- (let [calls (t2/delete! :model/AgentApiCallLog {:where [:< :created_at cutoff]})]+ (let [calls (agent-api.db/delete-call-logs-created-before! cutoff)](log/infof "Agent API usage log cleanup complete. Deleted %d call rows." (or calls 0)))))))(task/defjob ^{DisallowConcurrentExecution truediff --git a/enterprise/backend/src/metabase_enterprise/agent_api/usage.clj b/enterprise/backend/src/metabase_enterprise/agent_api/usage.cljindex 7c2ca62de13..f98a0c98624 100644--- a/enterprise/backend/src/metabase_enterprise/agent_api/usage.clj+++ b/enterprise/backend/src/metabase_enterprise/agent_api/usage.clj@@ -7,13 +7,13 @@(itself `:audit-app`-gated). Every write is best-effort: a failure is logged and swallowed sologging never fails the Agent API request and adds negligible latency."(:require+ [metabase-enterprise.agent-api.db :as agent-api.db][metabase.agent-api.usage :as agent-api.usage][metabase.analytics.core :as analytics][metabase.analytics.settings :as analytics.settings][metabase.premium-features.core :refer [defenterprise]][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -38,15 +38,15 @@pii (select-keys (analytics/pii-fields-from {:user-agent user-agent:ip-address ip-address})[:ip_address])]- (t2/insert! :model/AgentApiCallLog- (merge {:user_id user-id- :tenant_id tenant-id- :client_name (agent-api.usage/detect-client user-agent)- :operation (some-> operation (u/truncate operation-max-length))- :status status- :duration_ms duration-ms- :error_message (when (analytics.settings/analytics-pii-retention-enabled)- (some-> error-message (u/truncate error-message-max-length)))}- pii)))+ (agent-api.db/insert-call-log!+ (merge {:user_id user-id+ :tenant_id tenant-id+ :client_name (agent-api.usage/detect-client user-agent)+ :operation (some-> operation (u/truncate operation-max-length))+ :status status+ :duration_ms duration-ms+ :error_message (when (analytics.settings/analytics-pii-retention-enabled)+ (some-> error-message (u/truncate error-message-max-length)))}+ pii)))(catch Throwable e(log/warn e "Failed to record Agent API call"))))diff --git a/enterprise/backend/src/metabase_enterprise/analytics/db.clj b/enterprise/backend/src/metabase_enterprise/analytics/db.cljnew file mode 100644index 00000000000..00a5a0fe0b6--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/analytics/db.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.analytics.db+ "Application database queries for the analytics module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn database-with-engine-exists?+ "Whether a Database whose engine is one of `engines` exists."+ [engines]+ (t2/exists? :model/Database :engine [:in engines]))++(defn sandbox-exists?+ "Whether any Sandbox exists."+ []+ (t2/exists? :model/Sandbox))diff --git a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj b/enterprise/backend/src/metabase_enterprise/analytics/stats.cljindex 7d3b4e531f9..744502c94c4 100644--- a/enterprise/backend/src/metabase_enterprise/analytics/stats.clj+++ b/enterprise/backend/src/metabase_enterprise/analytics/stats.clj@@ -1,13 +1,13 @@(ns metabase-enterprise.analytics.stats(:require[metabase-enterprise.advanced-config.settings :as advanced-config.settings]+ [metabase-enterprise.analytics.db :as analytics.db][metabase-enterprise.mfa.core :as mfa][metabase-enterprise.scim.core :as scim][metabase-enterprise.semantic-search.core :as semantic-search][metabase-enterprise.sso.settings :as ee-sso-settings][metabase.driver :as driver]- [metabase.premium-features.core :as premium-features :refer [defenterprise]]- [toucan2.core :as t2]))+ [metabase.premium-features.core :as premium-features :refer [defenterprise]]))(defenterprise ee-snowplow-features-data"A subset of feature information included in the daily Snowplow stats report. This function only returns information@@ -31,8 +31,8 @@(mfa/mfa-enabled?))}{:name :sandboxes:available (and (premium-features/enable-official-collections?)- (t2/exists? :model/Database :engine [:in (descendants driver/hierarchy :sql)]))- :enabled (t2/exists? :model/Sandbox)}+ (analytics.db/database-with-engine-exists? (descendants driver/hierarchy :sql)))+ :enabled (analytics.db/sandbox-exists?)}{:name :email-allow-list:available (premium-features/enable-email-allow-list?):enabled (some? (advanced-config.settings/subscription-allowed-domains))}diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/analytics_dev.clj b/enterprise/backend/src/metabase_enterprise/audit_app/analytics_dev.cljindex 71bfc5414de..ca6fc00a114 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/analytics_dev.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/analytics_dev.clj@@ -13,6 +13,7 @@[clojure.string :as str][clojure.walk :as walk][metabase-enterprise.audit-app.audit :as audit-ee]+ [metabase-enterprise.audit-app.db :as audit-app.db][metabase-enterprise.audit-app.permissions :as audit-ee.permissions][metabase-enterprise.serialization.core :as serialization][metabase.app-db.core :as mdb]@@ -23,8 +24,7 @@[metabase.startup.core :as startup][metabase.sync.core :as sync][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.io File)(java.nio.file Files)@@ -52,7 +52,7 @@(defn find-analytics-dev-database"Finds existing analytics dev database."[]- (t2/select-one :model/Database :name canonical-db-name :is_audit false))+ (audit-app.db/non-audit-database-named canonical-db-name))(defn create-analytics-dev-database!"Creates a Database entry pointing to the app database for analytics development.@@ -74,16 +74,16 @@(do(log/info "Analytics dev database already exists:" (:id existing))existing)- (let [db (t2/insert-returning-instance! :model/Database- {:name canonical-db-name- :description "Development database for analytics views and content"- :engine (name db-type)- :details {:is-audit-dev true}- :is_audit false ; Important: not an audit DB- :is_full_sync true- :is_on_demand false- :creator_id user-id- :auto_run_queries true})]+ (let [db (audit-app.db/insert-returning-database!+ {:name canonical-db-name+ :description "Development database for analytics views and content"+ :engine (name db-type)+ :details {:is-audit-dev true}+ :is_audit false ; Important: not an audit DB+ :is_full_sync true+ :is_on_demand false+ :creator_id user-id+ :auto_run_queries true})](log/info "Created analytics dev database:" (:id db))(sync/sync-database! db {:scan :schema})db))))@@ -92,7 +92,7 @@"Deletes the analytics dev database and all related metadata."[db-id](log/info "Deleting analytics dev database:" db-id)- (t2/delete! :model/Database :id db-id)+ (audit-app.db/delete-database! db-id)(log/info "Deleted analytics dev database"));;; ============================================================================@@ -280,12 +280,12 @@(defn- first-admin-user"Get the first admin user (by ID)."[]- (t2/select-one [:model/User :id :email] :is_superuser true {:order-by [[:id :asc]]}))+ (audit-app.db/first-superuser))(defn find-analytics-collection"Get the analytics collection"[]- (t2/select-one :model/Collection :entity_id audit/default-audit-collection-entity-id))+ (audit-app.db/collection-by-entity-id audit/default-audit-collection-entity-id))(defn- analytics-content-loaded?"Check if analytics content has already been imported."@@ -294,8 +294,8 @@(find-analytics-collection)))(defn- cleanup-real-analytics []- (t2/delete! :model/Database :is_audit true)- (t2/delete! :model/Collection :namespace "analytics"))+ (audit-app.db/delete-audit-databases!)+ (audit-app.db/delete-analytics-collections!))(defn- analytics-dev-mode-setup [](when (audit/analytics-dev-mode)diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/api/user.clj b/enterprise/backend/src/metabase_enterprise/audit_app/api/user.cljindex 8325b806613..e2dcaa4022a 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/api/user.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/api/user.clj@@ -2,14 +2,14 @@"`/api/ee/audit-app/user` endpoints. These only work if you have a premium token with the `:audit-app` feature."(:require[metabase-enterprise.audit-app.audit :as ee-audit]+ [metabase-enterprise.audit-app.db :as audit-app.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.audit-app.core :as audit][metabase.models.interface :as mi][metabase.users.core :as users][metabase.util :as u]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -42,9 +42,9 @@(users/check-self-or-superuser id);; delete all `PulseChannelRecipient` rows for this User, which means they will no longer receive any;; Alerts/DashboardSubscriptions- (t2/delete! :model/PulseChannelRecipient :user_id id)- (t2/delete! :model/NotificationRecipient :user_id id)+ (audit-app.db/delete-pulse-channel-recipients-of-user! id)+ (audit-app.db/delete-notification-recipients-of-user! id);; archive anything they created.- (t2/update! :model/Pulse {:creator_id id, :archived false} {:archived true})- (t2/update! :model/Notification {:creator_id id :active true} {:active false})+ (audit-app.db/archive-pulses-of-creator! id)+ (audit-app.db/deactivate-notifications-of-creator! id)api/generic-204-no-content)diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj b/enterprise/backend/src/metabase_enterprise/audit_app/audit.cljindex 80dfb2f5a79..3042232b89b 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/audit.clj@@ -4,6 +4,7 @@[clojure.java.io :as io][clojure.string :as str][medley.core :as m]+ [metabase-enterprise.audit-app.db :as audit-app.db][metabase-enterprise.audit-app.settings :as audit-app.settings][metabase-enterprise.serialization.cmd :as serialization.cmd][metabase.app-db.cluster-lock :as cluster-lock]@@ -66,17 +67,17 @@;; one transaction so a crash can't commit the database row yet skip the permissions guard below —;; the next boot would see the database and no-op, leaving the stale permissions with no re-run path(t2/with-transaction [_conn]- (t2/insert! :model/Database {:is_audit true- :id id- :name default-db-name- :description "Internal Audit DB used to power metabase analytics."- :engine engine- :is_full_sync true- :is_on_demand false- :creator_id nil- :auto_run_queries true})+ (audit-app.db/insert-database! {:is_audit true+ :id id+ :name default-db-name+ :description "Internal Audit DB used to power metabase analytics."+ :engine engine+ :is_full_sync true+ :is_on_demand false+ :creator_id nil+ :auto_run_queries true});; guard against someone manually deleting the audit-db entry, but not removing the audit-db permissions.- (t2/delete! :model/Permissions {:where [:like :object (str "%/db/" id "/%")]})))+ (audit-app.db/delete-permissions-for-database! id)))(defn- adjust-audit-db-to-source![{audit-db-id :id}]@@ -85,54 +86,18 @@;; The flip commits, so on a multi-node mysql/h2 cluster other nodes can see engine="postgres" while;; the load runs — the longstanding behavior of this pipeline (only #76551's single-transaction era;; briefly hid it). Resolving serialized names against an overlay instead would avoid even that.- (t2/update! :model/Database audit-db-id {:engine "postgres"})+ (audit-app.db/set-database-engine! audit-db-id "postgres");; do a separate select and update of table ids that are not downcased;; we don't want to try to downcase audit db tables that may already have a downcased version;; some older migrations have both upper and lowercased table names;; just grab the ids separately since there aren't many and this kind of check in an update;; has different syntax on different appdbs- (let [table-ids-to-update (t2/query {:select [:table.id]- :from [[(t2/table-name :model/Table) :table]]- :where [:and [:= :table.db_id audit-db-id]- ;; Exclude DATABASECHANGELOG, DATABASECHANGELOGLOCK, and QRTZ_* tables, they are not metabase managed- [:not= :table.name "DATABASECHANGELOG"]- [:not= :table.name "DATABASECHANGELOGLOCK"] ;; new instances do not get this file, but existing instances may have it- [:not [:like :table.name "QRTZ_%"]]- [:not [:exists ^:allow-subquery {:select [1]- :from [[(t2/table-name :model/Table) :self_table]]- :where [:and- [:= :self_table.db_id :table.db_id]- [:or- [:= :self_table.schema [:lower :table.schema]]- [:and- [:= :self_table.schema "public"]- [:= :table.schema nil]]]- [:= :self_table.name [:lower :table.name]]]}]]]})]+ (let [table-ids-to-update (audit-app.db/table-ids-to-downcase audit-db-id)](when (seq table-ids-to-update)- (t2/update! :model/Table :id [:in (map :id table-ids-to-update)]- {:schema "public" :name [:lower :name]})))- (let [field-ids-to-update (t2/query {:select [:field.id]- :from [[(t2/table-name :model/Field) :field]]- :inner-join [[(t2/table-name :model/Table) :table]- [:= :table.id :field.table_id]]- :where [:and [:= :table.db_id audit-db-id]- [:not= :table.name "DATABASECHANGELOG"]- [:not [:like :table.name "QRTZ_%"]]- [:not [:exists ^:allow-subquery {:select [1]- :from [[(t2/table-name :model/Field) :self_field]]- :inner-join [[(t2/table-name :model/Table) :self_table]- [:= :self_table.id :self_field.table_id]]- :where [:and- [:= :self_table.db_id :table.db_id]- [:or- [:= :self_table.schema [:lower :table.schema]]- [:and- [:= :self_table.schema "public"]- [:= :table.schema nil]]]- [:= :self_field.name [:lower :field.name]]]}]]]})]+ (audit-app.db/downcase-tables! table-ids-to-update)))+ (let [field-ids-to-update (audit-app.db/field-ids-to-downcase audit-db-id)](when (seq field-ids-to-update)- (t2/update! :model/Field :id [:in (map :id field-ids-to-update)]- {:name [:lower :name]})))+ (audit-app.db/downcase-fields! field-ids-to-update)))(log/info "Adjusted Audit DB for loading Analytics Content"))(defn- fix-h2-card-metadata! [audit-db-id]@@ -148,28 +113,22 @@(.setInt stmt 2 (:id card))(.addBatch stmt))))nil- (t2/reducible-select [(t2/table-name :model/Card) :id :result_metadata] :database_id audit-db-id))+ (audit-app.db/card-result-metadata-reducible audit-db-id))(.executeBatch stmt))))(defn- adjust-audit-db-to-host![{audit-db-id :id :keys [engine] :as audit-db}](when-not (= engine (mdb/db-type));; We need to move the loaded data back to the host db- (t2/update! :model/Database audit-db-id {:engine (name (mdb/db-type))})+ (audit-app.db/set-database-engine! audit-db-id (name (mdb/db-type)))(case (mdb/db-type):mysql- (t2/update! :model/Table {:db_id audit-db-id} {:schema nil})+ (audit-app.db/clear-table-schemas! audit-db-id):h2(do- (t2/update! :model/Table {:db_id audit-db-id} {:schema [:upper :schema] :name [:upper :name]})- (t2/update! :model/Field- {:table_id- [:in- ^:allow-subquery {:select [:id]- :from [(t2/table-name :model/Table)]- :where [:= :db_id audit-db-id]}]}- {:name [:upper :name]})+ (audit-app.db/upcase-tables! audit-db-id)+ (audit-app.db/upcase-fields! audit-db-id)(fix-h2-card-metadata! audit-db-id)):postgres@@ -264,7 +223,7 @@half-applied state left by an interrupted `adjust-audit-db-to-host!`."[audit-db-id](and (not= :postgres (mdb/db-type))- (t2/exists? :model/Table :db_id audit-db-id :schema "public" :active true)))+ (audit-app.db/active-public-table-exists? audit-db-id)))(defn- maybe-load-analytics-content!"Loads serialized audit content from the classpath if its checksum has changed.@@ -294,7 +253,7 @@(if loaded?(log/info (str "Loading Analytics Content Complete (" (count (:seen report)) ") entities loaded."))(log/info (str "Error Loading Analytics Content: " (pr-str report))))- (when-let [{:keys [engine] :as audit-db} (t2/select-one :model/Database :is_audit true)]+ (when-let [{:keys [engine] :as audit-db} (audit-app.db/audit-database)](let [original-engine engine](adjust-audit-db-to-host! audit-db);; GHY-3974 Mode B: advance the checksum only after the host-adjust completes, so an@@ -305,7 +264,7 @@(defn- maybe-install-audit-db![]- (let [audit-db (t2/select-one :model/Database :is_audit true)+ (let [audit-db (audit-app.db/audit-database)result (cond(not (audit-app.settings/install-analytics-database))(u/prog1 ::blocked@@ -324,7 +283,7 @@:else::no-op)](when (contains? #{::installed ::updated} result)- (when-let [db (t2/select-one :model/Database :is_audit true)]+ (when-let [db (audit-app.db/audit-database)](log/info "Syncing Audit DB")(log/with-no-logs (sync/sync-database! db {:scan :schema}))))result))@@ -383,12 +342,12 @@[orphan-table-id survivor-table-id](let [survivor-by-name (into {}(map (juxt (comp u/lower-case-en :name) :id))- (t2/select [:model/Field :id :name] :table_id survivor-table-id))]+ (audit-app.db/field-names-of-table survivor-table-id))](into {}(keep (fn [{:keys [id name]}](when-let [survivor-field-id (survivor-by-name (u/lower-case-en name))][id survivor-field-id])))- (t2/select [:model/Field :id :name] :table_id orphan-table-id))))+ (audit-app.db/field-names-of-table orphan-table-id))))(defn- remap-result-metadata-ref"Remap the Field ID of a single result-metadata `:field_ref` via `field-id-remap`. Handles legacy refs@@ -423,13 +382,13 @@when the orphan is deleted. Field ids are remapped onto the survivor's same-named fields."[orphan-table-id survivor-table-id](let [field-id-remap (orphan->survivor-field-ids orphan-table-id survivor-table-id)]- (doseq [card (t2/select :model/Card :table_id orphan-table-id)]- (t2/update! :model/Card (:id card)- (cond-> {:dataset_query (-> (:dataset_query card)- (lib/replace-table-ids {orphan-table-id survivor-table-id})- (lib/replace-field-ids field-id-remap))}- (:result_metadata card)- (assoc :result_metadata (remap-result-metadata field-id-remap (:result_metadata card))))))))+ (doseq [card (audit-app.db/cards-of-table orphan-table-id)]+ (audit-app.db/update-card! (:id card)+ (cond-> {:dataset_query (-> (:dataset_query card)+ (lib/replace-table-ids {orphan-table-id survivor-table-id})+ (lib/replace-field-ids field-id-remap))}+ (:result_metadata card)+ (assoc :result_metadata (remap-result-metadata field-id-remap (:result_metadata card))))))))(defn- reconcile-audit-db-duplicates!"Collapse duplicate `metabase_table` rows for the same audit view into a single active row at the host-canonical@@ -443,8 +402,7 @@[audit-db-id];; order by id in the query so every selection below (including the `referenced?` tiebreak) is deterministic;;; group-by preserves this order within each group- (let [groups (->> (t2/select [:model/Table :id :name :schema :active] :db_id audit-db-id- {:order-by [[:id :asc]]})+ (let [groups (->> (audit-app.db/tables-of-database-in-id-order audit-db-id)(group-by (comp u/lower-case-en :name))(filter (fn [[_ rows]] (> (count rows) 1))))](doseq [[_ rows] groups]@@ -453,9 +411,7 @@(t2/with-transaction [_conn](let [referenced-ids (into #{}(map :table_id)- (t2/query {:select-distinct [:table_id]- :from [(t2/table-name :model/Card)]- :where [:in :table_id (map :id rows)]}))+ (audit-app.db/table-ids-referenced-by-cards (map :id rows)))survivor (or (first (filter (comp referenced-ids :id) rows))(first (filter :active rows))(first rows))@@ -465,11 +421,11 @@;; new (name, schema) can't collide with an orphan still sitting at that slot on idx_unique_table(doseq [{orphan-id :id} orphans](repoint-cards-to-survivor! orphan-id (:id survivor))- (t2/delete! :model/Table orphan-id))+ (audit-app.db/delete-table! orphan-id));; clear is_defective_duplicate so the survivor re-enters idx_unique_table (its unique_table_helper is;; NULL — and thus excluded from the index — while the flag is set)- (t2/update! :model/Table (:id survivor)- {:active true :name c-name :schema c-schema :is_defective_duplicate false})+ (audit-app.db/update-table! (:id survivor)+ {:active true :name c-name :schema c-schema :is_defective_duplicate false})(log/infof "Reconciled %d duplicate audit view row(s) onto table id %s"(count orphans) (:id survivor)))))))@@ -504,7 +460,7 @@(try(cluster-lock/with-detached-cluster-lock {:lock audit-db-cluster-lock :timeout-seconds 5 :retry-config {:max-retries 2}}(u/prog1 (maybe-install-audit-db!)- (when-let [audit-db (t2/select-one :model/Database :is_audit true)]+ (when-let [audit-db (audit-app.db/audit-database)]((sync-util/with-duplicate-ops-prevented:sync-database audit-db(fn []diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/db.clj b/enterprise/backend/src/metabase_enterprise/audit_app/db.cljnew file mode 100644index 00000000000..b79713f2b2f--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/audit_app/db.clj@@ -0,0 +1,211 @@+(ns metabase-enterprise.audit-app.db+ "Application database queries for the audit-app module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for transactions and connections."+ (:require+ [toucan2.core :as t2]))++(defn audit-database+ "The audit Database, or nil."+ []+ (t2/select-one :model/Database :is_audit true))++(defn non-audit-database-named+ "The non-audit Database named `database-name`, or nil."+ [database-name]+ (t2/select-one :model/Database :name database-name :is_audit false))++(defn insert-database!+ "Insert the Database `row`."+ [row]+ (t2/insert! :model/Database row))++(defn insert-returning-database!+ "Insert the Database `row` and return the new instance."+ [row]+ (t2/insert-returning-instance! :model/Database row))++(defn set-database-engine!+ "Set the engine of the Database with `database-id`."+ [database-id engine]+ (t2/update! :model/Database database-id {:engine engine}))++(defn delete-database!+ "Delete the Database with `database-id`."+ [database-id]+ (t2/delete! :model/Database :id database-id))++(defn delete-audit-databases!+ "Delete every audit Database."+ []+ (t2/delete! :model/Database :is_audit true))++(defn delete-permissions-for-database!+ "Delete the Permissions rows on the Database with `database-id`."+ [database-id]+ (t2/delete! :model/Permissions {:where [:like :object (str "%/db/" database-id "/%")]}))++(defn tables-of-database-named+ "The Tables of the Database with `database-id` named one of `table-names`."+ [database-id table-names]+ (t2/select :model/Table :db_id database-id :name [:in table-names]))++(defn tables-of-database-in-id-order+ "The `:id`, `:name`, `:schema`, and `:active` of the Tables of the Database with `database-id`, in ID order."+ [database-id]+ (t2/select [:model/Table :id :name :schema :active] :db_id database-id {:order-by [[:id :asc]]}))++(defn active-public-table-exists?+ "Whether the Database with `database-id` has an active Table in the `public` schema."+ [database-id]+ (t2/exists? :model/Table :db_id database-id :schema "public" :active true))++(defn table-ids-to-downcase+ "The IDs of the Metabase-managed Tables of the Database with `database-id` that have no lower-cased counterpart+ yet."+ [database-id]+ (mapv :id+ (t2/query {:select [:table.id]+ :from [[(t2/table-name :model/Table) :table]]+ :where [:and [:= :table.db_id database-id]+ ;; Exclude DATABASECHANGELOG, DATABASECHANGELOGLOCK, and QRTZ_* tables, they are not metabase managed+ [:not= :table.name "DATABASECHANGELOG"]+ [:not= :table.name "DATABASECHANGELOGLOCK"] ;; new instances do not get this file, but existing instances may have it+ [:not [:like :table.name "QRTZ_%"]]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[(t2/table-name :model/Table) :self_table]]+ :where [:and+ [:= :self_table.db_id :table.db_id]+ [:or+ [:= :self_table.schema [:lower :table.schema]]+ [:and+ [:= :self_table.schema "public"]+ [:= :table.schema nil]]]+ [:= :self_table.name [:lower :table.name]]]}]]]})))++(defn downcase-tables!+ "Move the Tables with `table-ids` to the `public` schema and lower-case their names."+ [table-ids]+ (t2/update! :model/Table :id [:in table-ids] {:schema "public" :name [:lower :name]}))++(defn field-ids-to-downcase+ "The IDs of the Fields of the Metabase-managed Tables of the Database with `database-id` that have no+ lower-cased counterpart yet."+ [database-id]+ (mapv :id+ (t2/query {:select [:field.id]+ :from [[(t2/table-name :model/Field) :field]]+ :inner-join [[(t2/table-name :model/Table) :table]+ [:= :table.id :field.table_id]]+ :where [:and [:= :table.db_id database-id]+ [:not= :table.name "DATABASECHANGELOG"]+ [:not [:like :table.name "QRTZ_%"]]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[(t2/table-name :model/Field) :self_field]]+ :inner-join [[(t2/table-name :model/Table) :self_table]+ [:= :self_table.id :self_field.table_id]]+ :where [:and+ [:= :self_table.db_id :table.db_id]+ [:or+ [:= :self_table.schema [:lower :table.schema]]+ [:and+ [:= :self_table.schema "public"]+ [:= :table.schema nil]]]+ [:= :self_field.name [:lower :field.name]]]}]]]})))++(defn downcase-fields!+ "Lower-case the names of the Fields with `field-ids`."+ [field-ids]+ (t2/update! :model/Field :id [:in field-ids] {:name [:lower :name]}))++(defn clear-table-schemas!+ "Clear the schema of the Tables of the Database with `database-id`."+ [database-id]+ (t2/update! :model/Table {:db_id database-id} {:schema nil}))++(defn upcase-tables!+ "Upper-case the schemas and names of the Tables of the Database with `database-id`."+ [database-id]+ (t2/update! :model/Table {:db_id database-id} {:schema [:upper :schema] :name [:upper :name]}))++(defn upcase-fields!+ "Upper-case the names of the Fields of the Database with `database-id`."+ [database-id]+ (t2/update! :model/Field+ {:table_id+ [:in+ ^:allow-subquery {:select [:id]+ :from [(t2/table-name :model/Table)]+ :where [:= :db_id database-id]}]}+ {:name [:upper :name]}))++(defn update-table!+ "Apply `changes` to the Table with `table-id`."+ [table-id changes]+ (t2/update! :model/Table table-id changes))++(defn delete-table!+ "Delete the Table with `table-id`."+ [table-id]+ (t2/delete! :model/Table table-id))++(defn field-names-of-table+ "The `:id` and `:name` of the Fields of the Table with `table-id`."+ [table-id]+ (t2/select [:model/Field :id :name] :table_id table-id))++(defn card-result-metadata-reducible+ "Reducible raw `:id` and `:result_metadata` rows of the Cards of the Database with `database-id`."+ [database-id]+ (t2/reducible-select [(t2/table-name :model/Card) :id :result_metadata] :database_id database-id))++(defn cards-of-table+ "The Cards on the Table with `table-id`."+ [table-id]+ (t2/select :model/Card :table_id table-id))++(defn table-ids-referenced-by-cards+ "The distinct `:table_id` rows of the Cards on the Tables with `table-ids`."+ [table-ids]+ (t2/query {:select-distinct [:table_id]+ :from [(t2/table-name :model/Card)]+ :where [:in :table_id table-ids]}))++(defn update-card!+ "Apply `changes` to the Card with `card-id`."+ [card-id changes]+ (t2/update! :model/Card card-id changes))++(defn first-superuser+ "The `:id` and `:email` of the oldest superuser, or nil."+ []+ (t2/select-one [:model/User :id :email] :is_superuser true {:order-by [[:id :asc]]}))++(defn collection-by-entity-id+ "The Collection with `entity-id`, or nil."+ [entity-id]+ (t2/select-one :model/Collection :entity_id entity-id))++(defn delete-analytics-collections!+ "Delete the Collections of the analytics namespace."+ []+ (t2/delete! :model/Collection :namespace "analytics"))++(defn delete-pulse-channel-recipients-of-user!+ "Delete the PulseChannelRecipients of the User with `user-id`."+ [user-id]+ (t2/delete! :model/PulseChannelRecipient :user_id user-id))++(defn delete-notification-recipients-of-user!+ "Delete the NotificationRecipients of the User with `user-id`."+ [user-id]+ (t2/delete! :model/NotificationRecipient :user_id user-id))++(defn archive-pulses-of-creator!+ "Archive the unarchived Pulses created by the User with `user-id`."+ [user-id]+ (t2/update! :model/Pulse {:creator_id user-id, :archived false} {:archived true}))++(defn deactivate-notifications-of-creator!+ "Deactivate the active Notifications created by the User with `user-id`."+ [user-id]+ (t2/update! :model/Notification {:creator_id user-id :active true} {:active false}))diff --git a/enterprise/backend/src/metabase_enterprise/audit_app/permissions.clj b/enterprise/backend/src/metabase_enterprise/audit_app/permissions.cljindex b1a8e6ea254..f551828f6a1 100644--- a/enterprise/backend/src/metabase_enterprise/audit_app/permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/audit_app/permissions.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.audit-app.permissions(:require+ [metabase-enterprise.audit-app.db :as audit-app.db][metabase.audit-app.core :as audit][metabase.lib.metadata :as lib.metadata][metabase.models.interface :as mi]@@ -9,8 +10,7 @@;; legacy usage -- don't do things like this going forward^{:clj-kondo/ignore [:deprecated-namespace :discouraged-namespace]} [metabase.query-processor.store :as qp.store][metabase.util :as u]- [metabase.util.i18n :refer [tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [tru]]))(def audit-db-view-names"Used for giving granular permissions into the audit db. Instead of granting permissions to@@ -74,7 +74,7 @@(let [create-queries-value (case tyype(:read :write) :query-builder:none :no)- view-tables (t2/select :model/Table :db_id audit/audit-db-id :name [:in audit-db-view-names])]+ view-tables (audit-app.db/tables-of-database-named audit/audit-db-id audit-db-view-names)](doseq [table view-tables](perms/set-table-permission! group-id table :perms/create-queries create-queries-value))(cond-> changesdiff --git a/enterprise/backend/src/metabase_enterprise/billing/api.clj b/enterprise/backend/src/metabase_enterprise/billing/api.cljindex 4029837ac03..3a04a7b1865 100644--- a/enterprise/backend/src/metabase_enterprise/billing/api.clj+++ b/enterprise/backend/src/metabase_enterprise/billing/api.clj@@ -5,6 +5,7 @@[clojure.core.memoize :as memoize][clojure.string :as str][java-time.api :as t]+ [metabase-enterprise.billing.db :as billing.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.premium-features.core :as premium-features]@@ -12,8 +13,7 @@[metabase.util :as u][metabase.util.date-2.parse :as u.date.parse][metabase.util.i18n :as i18n]- [metabase.util.json :as json]- [toucan2.core :as t2])+ [metabase.util.json :as json])(:import[com.fasterxml.jackson.core JsonParseException]))@@ -50,7 +50,7 @@(let [max-users (premium-features/max-users-allowed);; There is a defsetting for user count, but it is only updated every 5 minutes, and this should be exactly up;; to date here:- total-users (t2/count :model/User :is_active true, :type :personal)]+ total-users (billing.db/active-personal-user-count)]{:version "v1":content [{:name "Users included in your plan" :value max-users :format "integer" :display "value"}{:name "Users available" :value (- max-users total-users) :format "integer" :display "value"}@@ -66,7 +66,7 @@using the embedding token and signed in user's email to fetch the billing information."[](let [token (premium-features/premium-embedding-token)- email (t2/select-one-fn :email :model/User :id api/*current-user-id*)+ email (billing.db/user-email api/*current-user-id*)language (i18n/user-locale-string)](if (and token (str/starts-with? token "airgap_"))(billing-status)diff --git a/enterprise/backend/src/metabase_enterprise/billing/db.clj b/enterprise/backend/src/metabase_enterprise/billing/db.cljnew file mode 100644index 00000000000..5137a88d46b--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/billing/db.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.billing.db+ "Application database queries for the billing module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn active-personal-user-count+ "The number of active personal Users."+ []+ (t2/count :model/User :is_active true :type :personal))++(defn user-email+ "The email of the User with `user-id`."+ [user-id]+ (t2/select-one-fn :email :model/User :id user-id))diff --git a/enterprise/backend/src/metabase_enterprise/cache/db.clj b/enterprise/backend/src/metabase_enterprise/cache/db.cljnew file mode 100644index 00000000000..ffd2d108b24--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/cache/db.clj@@ -0,0 +1,144 @@+(ns metabase-enterprise.cache.db+ "Application database queries for the cache module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++(defn card-cache-config+ "The most specific CacheConfig applying to the Card with `card-id` on the Dashboard with `dashboard-id` in the+ Database with `database-id`, or nil."+ [card-id dashboard-id database-id]+ (let [qs (for [[i model model-id] [[1 "question" card-id]+ [2 "dashboard" dashboard-id]+ [3 "database" database-id]+ [4 "root" 0]]+ :when model-id]+ ^:allow-subquery+ {:from [:cache_config]+ :select [:id+ [[:inline i] :ordering]]+ :where [:and+ [:= :model model]+ [:= :model_id model-id]]})]+ (t2/select-one :model/CacheConfig+ :id ^:allow-subquery {:from [[^:allow-subquery {:union-all qs} :unused_alias]]+ :select [:id]+ :order-by :ordering+ :limit [:inline 1]})))++(defn cards-by-id+ "A map of ID to Card for `card-ids`."+ [card-ids]+ (t2/select-pk->fn identity :model/Card :id [:in card-ids]))++(defn router-database-ids+ "The subset of `database-ids` that are database routers."+ [database-ids]+ (t2/select-fn-set :database_id :model/DatabaseRouter :database_id [:in database-ids]))++(defn duration-cache-configs+ "The duration CacheConfigs that refresh automatically."+ []+ (t2/select :model/CacheConfig :strategy :duration :refresh_automatically true))++(defn duration-queries-to-rerun+ "The query definitions to rerun for the duration cache `scopes`, each `{:model :model-id :rerun-cutoff}`, counting+ only executions started after `started-after`; `parameterized?` selects parameterized or plain queries."+ [scopes started-after parameterized?]+ (t2/select+ :model/Query+ {:select [:u.query :u.cache-hash :u.card-id :u.dashboard-id :u.count]+ :from [[^:allow-subquery+ {:union (for [{:keys [model model-id rerun-cutoff]} scopes]+ ^:allow-subquery+ {:nest+ ^:allow-subquery+ {:select [[:q.query :query]+ [:qc.query_hash :cache-hash]+ [:qe.card_id :card-id]+ [:qe.dashboard_id :dashboard-id]+ [[:count :q.query_hash] :count]]+ :from [[(t2/table-name :model/Query) :q]]+ :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]+ [(t2/table-name :model/QueryCache) :qc] [:= :qc.query_hash :qe.cache_hash]]+ :where [:and+ (case model+ "question" [:= :qe.card_id model-id]+ "dashboard" [:= :qe.dashboard_id model-id])+ [:<= :qc.updated_at rerun-cutoff]+ [:>= :qe.started_at started-after]+ [:= :qe.error nil]+ [:= :qe.is_sandboxed false]+ (if parameterized?+ [:and+ [:= :qe.parameterized true]+ ;; Only rerun a parameterized query if it's had a cache hit within+ ;; the last caching window+ [:= :qe.cache_hit true]+ ;; Don't factor the last cache refresh into whether we should rerun+ ;; a parameterized query+ [:not= :qe.context "cache-refresh"]]+ [:= :qe.parameterized false])]+ :group-by [:q.query_hash :q.query :qc.query_hash :qe.card_id :qe.dashboard_id]}})}+ :u]]}))++(defn scheduled-base-query-to-rerun+ "The unparameterized query definition of the Card with `card-id` executed most recently after `started-after`, or+ nil."+ [card-id started-after]+ (t2/select-one :model/Query+ {:select [:q.query [:qe.card_id :card-id]]+ :from [[(t2/table-name :model/Query) :q]]+ :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]]+ :where [:and+ [:= :qe.card_id card-id]+ [:= :qe.parameterized false]+ [:= :qe.error nil]+ [:= :qe.is_sandboxed false]+ [:>= :qe.started_at started-after]]+ :order-by [[:qe.started_at :desc]]+ :limit 1}))++(defn scheduled-parameterized-queries-to-rerun+ "The `limit` most common parameterized query definitions of the Card with `card-id` executed after `rerun-cutoff`."+ [card-id rerun-cutoff limit]+ (t2/select :model/Query+ {:select [:q.query [:qe.card_id :card-id]]+ :from [[(t2/table-name :model/Query) :q]]+ :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]]+ :where [:and+ [:= :qe.card_id card-id]+ [:>= :qe.started_at rerun-cutoff]+ ;; Don't factor the last cache refresh into whether we should rerun a parameterized query+ [:not= :qe.context "cache-refresh"]+ [:= :parameterized true]+ [:= :qe.error nil]+ [:= :qe.is_sandboxed false]]+ :group-by [:q.query_hash :q.query :qe.card_id]+ :order-by [[[:count :q.query_hash] :desc]+ [[:min :qe.started_at] :asc]]+ :limit limit}))++(defn delete-query-caches!+ "Delete the QueryCache entries with `query-hashes`."+ [query-hashes]+ (t2/delete! :model/QueryCache :query_hash [:in query-hashes]))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn cache-configs-ready-to-run+ "The CacheConfigs of `strategy` whose next run is unset or due at `now`."+ [strategy now]+ (t2/select :model/CacheConfig+ :strategy strategy+ {:where [:or+ [:= :next_run_at nil]+ [:<= :next_run_at now]]}))++(defn update-cache-config!+ "Apply `changes` to the CacheConfig with `cache-config-id`."+ [cache-config-id changes]+ (t2/update! :model/CacheConfig {:id cache-config-id} changes))diff --git a/enterprise/backend/src/metabase_enterprise/cache/strategies.clj b/enterprise/backend/src/metabase_enterprise/cache/strategies.cljindex 89ed68763fa..532b392086f 100644--- a/enterprise/backend/src/metabase_enterprise/cache/strategies.clj+++ b/enterprise/backend/src/metabase_enterprise/cache/strategies.clj@@ -1,13 +1,13 @@(ns metabase-enterprise.cache.strategies(:require[java-time.api :as t]+ [metabase-enterprise.cache.db :as cache.db][metabase.cache.api][metabase.cache.core :as cache][metabase.premium-features.core :refer [defenterprise defenterprise-schema]][metabase.query-processor.middleware.cache-backend.db :as backend.db][metabase.util.log :as log]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(set! *warn-on-reflection* true)@@ -41,24 +41,7 @@:feature :cache-granular-controls[card :- :metabase.queries.schema/carddashboard-id :- [:maybe :metabase.lib.schema.id/dashboard]]- (let [qs (for [[i model model-id] [[1 "question" (:id card)]- [2 "dashboard" dashboard-id]- [3 "database" (:database_id card)]- [4 "root" 0]]- :when model-id]- ^:allow-subquery- {:from [:cache_config]- :select [:id- [[:inline i] :ordering]]- :where [:and- [:= :model model]- [:= :model_id model-id]]})- q ^:allow-subquery- {:from [[^:allow-subquery {:union-all qs} :unused_alias]]- :select [:id]- :order-by :ordering- :limit [:inline 1]}- item (t2/select-one :model/CacheConfig :id q)]+ (let [item (cache.db/card-cache-config (:id card) dashboard-id (:database_id card))](cache/card-strategy item card)));;; Strategy executiondiff --git a/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj b/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.cljindex ec8262e42bb..e8fb4fbb2bf 100644--- a/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj+++ b/enterprise/backend/src/metabase_enterprise/cache/task/refresh_cache_configs.clj@@ -4,6 +4,7 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.cache.db :as cache.db][metabase-enterprise.cache.strategies :as strategies][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.query-processor.core :as qp]@@ -58,12 +59,10 @@[refresh-defs](fn [](let [card-ids (into #{} (map :card-id refresh-defs))- cards-by-id (t2/select-pk->fn identity :model/Card :id [:in card-ids])+ cards-by-id (cache.db/cards-by-id card-ids)all-db-ids (into #{} (keep (comp :database_id val)) cards-by-id)router-db-ids (if (seq all-db-ids)- (t2/select-fn-set :database_id- :model/DatabaseRouter- :database_id [:in all-db-ids])+ (cache.db/router-database-ids all-db-ids)#{})](doseq [{:keys [card-id dashboard-id queries]} refresh-defs](let [card (get cards-by-id card-id)]@@ -92,45 +91,6 @@(t/minus (t/offset-date-time)(t/duration duration (keyword unit))))-(defn- duration-queries-to-rerun-honeysql- "HoneySQL query for selecting query definitions that should be rerun, given a list of :duration cache configs.- Executed twice, once to find parameterized queries and once to find non-parameterized queries."- [cache-configs parameterized?]- (let [queries- (for [{:keys [model model_id config]} cache-configs]- (let [rerun-cutoff (duration-ago config)]- ^:allow-subquery {:nest- ^:allow-subquery {:select [[:q.query :query]- [:qc.query_hash :cache-hash]- [:qe.card_id :card-id]- [:qe.dashboard_id :dashboard-id]- [[:count :q.query_hash] :count]]- :from [[(t2/table-name :model/Query) :q]]- :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]- [(t2/table-name :model/QueryCache) :qc] [:= :qc.query_hash :qe.cache_hash]]- :where [:and- (case model- "question" [:= :qe.card_id model_id]- "dashboard" [:= :qe.dashboard_id model_id])- [:<= :qc.updated_at rerun-cutoff]- ;; This is a safety check so that we don't scan all of query_execution -- if a query- ;; has not been executed at all in the last month (including cache hits) we won't bother- ;; refreshing it again.- [:>= :qe.started_at (duration-ago {:duration 30 :unit "days"})]- [:= :qe.error nil]- [:= :qe.is_sandboxed false]- (if parameterized?- [:and- [:= :qe.parameterized true]- ;; Only rerun a parameterized query if it's had a cache hit within the last caching window- [:= :qe.cache_hit true]- ;; Don't factor the last cache refresh into whether we should rerun a parameterized query- [:not= :qe.context (name :cache-refresh)]]- [:= :qe.parameterized false])]- :group-by [:q.query_hash :q.query :qc.query_hash :qe.card_id :qe.dashboard_id]}}))]- {:select [:u.query :u.cache-hash :u.card-id :u.dashboard-id :u.count]- :from [[^:allow-subquery {:union queries} :u]]}))-(defn- select-parameterized-queries"Given a list of parameterized query definitions from the Query table with additional :count and :card-id keys,selects the 10 most common queries for each card ID that we should rerun."@@ -144,12 +104,30 @@(take *parameterized-queries-to-rerun-per-card*))))vals)))+(defn- started-after+ "Cutoff of the safety check that keeps us from scanning all of query_execution: a query not executed at all in the+ last month (including cache hits) is not refreshed again."+ []+ (duration-ago {:duration 30 :unit "days"}))++(defn- duration-scopes+ "The `{:model :model-id :rerun-cutoff}` scopes of the duration `cache-configs`."+ [cache-configs]+ (for [{:keys [model model_id config]} cache-configs]+ {:model model, :model-id model_id, :rerun-cutoff (duration-ago config)}))++(defn- duration-queries-to-rerun-for+ "The query definitions to rerun for the duration `cache-configs`; `parameterized?` selects parameterized or plain+ queries."+ [cache-configs parameterized?]+ (cache.db/duration-queries-to-rerun (duration-scopes cache-configs) (started-after) parameterized?))+(defn- duration-queries-to-rerun[]- (let [cache-configs (t2/select :model/CacheConfig :strategy :duration :refresh_automatically true)]+ (let [cache-configs (cache.db/duration-cache-configs)](when (seq cache-configs)- (let [base-queries (t2/select :model/Query (duration-queries-to-rerun-honeysql cache-configs false))- parameterized-queries (t2/select :model/Query (duration-queries-to-rerun-honeysql cache-configs true))]+ (let [base-queries (duration-queries-to-rerun-for cache-configs false)+ parameterized-queries (duration-queries-to-rerun-for cache-configs true)](concat base-queries (select-parameterized-queries parameterized-queries))))))(defn- clear-caches-for-queries!@@ -157,7 +135,7 @@to re-run them before the cache has been refreshed. "[queries](doseq [batch (partition 1000 1000 nil queries)]- (t2/delete! :model/QueryCache :query_hash [:in (map :cache-hash batch)])))+ (cache.db/delete-query-caches! (map :cache-hash batch))))(defn- maybe-refresh-duration-caches!"Detects caches with strategy=duration that are eligible for refreshing, and returns a count of the refresh jobs that@@ -178,49 +156,24 @@(count refresh-defs))0))-(defn- scheduled-base-query-to-rerun-honeysql- "HoneySQL query for finding the the base query definition we should run for a card ID (i.e. the unparameterized- query)."+(defn- scheduled-base-query-to-rerun+ "The unparameterized query definition of the Card with `card-id` to rerun, or nil."[card-id]- {:select [:q.query [:qe.card_id :card-id]]- :from [[(t2/table-name :model/Query) :q]]- :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]]- :where [:and- [:= :qe.card_id card-id]- [:= :qe.parameterized false]- [:= :qe.error nil]- [:= :qe.is_sandboxed false]- ;; Was the query executed at least once in the last month?- ;; This is a safety check so that we don't scan all of query_execution -- if a query has not been executed at- ;; all in the last month (including cache hits) we won't bother refreshing it again.- [:>= :qe.started_at (duration-ago {:duration 30 :unit "days"})]]- :order-by [[:qe.started_at :desc]]- :limit 1})+ (cache.db/scheduled-base-query-to-rerun card-id (started-after)))-(defn- scheduled-parameterized-queries-to-rerun-honeysql+(defn- scheduled-parameterized-queries-to-rerun+ "The parameterized query definitions of the Card with `card-id` executed after `rerun-cutoff` to rerun."[card-id rerun-cutoff]- {:select [:q.query [:qe.card_id :card-id]]- :from [[(t2/table-name :model/Query) :q]]- :join [[(t2/table-name :model/QueryExecution) :qe] [:= :qe.hash :q.query_hash]]- :where [:and- [:= :qe.card_id card-id]- [:>= :qe.started_at rerun-cutoff]- ;; Don't factor the last cache refresh into whether we should rerun a parameterized query- [:not= :qe.context (name :cache-refresh)]- [:= :parameterized true]- [:= :qe.error nil]- [:= :qe.is_sandboxed false]]- :group-by [:q.query_hash :q.query :qe.card_id]- :order-by [[[:count :q.query_hash] :desc]- [[:min :qe.started_at] :asc]]- :limit *parameterized-queries-to-rerun-per-card*})+ (cache.db/scheduled-parameterized-queries-to-rerun card-id+ rerun-cutoff+ *parameterized-queries-to-rerun-per-card*))(defn- scheduled-queries-to-rerun"Returns a list containing all of the parameterized query definitions that we should preemptively rerun for a givencard that uses :schedule caching."[card-id rerun-cutoff]- (let [base-query (t2/select-one :model/Query (scheduled-base-query-to-rerun-honeysql card-id))- parameterized-queries (t2/select :model/Query (scheduled-parameterized-queries-to-rerun-honeysql card-id rerun-cutoff))]+ (let [base-query (scheduled-base-query-to-rerun card-id)+ parameterized-queries (scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)](->> (concat (when base-query [base-query])parameterized-queries)(map :query)@@ -231,7 +184,7 @@[{:keys [model_id model]}](case model"question" [model_id]- "dashboard" (let [dashboard (-> (t2/select-one :model/Dashboard :id model_id)+ "dashboard" (let [dashboard (-> (cache.db/dashboard model_id)(t2/hydrate :dashcards))](distinct (keep :card_id (:dashcards dashboard))))))@@ -265,11 +218,7 @@(defn- select-ready-to-run"Fetch whatever cache configs for a given `strategy` are ready to be updated."[strategy]- (t2/select :model/CacheConfig- :strategy strategy- {:where [:or- [:= :next_run_at nil]- [:<= :next_run_at (t/offset-date-time)]]}))+ (cache.db/cache-configs-ready-to-run strategy (t/offset-date-time)))(defn- calc-next-run"Calculate when a next run should happen based on a cron schedule"@@ -290,10 +239,8 @@schedule-refresh-count(reduce(fn [refreshed-count {:keys [id config refresh_automatically] :as cache-config}]- (t2/update! :model/CacheConfig- {:id id}- {:next_run_at (calc-next-run (:schedule config) now)- :invalidated_at now})+ (cache.db/update-cache-config! id {:next_run_at (calc-next-run (:schedule config) now)+ :invalidated_at now})(if (and (premium-features/enable-preemptive-caching?) refresh_automatically)(do(refresh-schedule-cache! cache-config)diff --git a/enterprise/backend/src/metabase_enterprise/content_translation/db.clj b/enterprise/backend/src/metabase_enterprise/content_translation/db.cljnew file mode 100644index 00000000000..552de869ae3--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/content_translation/db.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.content-translation.db+ "Application database queries for the content-translation module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn delete-all-translations!+ "Delete every ContentTranslation."+ []+ (t2/delete! :model/ContentTranslation))++(defn insert-translations!+ "Insert the ContentTranslation `rows`."+ [rows]+ (t2/insert! :model/ContentTranslation rows))diff --git a/enterprise/backend/src/metabase_enterprise/content_translation/dictionary.clj b/enterprise/backend/src/metabase_enterprise/content_translation/dictionary.cljindex 4779140e5ee..59dd1ca5a0a 100644--- a/enterprise/backend/src/metabase_enterprise/content_translation/dictionary.clj+++ b/enterprise/backend/src/metabase_enterprise/content_translation/dictionary.clj@@ -5,6 +5,7 @@[clojure.java.io :as io][clojure.set :as set][clojure.string :as str]+ [metabase-enterprise.content-translation.db :as content-translation.db][metabase.premium-features.core :as premium-features][metabase.util :as u][metabase.util.i18n :as i18n :refer [tru]]@@ -146,10 +147,10 @@(let [usable-rows (filter (comp is-msgstr-usable :msgstr) translations)](t2/with-transaction [_tx];; Replace all existing entries- (t2/delete! :model/ContentTranslation)+ (content-translation.db/delete-all-translations!);; Insert all usable rows at once(when-not (empty? usable-rows)- (t2/insert! :model/ContentTranslation usable-rows))))))+ (content-translation.db/insert-translations! usable-rows))))))(defn- maybe-read[reader]diff --git a/enterprise/backend/src/metabase_enterprise/content_verification/api/moderation_review.clj b/enterprise/backend/src/metabase_enterprise/content_verification/api/moderation_review.cljindex 5c867e64eaf..ea12cdac65f 100644--- a/enterprise/backend/src/metabase_enterprise/content_verification/api/moderation_review.clj+++ b/enterprise/backend/src/metabase_enterprise/content_verification/api/moderation_review.clj@@ -1,11 +1,11 @@(ns metabase-enterprise.content-verification.api.moderation-review"`api/ee/moderation-review` routes."(:require+ [metabase-enterprise.content-verification.db :as content-verification.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.content-verification.core :as moderation]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -27,5 +27,7 @@:moderated_item_type moderated_item_type:moderator_id api/*current-user-id*:status status}]- (api/check-404 (t2/exists? (get moderation/moderated-item-type->model moderated_item_type) moderated_item_id))+ (api/check-404 (case (get moderation/moderated-item-type->model moderated_item_type)+ :model/Card (content-verification.db/card-exists? moderated_item_id)+ :model/Dashboard (content-verification.db/dashboard-exists? moderated_item_id)))(moderation/create-review! review-data)))diff --git a/enterprise/backend/src/metabase_enterprise/content_verification/db.clj b/enterprise/backend/src/metabase_enterprise/content_verification/db.cljnew file mode 100644index 00000000000..b16ef2f1784--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/content_verification/db.clj@@ -0,0 +1,15 @@+(ns metabase-enterprise.content-verification.db+ "Application database queries for the content-verification module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn card-exists?+ "Whether a Card with `id` exists."+ [id]+ (t2/exists? :model/Card id))++(defn dashboard-exists?+ "Whether a Dashboard with `id` exists."+ [id]+ (t2/exists? :model/Dashboard id))diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.cljindex 75ef00f2ac9..513e9ca5cd9 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj@@ -4,8 +4,8 @@[clj-http.client :as http][clojure.core.async :as a][metabase-enterprise.custom-viz-plugin.cache :as cache]+ [metabase-enterprise.custom-viz-plugin.db :as custom-viz-plugin.db][metabase-enterprise.custom-viz-plugin.manifest :as manifest]- [metabase-enterprise.custom-viz-plugin.models.custom-viz-plugin :as custom-viz-plugin][metabase-enterprise.custom-viz-plugin.settings :as custom-viz.settings][metabase.api.common :as api][metabase.api.macros :as api.macros]@@ -14,8 +14,7 @@[metabase.server.streaming-response :as sr][metabase.util.http :as u.http][metabase.util.log :as log]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import(java.io BufferedReader File InputStream InputStreamReader OutputStream)(java.nio.file Files)))@@ -148,7 +147,7 @@validated (cache/validate-bundle! bundle-bytes)identifier (get-in validated [:manifest :name])_ (api/check-400- (not (t2/exists? :model/CustomVizPlugin :identifier identifier))+ (not (custom-viz-plugin.db/plugin-identifier-exists? identifier))(format "A custom visualization with identifier \"%s\" already exists." identifier))plugin (cache/insert-bundle! identifier validated)](events/publish-event! :event/custom-viz-plugin-create {:object plugin@@ -176,20 +175,19 @@"Could not fetch metabase-plugin.json from the dev server."){:status-code 400})))_ (api/check-400- (not (t2/exists? :model/CustomVizPlugin :identifier identifier))+ (not (custom-viz-plugin.db/plugin-identifier-exists? identifier))(format "A custom visualization with identifier \"%s\" already exists." identifier))display-name (or (:name manifest) identifier)icon (:icon manifest)version-str (get-in manifest [:metabase :version])- plugin (first (t2/insert-returning-instances! :model/CustomVizPlugin- :display_name display-name- :identifier identifier- :status :active- :enabled true- :dev_bundle_url dev_bundle_url- :icon icon- :manifest manifest- :metabase_version version-str))]+ plugin (custom-viz-plugin.db/insert-plugin! {:display_name display-name+ :identifier identifier+ :status :active+ :enabled true+ :dev_bundle_url dev_bundle_url+ :icon icon+ :manifest manifest+ :metabase_version version-str})](cache/set-or-clear-dev-bundle! (:id plugin) dev_bundle_url)(events/publish-event! :event/custom-viz-plugin-create {:object plugin:user-id api/*current-user-id*})@@ -199,7 +197,7 @@"List all registered custom visualization plugins."[](api/check-superuser)- (->> (custom-viz-plugin/select-non-blob {:order-by [[:display_name :asc]]})+ (->> (custom-viz-plugin.db/non-blob-plugins)(mapv (comp plugin->response api/read-check))))(api.macros/defendpoint :get "/list" :- [:sequential CustomVizPluginRuntimeResponse]@@ -208,9 +206,7 @@Dev-only plugins are excluded when dev mode is disabled."[](let [dev-mode? (custom-viz.settings/custom-viz-plugin-dev-mode-enabled)- plugins (custom-viz-plugin/select-non-blob :status :active- :enabled true- {:order-by [[:display_name :asc]]})]+ plugins (custom-viz-plugin.db/active-enabled-non-blob-plugins)](->> plugins(remove #(and (not dev-mode?) (dev-only-plugin? %)))(mapv (comp plugin->runtime-response api/read-check)))))@@ -218,8 +214,8 @@(api.macros/defendpoint :delete "/:id" :- :nil"Remove a custom visualization plugin and evict its on-disk cache."[{:keys [id]} :- [:map [:id ms/PositiveInt]]]- (let [plugin (api/write-check (custom-viz-plugin/select-one-non-blob :id id))]- (t2/delete! :model/CustomVizPlugin :id id)+ (let [plugin (api/write-check (custom-viz-plugin.db/non-blob-plugin id))]+ (custom-viz-plugin.db/delete-plugin! id)(cache/purge-plugin-cache! plugin)(events/publish-event! :event/custom-viz-plugin-delete {:object plugin:user-id api/*current-user-id*})@@ -231,11 +227,11 @@_query-paramsbody :- [:map[:enabled {:optional true} [:maybe :boolean]]]]- (let [existing (api/write-check (custom-viz-plugin/select-one-non-blob :id id))+ (let [existing (api/write-check (custom-viz-plugin.db/non-blob-plugin id))updates (select-keys body [:enabled])](when (seq updates)- (t2/update! :model/CustomVizPlugin id updates))- (let [result (custom-viz-plugin/select-one-non-blob :id id)]+ (custom-viz-plugin.db/update-plugin! id updates))+ (let [result (custom-viz-plugin.db/non-blob-plugin id)](events/publish-event! :event/custom-viz-plugin-update {:object result:previous-object existing:user-id api/*current-user-id*})@@ -250,7 +246,7 @@[{:keys [id]} :- [:map [:id ms/PositiveInt]]_query-params{:keys [file]} :- BundleUploadParts]- (let [existing (api/write-check (custom-viz-plugin/select-one-non-blob :id id))+ (let [existing (api/write-check (custom-viz-plugin.db/non-blob-plugin id))tempfile (check-upload! file)](try(let [bundle-bytes (Files/readAllBytes (.toPath tempfile))@@ -279,7 +275,7 @@respondraise](try- (let [plugin (api/read-check (custom-viz-plugin/select-one-non-blob :id id))+ (let [plugin (api/read-check (custom-viz-plugin.db/non-blob-plugin id))dev-url (cache/resolve-dev-bundle id)entry (cache/resolve-bundle plugin)](if entry@@ -311,7 +307,7 @@respondraise](try- (let [plugin (api/read-check (custom-viz-plugin/select-one-non-blob :id id))+ (let [plugin (api/read-check (custom-viz-plugin.db/non-blob-plugin id))content-type (or (manifest/asset-content-type path)(throw (ex-info "Unsupported asset type" {:status-code 404})))dev? (cache/resolve-dev-bundle id)@@ -339,7 +335,7 @@[{:keys [id]} :- [:map [:id ms/PositiveInt]]_query-params{:keys [dev_bundle_url]} :- [:map [:dev_bundle_url [:maybe :string]]]]- (api/write-check (custom-viz-plugin/select-one-non-blob :id id))+ (api/write-check (custom-viz-plugin.db/non-blob-plugin id))(check-dev-mode-enabled!)(cache/set-or-clear-dev-bundle! id dev_bundle_url){:dev_bundle_url (cache/resolve-dev-bundle id)})@@ -387,7 +383,7 @@plugins this is a no-op — to update an upload-backed plugin, PUT a new bundleto `/:id/bundle`."[{:keys [id]} :- [:map [:id ms/PositiveInt]]]- (let [plugin (api/write-check (custom-viz-plugin/select-one-non-blob :id id))]+ (let [plugin (api/write-check (custom-viz-plugin.db/non-blob-plugin id))](api/check-400 (dev-only-plugin? plugin)"Refresh is only supported for dev-only plugins; upload a new bundle to update an upload-backed plugin.")(let [dev-url (or (cache/resolve-dev-bundle id)@@ -395,12 +391,12 @@manifest (or (cache/fetch-dev-manifest dev-url)(throw (ex-info "Failed to fetch manifest from dev server" {:status-code 502})))version-str (get-in manifest [:metabase :version])]- (t2/update! :model/CustomVizPlugin id- {:display_name (or (:name manifest) (:identifier plugin))- :icon (:icon manifest)- :manifest manifest- :metabase_version version-str})- (let [result (custom-viz-plugin/select-one-non-blob :id id)]+ (custom-viz-plugin.db/update-plugin! id+ {:display_name (or (:name manifest) (:identifier plugin))+ :icon (:icon manifest)+ :manifest manifest+ :metabase_version version-str})+ (let [result (custom-viz-plugin.db/non-blob-plugin id)](events/publish-event! :event/custom-viz-plugin-update {:object result:previous-object plugin:user-id api/*current-user-id*})diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/cache.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/cache.cljindex 46ee9188cd8..72aa318214a 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/cache.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/cache.clj@@ -15,15 +15,14 @@[buddy.core.hash :as buddy-hash][clj-http.client :as http][clojure.string :as str]+ [metabase-enterprise.custom-viz-plugin.db :as custom-viz-plugin.db][metabase-enterprise.custom-viz-plugin.manifest :as manifest]- [metabase-enterprise.custom-viz-plugin.models.custom-viz-plugin :as custom-viz-plugin][metabase-enterprise.custom-viz-plugin.settings :as custom-viz.settings][metabase.util :as u][metabase.util.compress :as u.compress][metabase.util.files :as u.files][metabase.util.http :as u.http]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.nio.file CopyOption FileAlreadyExistsException Files FileVisitOption Path)(java.nio.file.attribute FileAttribute)))@@ -202,7 +201,7 @@(when bundle_hash(let [dir (plugin-cache-dir id bundle_hash)](when-not (u.files/exists? dir)- (when-let [bundle-bytes (t2/select-one-fn :bundle :model/CustomVizPlugin :id id)]+ (when-let [bundle-bytes (custom-viz-plugin.db/plugin-bundle id)](let [actual-hash (bytes-hash bundle-bytes)](when-not (= actual-hash bundle_hash)(throw (ex-info "Bundle integrity check failed: stored bytes do not match bundle_hash"@@ -238,16 +237,15 @@"Persist a validated bundle for an existing plugin row, evict stale on-diskcaches, and return the refreshed row."[{:keys [id]} validated]- (t2/update! :model/CustomVizPlugin id (derived-columns validated))+ (custom-viz-plugin.db/update-plugin! id (derived-columns validated))(purge-plugin-cache! {:id id})- (custom-viz-plugin/select-one-non-blob :id id))+ (custom-viz-plugin.db/non-blob-plugin id))(defn insert-bundle!"Insert a new plugin row from a validated bundle and an `:identifier`. Returnsthe inserted row."[identifier validated]- (t2/insert-returning-instance!- :model/CustomVizPlugin+ (custom-viz-plugin.db/insert-plugin!(merge {:identifier identifier:enabled true}(derived-columns validated))))@@ -418,14 +416,14 @@[id dev-bundle-url](let [url (not-empty dev-bundle-url)](some-> url (validate-url! "Dev bundle URL"))- (t2/update! :model/CustomVizPlugin id {:dev_bundle_url url})))+ (custom-viz-plugin.db/update-plugin! id {:dev_bundle_url url})))(defn resolve-dev-bundle"Resolve the dev bundle URL for a plugin from the database. Returns the URL string or nil.Always returns nil when dev mode is disabled."[id](when (custom-viz.settings/custom-viz-plugin-dev-mode-enabled)- (not-empty (t2/select-one-fn :dev_bundle_url :model/CustomVizPlugin :id id))))+ (not-empty (custom-viz-plugin.db/plugin-dev-bundle-url id))));;; ------------------------------------------------ Resolve ------------------------------------------------diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/db.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/db.cljnew file mode 100644index 00000000000..2caee3f57ed--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/db.clj@@ -0,0 +1,61 @@+(ns metabase-enterprise.custom-viz-plugin.db+ "Application database queries for the custom-viz-plugin module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [toucan2.core :as t2]))++(def ^:private non-blob-columns+ "Columns to select for normal plugin reads, excluding the bundle blob."+ [:model/CustomVizPlugin :id :identifier :display_name :icon :status :error_message :enabled+ :manifest :metabase_version :bundle_hash :dev_bundle_url+ :created_at :updated_at])++(defn non-blob-plugin+ "The CustomVizPlugin with `plugin-id` without its bundle, or nil."+ [plugin-id]+ (t2/select-one non-blob-columns :id plugin-id))++(defn non-blob-plugins+ "Every CustomVizPlugin without its bundle, ordered by display name."+ []+ (t2/select non-blob-columns {:order-by [[:display_name :asc]]}))++(defn active-enabled-non-blob-plugins+ "The active, enabled CustomVizPlugins without their bundle, ordered by display name."+ []+ (t2/select non-blob-columns :status :active :enabled true {:order-by [[:display_name :asc]]}))++(defn plugin-by-identifier+ "The CustomVizPlugin with `identifier`, or nil."+ [identifier]+ (t2/select-one :model/CustomVizPlugin :identifier identifier))++(defn plugin-identifier-exists?+ "Whether a CustomVizPlugin with `identifier` exists."+ [identifier]+ (t2/exists? :model/CustomVizPlugin :identifier identifier))++(defn plugin-bundle+ "The bundle bytes of the CustomVizPlugin with `plugin-id`."+ [plugin-id]+ (t2/select-one-fn :bundle :model/CustomVizPlugin :id plugin-id))++(defn plugin-dev-bundle-url+ "The dev bundle URL of the CustomVizPlugin with `plugin-id`."+ [plugin-id]+ (t2/select-one-fn :dev_bundle_url :model/CustomVizPlugin :id plugin-id))++(defn insert-plugin!+ "Insert `plugin` and return the new instance."+ [plugin]+ (t2/insert-returning-instance! :model/CustomVizPlugin plugin))++(defn update-plugin!+ "Apply `changes` to the CustomVizPlugin with `plugin-id`."+ [plugin-id changes]+ (t2/update! :model/CustomVizPlugin plugin-id changes))++(defn delete-plugin!+ "Delete the CustomVizPlugin with `plugin-id`."+ [plugin-id]+ (t2/delete! :model/CustomVizPlugin :id plugin-id))diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/init.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/init.cljindex ff119121ba7..f7dea85beb0 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/init.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/init.clj@@ -1,4 +1,5 @@(ns metabase-enterprise.custom-viz-plugin.init(:require[metabase-enterprise.custom-viz-plugin.api]+ [metabase-enterprise.custom-viz-plugin.models.custom-viz-plugin][metabase-enterprise.custom-viz-plugin.settings]))diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/models/custom_viz_plugin.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/models/custom_viz_plugin.cljindex 2e47ee90f80..0000f93ccd2 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/models/custom_viz_plugin.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/models/custom_viz_plugin.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.custom-viz-plugin.models.custom-viz-plugin(:require[buddy.core.codecs :as codecs]+ [metabase-enterprise.custom-viz-plugin.db :as custom-viz-plugin.db][metabase.api.common :as api][metabase.models.interface :as mi][metabase.models.serialization :as serdes]@@ -39,16 +40,6 @@:manifest :metabase_version :bundle_hash :dev_bundle_url:created_at :updated_at])-(defn select-one-non-blob- "Like `t2/select-one` on `:model/CustomVizPlugin`, but excludes the bundle blob."- [& conditions]- (apply t2/select-one (into [:model/CustomVizPlugin] non-blob-columns) conditions))--(defn select-non-blob- "Like `t2/select` on `:model/CustomVizPlugin`, but excludes the bundle blob."- [& conditions]- (apply t2/select (into [:model/CustomVizPlugin] non-blob-columns) conditions))-(defmethod mi/can-read? :model/CustomVizPlugin([_instance] (some? api/*current-user-id*))([_model _pk] (some? api/*current-user-id*)))@@ -95,7 +86,7 @@(defmethod serdes/load-find-local "CustomVizPlugin" [path](let [{:keys [id]} (last path)]- (t2/select-one :model/CustomVizPlugin :identifier id)))+ (custom-viz-plugin.db/plugin-by-identifier id)))(defmethod serdes/storage-path "CustomVizPlugin" [entity _ctx][{:label "custom_viz_plugins"} {:label (:identifier entity)}])diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/README.md b/enterprise/backend/src/metabase_enterprise/data_apps/README.mdindex e6653b7a8a9..21ccaf95fcf 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/README.md+++ b/enterprise/backend/src/metabase_enterprise/data_apps/README.md@@ -106,7 +106,7 @@ assets (`metabase.server.routes/static-files-handler`).Responses are field-filtered by role: superusers get full metadata, everyone else gets `name` and`display_name` only. The bundle blob is never serialized into JSON, and metadata reads go through-`select-non-blob` helpers so listing apps doesn't drag the bundles out of the DB.+`data-apps.db`'s non-blob helpers so listing apps doesn't drag the bundles out of the DB.`csp.clj` exposes an app's `allowed_hosts` to the core security middleware through a `defenterprise`hook, which drives the `connect-src` of the iframe document's CSP. It's a separate namespace so thediff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.cljindex df3018d5360..228465ae553 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj@@ -8,14 +8,13 @@`metabase.server.routes/static-files-handler`)."(:require[clojure.string :as str]- [metabase-enterprise.data-apps.models.data-app :as data-app]+ [metabase-enterprise.data-apps.db :as data-apps.db][metabase-enterprise.data-apps.sync :as data-app.sync][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.util.json :as json]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import(java.io ByteArrayInputStream)))@@ -137,10 +136,7 @@to return only enabled apps without sync errors."[_route-params{:keys [available]} :- [:map [:available {:optional true} [:maybe :boolean]]]]- (->> (data-app/select-non-blob (cond-> {:order-by [[:display_name :asc]]}- available (assoc :where [:and- [:= :enabled true]- [:= :sync_error nil]])))+ (->> (data-apps.db/non-blob-data-apps available)(map api/read-check)(mapv data-app-response)))@@ -153,9 +149,9 @@_query-params{:keys [enabled]} :- [:map [:enabled :boolean]]](api/check-superuser)- (let [app (api/check-404 (data-app/select-one-non-blob :name slug))]- (t2/update! :model/DataApp :id (:id app) {:enabled enabled})- (data-app/select-one-non-blob :id (:id app))))+ (let [app (api/check-404 (data-apps.db/non-blob-data-app-by-slug slug))]+ (data-apps.db/update-data-app! (:id app) {:enabled enabled})+ (data-apps.db/non-blob-data-app (:id app))))(api.macros/defendpoint :delete ["/:slug" :slug slug-regex] :- :nil"Remove a single data app (its row and cached bundle). Intended for clearing out@@ -165,7 +161,7 @@[{:keys [slug]} :- [:map [:slug ms/NonBlankString]]](api/check-superuser);; `t2/delete!` returns the row count; a 0 means the slug wasn't there → 404.- (api/check-404 (pos? (t2/delete! :model/DataApp :name slug)))+ (api/check-404 (pos? (data-apps.db/delete-data-app-by-slug! slug)));; a `nil` body is rendered as a 204; matches the `:- :nil` response schema;; above (returning `generic-204-no-content` would fail that validation).nil)@@ -173,7 +169,7 @@(api.macros/defendpoint :get ["/:slug" :slug slug-regex] :- [:or DataAppResponse PublicDataAppResponse]"Fetch metadata for a single enabled data app by its slug."[{:keys [slug]} :- [:map [:slug ms/NonBlankString]]]- (data-app-response (api/read-check (data-app/select-one-non-blob :name slug :enabled true))))+ (data-app-response (api/read-check (data-apps.db/enabled-non-blob-data-app-by-slug slug))))(api.macros/defendpoint :get ["/:slug/bundle" :slug slug-regex] :- :any"Serve the cached JS bundle for a single enabled data app by slug. Honors@@ -185,7 +181,7 @@respondraise](try- (let [row (api/read-check (data-app/select-one-non-blob :name slug :enabled true))+ (let [row (api/read-check (data-apps.db/enabled-non-blob-data-app-by-slug slug))hash (:bundle_hash row)etag (some->> hash (format "\"%s\""))](cond@@ -195,7 +191,7 @@(respond {:status 304, :headers {"Cache-Control" "no-cache", "ETag" etag}}):else- (let [^bytes bundle (t2/select-one-fn :bundle :model/DataApp :id (:id row))]+ (let [^bytes bundle (data-apps.db/data-app-bundle (:id row))](if (and bundle (pos? (alength bundle)))(respond {:status 200:headers (-> bundle-response-headersdiff --git a/enterprise/backend/src/metabase_enterprise/data_apps/csp.clj b/enterprise/backend/src/metabase_enterprise/data_apps/csp.cljindex f4db3e69539..34a941220d9 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/csp.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/csp.clj@@ -3,7 +3,7 @@[[metabase.server.middleware.security]]. Kept separate from the HTTP API sothe core security middleware's lookup doesn't pull in route code."(:require- [metabase-enterprise.data-apps.models.data-app :as data-app]+ [metabase-enterprise.data-apps.db :as data-apps.db][metabase.premium-features.core :refer [defenterprise]]))(defenterprise data-app-connect-src-hosts@@ -12,5 +12,5 @@CSP `connect-src` so the sandboxed bundle can fetch/XHR those origins.":feature :data-apps-preview[slug]- (or (:allowed_hosts (data-app/select-one-non-blob :name slug :enabled true))+ (or (:allowed_hosts (data-apps.db/enabled-non-blob-data-app-by-slug slug))[]))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/db.clj b/enterprise/backend/src/metabase_enterprise/data_apps/db.cljnew file mode 100644index 00000000000..1bf071a4a13--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_apps/db.clj@@ -0,0 +1,80 @@+(ns metabase-enterprise.data-apps.db+ "Application database queries for the data-apps module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [toucan2.core :as t2]))++(def ^:private non-blob-columns+ "Columns to select for normal data-app metadata reads, excluding the raw bundle blob."+ [:model/DataApp :id :name :display_name :description :bundle_path :enabled :allowed_hosts+ :bundle_hash :last_synced_sha :last_synced_at :sync_error+ :created_at :updated_at])++(defn non-blob-data-app+ "The DataApp with `data-app-id` without its bundle, or nil."+ [data-app-id]+ (t2/select-one non-blob-columns :id data-app-id))++(defn non-blob-data-app-by-slug+ "The DataApp named `slug` without its bundle, or nil."+ [slug]+ (t2/select-one non-blob-columns :name slug))++(defn enabled-non-blob-data-app-by-slug+ "The enabled DataApp named `slug` without its bundle, or nil."+ [slug]+ (t2/select-one non-blob-columns :name slug :enabled true))++(defn non-blob-data-apps+ "Every DataApp without its bundle, ordered by display name; only the enabled, error-free ones when `available?`."+ [available?]+ (t2/select non-blob-columns+ (cond-> {:order-by [[:display_name :asc]]}+ available? (assoc :where [:and+ [:= :enabled true]+ [:= :sync_error nil]]))))++(defn data-app-bundle+ "The bundle bytes of the DataApp with `data-app-id`."+ [data-app-id]+ (t2/select-one-fn :bundle :model/DataApp :id data-app-id))++(defn data-apps-sync-info+ "The sync-relevant columns of every DataApp."+ []+ (t2/select [:model/DataApp :name :display_name :description :allowed_hosts :bundle_path :bundle_hash :sync_error]))++(defn data-app-exists?+ "Whether a DataApp named `slug` exists."+ [slug]+ (t2/exists? :model/DataApp :name slug))++(defn insert-data-app!+ "Insert the DataApp `row`."+ [row]+ (t2/insert! :model/DataApp row))++(defn update-data-app!+ "Apply `changes` to the DataApp with `data-app-id`."+ [data-app-id changes]+ (t2/update! :model/DataApp :id data-app-id changes))++(defn update-data-app-by-slug!+ "Apply `changes` to the DataApp named `slug`."+ [slug changes]+ (t2/update! :model/DataApp :name slug changes))++(defn delete-data-app-by-slug!+ "Delete the DataApp named `slug`, returning the number deleted."+ [slug]+ (t2/delete! :model/DataApp :name slug))++(defn delete-data-apps-not-named!+ "Delete the DataApps whose name is not one of `slugs`, returning the number deleted."+ [slugs]+ (t2/delete! :model/DataApp :name [:not-in slugs]))++(defn delete-all-data-apps!+ "Delete every DataApp, returning the number deleted."+ []+ (t2/delete! :model/DataApp))diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.cljindex 2c24cfe7ba2..f97919e9d5f 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj@@ -40,22 +40,6 @@(cond-> app(contains? app :allowed_hosts) (update :allowed_hosts #(or % []))))-(def non-blob-columns- "Columns to select for normal data-app metadata reads, excluding the raw bundle blob."- [:id :name :display_name :description :bundle_path :enabled :allowed_hosts- :bundle_hash :last_synced_sha :last_synced_at :sync_error- :created_at :updated_at])--(defn select-one-non-blob- "Like `t2/select-one` on `:model/DataApp`, but excludes the bundle blob."- [& conditions]- (apply t2/select-one (into [:model/DataApp] non-blob-columns) conditions))--(defn select-non-blob- "Like `t2/select` on `:model/DataApp`, but excludes the bundle blob."- [& conditions]- (apply t2/select (into [:model/DataApp] non-blob-columns) conditions))-;; Deliberately ungated: any signed-in user may view a data app, and the `+auth`;; endpoints mean reaching a read check already implies authentication. See the;; README's permissions section for why this is safe.diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj b/enterprise/backend/src/metabase_enterprise/data_apps/sync.cljindex c7f24b325f7..728330615a9 100644--- a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj+++ b/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj@@ -14,6 +14,7 @@(:require[clojure.string :as str][metabase-enterprise.data-apps.config :as data-app.config]+ [metabase-enterprise.data-apps.db :as data-apps.db][metabase.settings.core :as setting][metabase.util.i18n :refer [tru]][metabase.util.log :as log]@@ -86,9 +87,9 @@"Insert or update by slug. Never writes `:enabled`, so the admin toggle (and theDB default of true for new rows) is preserved across syncs."[slug row]- (if (t2/exists? :model/DataApp :name slug)- (t2/update! :model/DataApp :name slug row)- (t2/insert! :model/DataApp (assoc row :name slug))))+ (if (data-apps.db/data-app-exists? slug)+ (data-apps.db/update-data-app-by-slug! slug row)+ (data-apps.db/insert-data-app! (assoc row :name slug))))(defn- app-metadata-changed?"Whether the metadata a sync stores whether or not the bundle loaded differs from@@ -120,7 +121,7 @@[existing slug message](boolean(when (and existing (not= (:sync_error existing) message))- (t2/update! :model/DataApp :name slug {:sync_error message})+ (data-apps.db/update-data-app-by-slug! slug {:sync_error message})true)))(defn- sync-app!@@ -193,8 +194,7 @@present-slugs (into #{} (map :slug) results);; pre-sync rows, so we can tell a real change from a sha/timestamp bumpexisting (into {} (map (juxt :name identity))- (t2/select [:model/DataApp :name :display_name :description :allowed_hosts- :bundle_path :bundle_hash :sync_error]))+ (data-apps.db/data-apps-sync-info)){:keys [changed removed]}(t2/with-transaction [_conn](let [changed (reduce (fn [n {:keys [slug config-error] :as cfg}]@@ -211,8 +211,8 @@;; `enabled` is deliberately not consulted — see the README's;; source-of-truth table. (`[:not-in #{}]` is invalid SQL, so delete-all.)removed (if (seq present-slugs)- (t2/delete! :model/DataApp :name [:not-in present-slugs])- (t2/delete! :model/DataApp))]+ (data-apps.db/delete-data-apps-not-named! present-slugs)+ (data-apps.db/delete-all-data-apps!))]{:changed changed, :removed removed}))](log/infof "[data-app] synced sha=%s apps=%d changed=%d removed=%d errors=%d"sha (count good) changed removed (count errors))diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.cljindex 62f05ad0300..a5482257dc6 100644--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity.clj@@ -6,14 +6,14 @@(:require[clojure.string :as str][metabase-enterprise.data-complexity-score.complexity-embedders :as embedders]+ [metabase-enterprise.data-complexity-score.db :as data-complexity-score.db][metabase.analytics-interface.core :as analytics.interface][metabase.analytics.core :as analytics][metabase.audit-app.core :as audit][metabase.collections.core :as collections][metabase.collections.curation :as curation][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -124,12 +124,7 @@(into {}(mapcat (fn [chunk](map (juxt :table_id :field_count)- (t2/query {:select [:table_id [:%count.* :field_count]]- :from [:metabase_field]- :where [:and- [:= :active true]- [:in :table_id chunk]]- :group-by [:table_id]}))))+ (data-complexity-score.db/active-field-counts-by-table chunk))))(partition-all in-clause-chunk-size table-ids)))(defn- table-measure-names@@ -139,9 +134,7 @@(into {}(mapcat (fn [chunk](u/group-by :table_id :name- (t2/select [:model/Measure :table_id :name]- :archived false- :table_id [:in chunk]))))+ (data-complexity-score.db/unarchived-measure-names chunk))))(partition-all in-clause-chunk-size table-ids)))(defn- ->card-entity@@ -180,7 +173,7 @@[collection-id](when collection-id(into #{collection-id}- (when-let [root (t2/select-one :model/Collection :id collection-id)]+ (when-let [root (data-complexity-score.db/collection collection-id)](collections/descendant-ids root)))))(defn- verified-card-id-set@@ -188,22 +181,19 @@[];; Called only when `metabot-scope` requests curated-only filtering — avoids a `moderation_review`;; join on the universe Card select by pushing the check into a small auxiliary lookup.- (t2/select-fn-set :moderated_item_id :model/ModerationReview- :moderated_item_type "card"- :most_recent true- :status "verified"))+ (data-complexity-score.db/verified-card-ids))(defn- official-collection-id-set"Set of collection ids with `official` authority level."[]- (t2/select-fn-set :id :model/Collection :authority_level "official"))+ (data-complexity-score.db/official-collection-ids))(defn- routed-child-database-id-set"Set of database ids whose `router_database_id` is non-nil — the routed child databases whosetables Metabot/search hide. Tables with `:db_id` in this set are excluded from the `:metabot`catalog, mirroring the table-visibility rule in `metabase.warehouse-schema.models.table`."[]- (t2/select-fn-set :id :model/Database :router_database_id [:not= nil]))+ (data-complexity-score.db/routed-child-database-ids))(defn- pick-by-row"Filter `entities` by `row-pred` applied to the correspondingly-indexed `rows`. Preserves@@ -244,14 +234,8 @@;; library/metabot derivations below — they're ignored by `->card-entity` /;; `->table-entity`. `:card_schema` is required by `:model/Card`'s post-select hooks;; even when we don't otherwise use it.- universe-cards (t2/select [:model/Card :id :name :type :collection_id :card_schema]- :type [:in ["metric" "model"]]- :archived false- :database_id [:not= audit/audit-db-id])- universe-tables (t2/select [:model/Table :id :name :collection_id :is_published- :visibility_type :db_id :data_layer :data_authority]- :active true- :db_id [:not= audit/audit-db-id])+ universe-cards (data-complexity-score.db/universe-cards audit/audit-db-id)+ universe-tables (data-complexity-score.db/universe-tables audit/audit-db-id)field-counts (table-field-counts (mapv :id universe-tables))measure-names (table-measure-names (mapv :id universe-tables))card-entities (mapv ->card-entity universe-cards)diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/db.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/db.cljnew file mode 100644index 00000000000..64bbc4bf3b4--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/db.clj@@ -0,0 +1,96 @@+(ns metabase-enterprise.data-complexity-score.db+ "Application database queries for the data-complexity-score module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn active-field-counts-by-table+ "Rows of `:table_id` and `:field_count` of active Fields for `table-ids`."+ [table-ids]+ (t2/query {:select [:table_id [:%count.* :field_count]]+ :from [:metabase_field]+ :where [:and+ [:= :active true]+ [:in :table_id table-ids]]+ :group-by [:table_id]}))++(defn unarchived-measure-names+ "The Table ID and name of the unarchived Measures on the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Measure :table_id :name] :archived false :table_id [:in table-ids]))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn verified-card-ids+ "The IDs of the Cards whose most recent moderation review is verified."+ []+ (t2/select-fn-set :moderated_item_id :model/ModerationReview+ :moderated_item_type "card"+ :most_recent true+ :status "verified"))++(defn official-collection-ids+ "The IDs of the official Collections."+ []+ (t2/select-fn-set :id :model/Collection :authority_level "official"))++(defn routed-child-database-ids+ "The IDs of the Databases that are routing destinations."+ []+ (t2/select-fn-set :id :model/Database :router_database_id [:not= nil]))++(defn universe-cards+ "The ID, name, type, and Collection of the unarchived metric and model Cards outside the Database with+ `audit-database-id`."+ [audit-database-id]+ (t2/select [:model/Card :id :name :type :collection_id :card_schema]+ :type [:in ["metric" "model"]]+ :archived false+ :database_id [:not= audit-database-id]))++(defn universe-tables+ "The scoring columns of the active Tables outside the Database with `audit-database-id`."+ [audit-database-id]+ (t2/select [:model/Table :id :name :collection_id :is_published :visibility_type :db_id :data_layer :data_authority]+ :active true+ :db_id [:not= audit-database-id]))++(defn metabot-by-entity-id+ "The Metabot with `entity-id`, or nil."+ [entity-id]+ (t2/select-one :model/Metabot :entity_id entity-id))++(defn latest-score-entry+ "The most recent DataComplexityScore of `source` for `fingerprint`, or nil."+ [fingerprint source]+ (t2/select-one :model/DataComplexityScore :fingerprint fingerprint :source source {:order-by [[:id :desc]]}))++(defn score-entry+ "The DataComplexityScore with `id`, or nil."+ [id]+ (t2/select-one :model/DataComplexityScore :id id))++(defn scored-within-hours?+ "Whether a DataComplexityScore of `source` for `fingerprint` was created within the last `hours` hours of+ database time."+ [fingerprint source hours]+ (t2/exists? :model/DataComplexityScore+ {:where [:and+ [:= :fingerprint fingerprint]+ [:= :source source]+ [:>= :created_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- hours) :hour)]]}))++(defn insert-score!+ "Insert `score-entry` and return its ID."+ [score-entry]+ (t2/insert-returning-pk! :model/DataComplexityScore score-entry))++(defn delete-scores-created-before!+ "Delete the DataComplexityScores created before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/DataComplexityScore {:where [:< :created_at cutoff]}))diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/metabot_scope.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/metabot_scope.cljindex a8f0416b0e6..e6b29a9d1d7 100644--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/metabot_scope.clj+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/metabot_scope.clj@@ -1,14 +1,14 @@(ns metabase-enterprise.data-complexity-score.metabot-scope"Resolves the internal Metabot's retrieval scope for the `:metabot` catalog."(:require- [metabase.metabot.config :as metabot.config]- [toucan2.core :as t2]))+ [metabase-enterprise.data-complexity-score.db :as data-complexity-score.db]+ [metabase.metabot.config :as metabot.config]))(defn internal-metabot-scope"`{:curated-only? <bool> :collection-id <nil|Long>}` matching the filters Metabot search applies."[](let [entity-id (get-in metabot.config/metabot-config [metabot.config/internal-metabot-id :entity-id])- metabot (t2/select-one :model/Metabot :entity_id entity-id)]+ metabot (data-complexity-score.db/metabot-by-entity-id entity-id)];; `use_verified_content` means "verified or curated content only" (see the note in;; `metabase.metabot.models.metabot`). No premium-feature gate, mirroring the search index's;; precomputed `curated` column: a curation signal can only be set while its feature is present,diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/models/data_complexity_score.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/models/data_complexity_score.cljindex 04f6f1746bb..628f4124d93 100644--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/models/data_complexity_score.clj+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/models/data_complexity_score.clj@@ -1,9 +1,8 @@(ns metabase-enterprise.data-complexity-score.models.data-complexity-score"Persistence for cached Data Complexity Score snapshots."(:require- [metabase.app-db.core :as mdb]+ [metabase-enterprise.data-complexity-score.db :as data-complexity-score.db][metabase.models.interface :as mi]- [metabase.util.honey-sql-2 :as h2x][methodical.core :as methodical][toucan2.core :as t2]))@@ -24,8 +23,7 @@"Return the most recently persisted Data Complexity Score row for `fingerprint`, or nil if none exist."([fingerprint] (latest-entry fingerprint "appdb"))([fingerprint source]- (t2/select-one :model/DataComplexityScore- :fingerprint fingerprint :source source {:order-by [[:id :desc]]})))+ (data-complexity-score.db/latest-score-entry fingerprint source)))(defn latest-score"Return the latest persisted Data Complexity Score payload for `fingerprint`, or nil if none exist."@@ -40,19 +38,14 @@we never compare it against the app server's clock.Lets the scoring task skip a run that would only re-publish a still-fresh score."[fingerprint source cooldown-hours]- (t2/exists? :model/DataComplexityScore- {:where [:and- [:= :fingerprint fingerprint]- [:= :source source]- [:>= :created_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- cooldown-hours) :hour)]]}))+ (data-complexity-score.db/scored-within-hours? fingerprint source cooldown-hours))(defn record-score!"Persist one append-only Data Complexity Score snapshot."[fingerprint source score]- (let [id (t2/insert-returning-pk! :model/DataComplexityScore- {:fingerprint fingerprint- :source source- :score_data score})]+ (let [id (data-complexity-score.db/insert-score! {:fingerprint fingerprint+ :source source+ :score_data score})](if id- (score-with-calculated-at (t2/select-one :model/DataComplexityScore :id id))+ (score-with-calculated-at (data-complexity-score.db/score-entry id))(latest-score fingerprint source))))diff --git a/enterprise/backend/src/metabase_enterprise/data_complexity_score/task/complexity_score_trimmer.clj b/enterprise/backend/src/metabase_enterprise/data_complexity_score/task/complexity_score_trimmer.cljindex 3f9f506ef48..61fbcaa7f26 100644--- a/enterprise/backend/src/metabase_enterprise/data_complexity_score/task/complexity_score_trimmer.clj+++ b/enterprise/backend/src/metabase_enterprise/data_complexity_score/task/complexity_score_trimmer.clj@@ -5,9 +5,9 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.data-complexity-score.db :as data-complexity-score.db][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.sql Timestamp)(org.quartz DisallowConcurrentExecution)))@@ -31,7 +31,7 @@[](log/info "Trimming old Data Complexity Score snapshots.")(let [cutoff (retention-cutoff-timestamp retention-months)- deleted (t2/delete! :model/DataComplexityScore {:where [:< :created_at cutoff]})]+ deleted (data-complexity-score.db/delete-scores-created-before! cutoff)](log/infof "Data Complexity Score cleanup complete. Deleted %d rows." (or deleted 0))))(task/defjob ^{DisallowConcurrentExecution truediff --git a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.cljindex 41d70f499cb..a94802c5ac3 100644--- a/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj+++ b/enterprise/backend/src/metabase_enterprise/data_studio/api/table.clj@@ -2,7 +2,7 @@"/api/ee/data-studio/table endpoints for bulk table operations (enterprise-only endpoints)."(:require[clojure.set :as set]- [clojure.string :as str]+ [metabase-enterprise.data-studio.db :as data-studio.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -11,10 +11,8 @@[metabase.models.interface :as mi][metabase.premium-features.core :refer [defenterprise]][metabase.util.i18n :refer [tru]]- [metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)@@ -31,15 +29,10 @@[:map[:collection_id ms/PositiveInt]]])-(mu/defn ^:private table-selectors->filter+(defn- body->table-selectors+ "The table selectors of a request `body`, as [[data-studio.db/table-ids-matching-selectors]] expects them."[{:keys [database_ids table_ids schema_ids]}]- (let [schema-expr (fn [s]- (let [[schema-db-id schema-name] (str/split s #"\:")]- [:and [:= :db_id (parse-long schema-db-id)] [:= :schema schema-name]]))]- (cond-> [:or false]- (seq database_ids) (conj [:in :db_id (sort database_ids)])- (seq table_ids) (conj [:in :id (sort table_ids)])- (seq schema_ids) (conj (into [:or] (map schema-expr) (sort schema_ids))))))+ {:database-ids database_ids, :table-ids table_ids, :schema-ids schema_ids});;; ------------------------------------------------ Remapping Graph Traversal ------------------------------------------------@@ -47,29 +40,12 @@"Find tables connected via FK remapping (Dimensions).`input-field` and `output-field` are field aliases (:source_field or :target_field).Returns table IDs from `output-field` that are connected to `tables` via `input-field`.- `tables` can be a set of table IDs or a HoneySQL subquery map."+ `tables` can be a set of table IDs or a table-selectors map."[input-field output-field tables](if (empty? tables)#{}- (let [input-table-id (keyword (name input-field) "table_id")- output-table-id (keyword (name output-field) "table_id")- not-in-tables (if (map? tables)- [:not [:exists (-> tables- (assoc :select [1])- (update :where (fn [where]- [:and where [:= :id output-table-id]])))]]- [:not [:in output-table-id tables]])]- (into #{} (map :table_id)- (t2/reducible-query {:select [[output-table-id :table_id]]- :from [[(t2/table-name :model/Dimension) :dim]]- :join [[(t2/table-name :model/Field) :source_field]- [:= :dim.field_id :source_field.id]- [(t2/table-name :model/Field) :target_field]- [:= :dim.human_readable_field_id :target_field.id]]- :where [:and- [:= :dim.type "external"]- [:in input-table-id tables]- not-in-tables]})))))+ (into #{} (map :table_id)+ (data-studio.db/remapped-table-ids-reducible input-field output-field tables))))(defn- upstream-table-ids"Given a table selector (set of IDs or subquery), find all tables that these tables depend on@@ -83,11 +59,6 @@[target-tables](remapped-table-ids :target_field :source_field target-tables))-(defn- table-subquery- "Create a subquery that selects table IDs matching the given WHERE clause."- [where]- ^:allow-subquery {:select [:id] :from [(t2/table-name :model/Table)] :where where})-(defn- traverse-graph"Recursively traverse the remapping graph starting from initial-ids.Returns all reachable table IDs (including initial-ids)."@@ -101,21 +72,21 @@new-neighbors)))))(defn- all-upstream-table-ids- "Get all upstream table IDs recursively for tables matching the given WHERE clause.+ "Get all upstream table IDs recursively for tables matching the given table selectors.The first hop uses a subquery to avoid materializing potentially millions of IDs;subsequent hops use IDs since remappings are rare."- [source-table-where]- (let [initial-ids (upstream-table-ids (table-subquery source-table-where))]+ [source-table-selectors]+ (let [initial-ids (upstream-table-ids source-table-selectors)](if (empty? initial-ids)#{}(traverse-graph upstream-table-ids initial-ids))))(defn- all-downstream-table-ids- "Get all downstream table IDs recursively for tables matching the given WHERE clause.+ "Get all downstream table IDs recursively for tables matching the given table selectors.The first hop uses a subquery to avoid materializing potentially millions of IDs;subsequent hops use IDs since remappings are rare."- [target-table-where]- (let [initial-ids (downstream-table-ids (table-subquery target-table-where))]+ [target-table-selectors]+ (let [initial-ids (downstream-table-ids target-table-selectors)](if (empty? initial-ids)#{}(traverse-graph downstream-table-ids initial-ids))))@@ -129,15 +100,13 @@:feature :library[seed-table-ids](when (seq seed-table-ids)- (let [downstream-ids (all-downstream-table-ids [:in :id seed-table-ids])+ (let [downstream-ids (all-downstream-table-ids {:table-ids seed-table-ids})table-ids-to-update (when (seq downstream-ids)- (t2/select-pks-set :model/Table :id [:in downstream-ids] :is_published true))]+ (data-studio.db/published-table-ids downstream-ids))](when (seq table-ids-to-update)- (t2/update! :model/Table :id [:in table-ids-to-update]- {:collection_id nil- :is_published false})+ (data-studio.db/unpublish-tables! table-ids-to-update);; Publish events for audit log and remote sync tracking- (let [updated-tables (t2/select :model/Table :id [:in table-ids-to-update])]+ (let [updated-tables (data-studio.db/tables table-ids-to-update)](doseq [table updated-tables](events/publish-event! :event/table-unpublish {:object table:user-id api/*current-user-id*})))))))@@ -160,7 +129,7 @@"This function returns `true` iff you have permission to publish every table passed."[table-ids](every? can-publish? (when (seq table-ids)- (t2/select :model/Table :id [:in table-ids]))))+ (data-studio.db/tables table-ids))))(api.macros/defendpoint :post "/publish-tables" :- ::publish-tables-response"Set collection for each of selected tables and all upstream dependencies recursively."@@ -168,24 +137,19 @@_query-paramsbody :- ::publish-table-selectors](api/check-data-analyst)- (let [target-collection (api/check-404 (t2/select-one :model/Collection (:collection_id body)))+ (let [target-collection (api/check-404 (data-studio.db/collection (:collection_id body)))_ (api/check-400 (= (:type target-collection) collection/library-data-collection-type)(tru "Tables can only be published to Library/Data collections."))- where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))- upstream-ids (all-upstream-table-ids where)- ;; Don't move already-published upstream tables; only publish unpublished ones.- update-where (if (seq upstream-ids)- [:or where [:and [:in :id upstream-ids] [:= :is_published false]]]- where)- ;; Get table IDs before update for event publishing- table-ids-to-update (t2/select-pks-set :model/Table {:where update-where})]+ selectors (body->table-selectors body)+ upstream-ids (all-upstream-table-ids selectors)+ ;; Don't move already-published upstream tables; only publish unpublished ones. Get table IDs before update+ ;; for event publishing.+ table-ids-to-update (data-studio.db/table-ids-matching-selectors selectors upstream-ids :unpublished)](api/check-403 (can-publish-all-tables? table-ids-to-update))(when (seq table-ids-to-update)- (t2/update! :model/Table :id [:in table-ids-to-update]- {:collection_id (:id target-collection)- :is_published true})+ (data-studio.db/publish-tables! table-ids-to-update (:id target-collection));; Publish events for audit log and remote sync tracking- (let [updated-tables (t2/select :model/Table :id [:in table-ids-to-update])]+ (let [updated-tables (data-studio.db/tables table-ids-to-update)](doseq [table updated-tables](events/publish-event! :event/table-publish {:object table:user-id api/*current-user-id*}))))@@ -197,20 +161,15 @@_query-paramsbody :- ::table-selectors](api/check-data-analyst)- (let [where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))- downstream-ids (all-downstream-table-ids where)- update-where (if (seq downstream-ids)- [:or where [:in :id downstream-ids]]- where)+ (let [selectors (body->table-selectors body)+ downstream-ids (all-downstream-table-ids selectors);; Get table IDs before update for event publishing- table-ids-to-update (t2/select-pks-set :model/Table {:where update-where})]+ table-ids-to-update (data-studio.db/table-ids-matching-selectors selectors downstream-ids :any)](api/check-403 (can-publish-all-tables? table-ids-to-update))(when (seq table-ids-to-update)- (t2/update! :model/Table :id [:in table-ids-to-update]- {:collection_id nil- :is_published false})+ (data-studio.db/unpublish-tables! table-ids-to-update);; Publish events for audit log and remote sync tracking- (let [updated-tables (t2/select :model/Table :id [:in table-ids-to-update])]+ (let [updated-tables (data-studio.db/tables table-ids-to-update)](doseq [table updated-tables](events/publish-event! :event/table-unpublish {:object table:user-id api/*current-user-id*}))))diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/db.clj b/enterprise/backend/src/metabase_enterprise/data_studio/db.cljnew file mode 100644index 00000000000..22ce0ba01fc--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/data_studio/db.clj@@ -0,0 +1,114 @@+(ns metabase-enterprise.data-studio.db+ "Application database queries for the data-studio module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [clojure.string :as str]+ [metabase.collections.models.collection :as collection]+ [toucan2.core :as t2]))++(defn- table-selectors-expr+ "Matches the Tables selected by `database-ids`, `table-ids`, and `schema-ids` (each `\"<db-id>:<schema>\"`)."+ [{:keys [database-ids table-ids schema-ids]}]+ (let [schema-expr (fn [s]+ (let [[schema-db-id schema-name] (str/split s #"\:")]+ [:and [:= :db_id (parse-long schema-db-id)] [:= :schema schema-name]]))]+ (cond-> [:or false]+ (seq database-ids) (conj [:in :db_id (sort database-ids)])+ (seq table-ids) (conj [:in :id (sort table-ids)])+ (seq schema-ids) (conj (into [:or] (map schema-expr) (sort schema-ids))))))++(defn- table-selectors-subquery+ [selectors]+ ^:allow-subquery {:select [:id] :from [(t2/table-name :model/Table)] :where (table-selectors-expr selectors)})++(defn remapped-table-ids-reducible+ "Reducible `:table_id` rows of the Tables reachable from `tables` through FK remapping Dimensions, from the+ `input-field` side to the `output-field` side (`:source_field` or `:target_field`), excluding `tables` themselves.+ `tables` is a set of Table IDs or a selectors map (see [[table-ids-matching-selectors]])."+ [input-field output-field tables]+ (let [input-table-id (keyword (name input-field) "table_id")+ output-table-id (keyword (name output-field) "table_id")+ table-ids (if (map? tables)+ (table-selectors-subquery tables)+ tables)+ not-in-tables (if (map? tables)+ [:not [:exists (-> table-ids+ (assoc :select [1])+ (update :where (fn [where]+ [:and where [:= :id output-table-id]])))]]+ [:not [:in output-table-id tables]])]+ (t2/reducible-query {:select [[output-table-id :table_id]]+ :from [[(t2/table-name :model/Dimension) :dim]]+ :join [[(t2/table-name :model/Field) :source_field]+ [:= :dim.field_id :source_field.id]+ [(t2/table-name :model/Field) :target_field]+ [:= :dim.human_readable_field_id :target_field.id]]+ :where [:and+ [:= :dim.type "external"]+ [:in input-table-id table-ids]+ not-in-tables]})))++(defn table-ids-matching-selectors+ "The IDs of the Tables selected by `selectors` (`{:database-ids :table-ids :schema-ids}`) plus, when given, the+ `extra-table-ids` that are unpublished (`:unpublished` mode) or any of them (`:any` mode)."+ [selectors extra-table-ids extra-mode]+ (t2/select-pks-set :model/Table+ {:where (let [selector-expr (table-selectors-expr selectors)]+ (if (seq extra-table-ids)+ [:or selector-expr (case extra-mode+ :unpublished [:and [:in :id extra-table-ids] [:= :is_published false]]+ :any [:in :id extra-table-ids])]+ selector-expr))}))++(defn published-table-ids+ "The IDs of the published Tables among `table-ids`."+ [table-ids]+ (t2/select-pks-set :model/Table :id [:in table-ids] :is_published true))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection collection-id))++(defn publish-tables!+ "Publish the Tables with `table-ids` into the Collection with `collection-id`."+ [table-ids collection-id]+ (t2/update! :model/Table :id [:in table-ids] {:collection_id collection-id, :is_published true}))++(defn unpublish-tables!+ "Unpublish the Tables with `table-ids` and detach them from their Collection."+ [table-ids]+ (t2/update! :model/Table :id [:in table-ids] {:collection_id nil, :is_published false}))++(defn published-table-visible-to-user?+ "Whether the Table with `table-id` is published in a Collection the User with `user-id` can read."+ [table-id user-id superuser?]+ (t2/exists? :model/Table+ {:where [:and+ [:= :id table-id]+ [:= :is_published true]+ (collection/visible-collection-filter-clause+ :collection_id {} {:current-user-id user-id+ :is-superuser? superuser?})]}))++(defn any-published-table-visible?+ "Whether the current user can read the Collection of any published Table."+ []+ (t2/exists? :model/Table+ {:where [:and+ [:= :is_published true]+ (collection/visible-collection-filter-clause :collection_id)]}))++(defn published-table-visible-in-database?+ "Whether the current user can read the Collection of any published Table in the Database with `database-id`."+ [database-id]+ (t2/exists? :model/Table+ {:where [:and+ [:= :db_id database-id]+ [:= :is_published true]+ (collection/visible-collection-filter-clause :collection_id)]}))diff --git a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.cljindex 1bba40503fc..904d263291c 100644--- a/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj+++ b/enterprise/backend/src/metabase_enterprise/data_studio/permissions/published_tables.clj@@ -2,12 +2,12 @@"Enterprise implementation of published table permissions.Provides query access to published tables via collection permissions."(:require+ [metabase-enterprise.data-studio.db :as data-studio.db][metabase.collections.models.collection :as collection][metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]]- [metabase.util.honey-sql-2 :as h2x]- [toucan2.core :as t2]))+ [metabase.util.honey-sql-2 :as h2x]))(defenterprise user-published-table-permission"Returns :query-builder permission if table is published and user has collection access.@@ -15,33 +15,20 @@:feature :library[user-id perm-type table-id](when (and (= perm-type :perms/create-queries)- (t2/exists? :model/Table- {:where [:and- [:= :id table-id]- [:= :is_published true]- (collection/visible-collection-filter-clause- :collection_id {} {:current-user-id user-id- :is-superuser? (perms/is-superuser? user-id)})]}))+ (data-studio.db/published-table-visible-to-user? table-id user-id (perms/is-superuser? user-id))):query-builder))(defenterprise user-has-any-published-table-permission?"Returns true if user has access to any published table via collection permissions.":feature :library[]- (t2/exists? :model/Table- {:where [:and- [:= :is_published true]- (collection/visible-collection-filter-clause :collection_id)]}))+ (data-studio.db/any-published-table-visible?))(defenterprise user-has-published-table-permission-for-database?"Returns true if user has access to any published table in the given database via collection permissions.":feature :library[database-id]- (t2/exists? :model/Table- {:where [:and- [:= :db_id database-id]- [:= :is_published true]- (collection/visible-collection-filter-clause :collection_id)]}))+ (data-studio.db/published-table-visible-in-database? database-id))(defenterprise can-access-via-collection?"Returns true if the user can access this published table via collection read permissions."diff --git a/enterprise/backend/src/metabase_enterprise/database_replication/api.clj b/enterprise/backend/src/metabase_enterprise/database_replication/api.cljindex d53a7873013..53c0a8a4aa1 100644--- a/enterprise/backend/src/metabase_enterprise/database_replication/api.clj+++ b/enterprise/backend/src/metabase_enterprise/database_replication/api.clj@@ -3,6 +3,7 @@[clojure.core.memoize :as memoize][clojure.set :as set][medley.core :as m]+ [metabase-enterprise.database-replication.db :as database-replication.db][metabase-enterprise.database-replication.settings :as database-replication.settings][metabase-enterprise.harbormaster.client :as hm.client][metabase.api.common :as api]@@ -12,8 +13,7 @@[metabase.premium-features.core :as premium-features][metabase.util :as u][metabase.util.log :as log]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import(java.util.regex PatternSyntaxException)))@@ -147,7 +147,7 @@(api.macros/defendpoint :post "/connection/:database-id/preview""Return info about pg-replication connection that is about to be created."[{:keys [database-id]} :- [:map [:database-id ms/PositiveInt]] _ {:keys [replicationSchemaFilters]} :- body-schema]- (let [database (t2/select-one :model/Database :id database-id)+ (let [database (database-replication.db/database database-id)secret (->secret database)replication-schema-filters (m->schema-filter replicationSchemaFilters)](u/recursive-map-keys u/->camelCaseEn (preview-replication (premium-features/quotas) (preview-tables secret replication-schema-filters)))))@@ -160,7 +160,7 @@"Create a new PG replication connection for the specified database."[{:keys [database-id]} :- [:map [:database-id ms/PositiveInt]] _ {:keys [replicationSchemaFilters]} :- body-schema](api/check-400 (database-replication.settings/database-replication-enabled) "PG replication integration is not enabled.")- (let [database (t2/select-one :model/Database :id database-id)+ (let [database (database-replication.db/database database-id)db-details (:details database)](api/check-404 database)(api/check-400 (= :postgres (:engine database)) "PG replication is only supported for PostgreSQL databases.")diff --git a/enterprise/backend/src/metabase_enterprise/database_replication/db.clj b/enterprise/backend/src/metabase_enterprise/database_replication/db.cljnew file mode 100644index 00000000000..380bd6d14ef--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/database_replication/db.clj@@ -0,0 +1,10 @@+(ns metabase-enterprise.database-replication.db+ "Application database queries for the database-replication module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))diff --git a/enterprise/backend/src/metabase_enterprise/database_routing/api.clj b/enterprise/backend/src/metabase_enterprise/database_routing/api.cljindex fef4a8a77d5..733dbca491e 100644--- a/enterprise/backend/src/metabase_enterprise/database_routing/api.clj+++ b/enterprise/backend/src/metabase_enterprise/database_routing/api.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.database-routing.api(:require+ [metabase-enterprise.database-routing.db :as database-routing.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -9,8 +10,7 @@[metabase.settings.core :as setting][metabase.util :as u][metabase.util.malli.schema :as ms]- [metabase.warehouses.core :as warehouses]- [toucan2.core :as t2]))+ [metabase.warehouses.core :as warehouses]));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST API@@ -36,10 +36,10 @@[:map[:name ms/NonBlankString][:details ms/Map]]]]]]- (api/check-400 (t2/exists? :model/DatabaseRouter :database_id router_database_id))- (api/check-400 (not (t2/exists? :model/Database :router_database_id router_database_id :name [:in (map :name destinations)]))+ (api/check-400 (database-routing.db/router-exists? router_database_id))+ (api/check-400 (not (database-routing.db/destination-name-exists? router_database_id (map :name destinations)))"A destination database with that name already exists.")- (let [{:keys [engine auto_run_queries is_on_demand] :as router-db} (t2/select-one :model/Database :id router_database_id)]+ (let [{:keys [engine auto_run_queries is_on_demand] :as router-db} (database-routing.db/database router_database_id)](if-let [invalid-destinations (->> destinations(keep (fn [{details :details n :name}](try@@ -53,8 +53,7 @@seq)]{:status 400:body (into {} invalid-destinations)}- (u/prog1 (t2/insert-returning-instances!- :model/Database+ (u/prog1 (database-routing.db/insert-databases!(map (fn [{:keys [name details]}]{:name name:engine engine@@ -75,16 +74,16 @@(defn- delete-router![db-id]- (let [db (t2/select-one :model/Database db-id)]+ (let [db (database-routing.db/database db-id)](events/publish-event! :event/database-update {:object db:previous-object db:user-id api/*current-user-id*:details {:db_routing :disabled}})- (t2/delete! :model/DatabaseRouter :database_id db-id)))+ (database-routing.db/delete-router! db-id)))(defn- create-or-update-router![db-id user-attribute]- (let [db (t2/select-one :model/Database db-id)]+ (let [db (database-routing.db/database db-id)](when-not (driver.u/supports? (:engine db) :database-routing db)(throw (ex-info "This database does not support DB routing" {:status-code 400})))(events/publish-event! :event/database-update {:object db@@ -92,9 +91,9 @@:user-id api/*current-user-id*:details {:db_routing :enabled:routing_attribute user-attribute}})- (if (t2/select-one :model/DatabaseRouter :database_id db-id)- (t2/update! :model/DatabaseRouter :database_id db-id {:user_attribute user-attribute})- (t2/insert! :model/DatabaseRouter {:database_id db-id :user_attribute user-attribute}))))+ (if (database-routing.db/router-for-database db-id)+ (database-routing.db/update-router-user-attribute! db-id user-attribute)+ (database-routing.db/insert-router! db-id user-attribute))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -109,13 +108,13 @@[{:keys [id]} :- [:map [:id ms/PositiveInt]]_query-params{:keys [user_attribute]} :- [:map [:user_attribute {:optional true} [:maybe ms/NonBlankString]]]]- (let [db (t2/select-one :model/Database :id id)]+ (let [db (database-routing.db/database id)](api/check-404 db)(api/check-400 (not (:router_database_id db)) "Cannot make a destination database a router database")(api/check-400 (not (:uploads_enabled db)) "Cannot enable database routing for a database with uploads enabled")(api/check-400 (not (:write_data_details db)) "Cannot enable database routing for a database with a write connection configured")(api/check-400 (not (:admin_details db)) "Cannot enable database routing for a database with an admin connection configured")- (api/check-400 (not (t2/exists? :model/Transform :source_database_id id)) "Cannot enable database routing for a database with transforms")+ (api/check-400 (not (database-routing.db/transform-exists-for-source-database? id)) "Cannot enable database routing for a database with transforms")(setting/with-database db(api/check-400 (not (setting/get :persist-models-enabled)) "Cannot enable database routing for a database with model persistence enabled")(api/check-400 (not (setting/get :database-enable-actions)) "Cannot enable database routing for a database with actions enabled")))diff --git a/enterprise/backend/src/metabase_enterprise/database_routing/common.clj b/enterprise/backend/src/metabase_enterprise/database_routing/common.cljindex 0e809b7731a..879cd7f555e 100644--- a/enterprise/backend/src/metabase_enterprise/database_routing/common.clj+++ b/enterprise/backend/src/metabase_enterprise/database_routing/common.clj@@ -1,15 +1,15 @@(ns metabase-enterprise.database-routing.common(:require+ [metabase-enterprise.database-routing.db :as database-routing.db][metabase.api.common :as api][metabase.premium-features.core :refer [defenterprise]][metabase.util :as u]- [metabase.util.i18n :refer [tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [tru]]))(defn- user-attribute"Which user attribute should we use for this RouterDB?"[db-or-id]- (t2/select-one-fn :user_attribute :model/DatabaseRouter :database_id (u/the-id db-or-id)))+ (database-routing.db/router-user-attribute (u/the-id db-or-id)))(def ^:dynamic ^:private *database-routing-on* :unset)@@ -26,7 +26,7 @@(throw (ex-info (tru "Anonymous users cannot access a database with routing enabled.") {:status-code 400:database-routing-enabled true:database-or-id db-or-id- :database-name (t2/select-one-fn :name :model/Database (u/the-id db-or-id))}))+ :database-name (database-routing.db/database-name (u/the-id db-or-id))}))(= database-name "__METABASE_ROUTER__")nil@@ -44,9 +44,7 @@:status-code 400})):else- (or (t2/select-one-pk :model/Database- :router_database_id (u/the-id db-or-id)- :name database-name)+ (or (database-routing.db/destination-database-id (u/the-id db-or-id) database-name)(throw (ex-info (tru "Database Routing error: No Destination Database with slug `{0}` found."database-name){:database-name database-name@@ -114,7 +112,7 @@(defn- is-disallowed-destination-db-access?[db-or-id]- (and (t2/exists? :model/Database :id db-or-id :router_database_id [:not= nil])+ (and (database-routing.db/destination-database? db-or-id)(not= *database-routing-on* :on)))(defn assert-not-direct-destination-access!diff --git a/enterprise/backend/src/metabase_enterprise/database_routing/db.clj b/enterprise/backend/src/metabase_enterprise/database_routing/db.cljnew file mode 100644index 00000000000..26163cc3020--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/database_routing/db.clj@@ -0,0 +1,75 @@+(ns metabase-enterprise.database-routing.db+ "Application database queries for the database-routing module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods, and transactions."+ (:require+ [toucan2.core :as t2]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn database-name+ "The name of the Database with `database-id`."+ [database-id]+ (t2/select-one-fn :name :model/Database database-id))++(defn destination-database?+ "Whether the Database with `database-id` is a routing destination."+ [database-id]+ (t2/exists? :model/Database :id database-id :router_database_id [:not= nil]))++(defn destination-database-id+ "The ID of the destination Database of the router with `router-database-id` named `database-name`, or nil."+ [router-database-id database-name]+ (t2/select-one-pk :model/Database :router_database_id router-database-id :name database-name))++(defn destination-name-exists?+ "Whether the router with `router-database-id` already has a destination Database named one of `names`."+ [router-database-id names]+ (t2/exists? :model/Database :router_database_id router-database-id :name [:in names]))++(defn insert-databases!+ "Insert the Database `rows` and return the new instances."+ [rows]+ (t2/insert-returning-instances! :model/Database rows))++(defn transform-exists-for-source-database?+ "Whether a Transform reads from the Database with `database-id`."+ [database-id]+ (t2/exists? :model/Transform :source_database_id database-id))++(defn router-exists?+ "Whether the Database with `database-id` is a router."+ [database-id]+ (t2/exists? :model/DatabaseRouter :database_id database-id))++(defn router-for-database+ "The DatabaseRouter of the Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/DatabaseRouter :database_id database-id))++(defn router-user-attribute+ "The user attribute the router of the Database with `database-id` routes on."+ [database-id]+ (t2/select-one-fn :user_attribute :model/DatabaseRouter :database_id database-id))++(defn router-user-attributes-by-database+ "A map of Database ID to routing user attribute for `database-ids`."+ [database-ids]+ (t2/select-fn->fn :database_id :user_attribute :model/DatabaseRouter :database_id [:in database-ids]))++(defn insert-router!+ "Insert a DatabaseRouter for the Database with `database-id` routing on `user-attribute`."+ [database-id user-attribute]+ (t2/insert! :model/DatabaseRouter {:database_id database-id :user_attribute user-attribute}))++(defn update-router-user-attribute!+ "Set the routing user attribute of the router of the Database with `database-id`."+ [database-id user-attribute]+ (t2/update! :model/DatabaseRouter :database_id database-id {:user_attribute user-attribute}))++(defn delete-router!+ "Delete the DatabaseRouter of the Database with `database-id`."+ [database-id]+ (t2/delete! :model/DatabaseRouter :database_id database-id))diff --git a/enterprise/backend/src/metabase_enterprise/database_routing/models.clj b/enterprise/backend/src/metabase_enterprise/database_routing/models.cljindex eddea3388c9..33e59adff1e 100644--- a/enterprise/backend/src/metabase_enterprise/database_routing/models.clj+++ b/enterprise/backend/src/metabase_enterprise/database_routing/models.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.database-routing.models(:require[metabase-enterprise.database-routing.common :refer [router-db-or-id->destination-db-id]]+ [metabase-enterprise.database-routing.db :as database-routing.db][metabase.models.interface :as mi][metabase.premium-features.core :refer [defenterprise]][metabase.util :as u]@@ -19,8 +20,7 @@[k databases](mi/instances-with-hydrated-datadatabases k- (fn [] (t2/select-fn->fn :database_id :user_attribute :model/DatabaseRouter- :database_id [:in (map :id databases)]))+ (fn [] (database-routing.db/router-user-attributes-by-database (map :id databases))):id{:default nil}))@@ -35,13 +35,13 @@"Deletes the Database Router associated with this router database.":feature :database-routing[db-id]- (t2/delete! :model/DatabaseRouter :database_id db-id))+ (database-routing.db/delete-router! db-id))(defenterprise db-routing-enabled?"Returns whether or not the given database is either a router or destination database.":feature :database-routing:fallback :oss[db-or-id]- (or (t2/exists? :model/DatabaseRouter :database_id (u/the-id db-or-id))+ (or (database-routing.db/router-exists? (u/the-id db-or-id))(some->> (:router-database-id db-or-id)- (t2/exists? :model/DatabaseRouter :database_id))))+ database-routing.db/router-exists?)))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj b/enterprise/backend/src/metabase_enterprise/dependencies/api.cljindex d9abfe517cb..8d3cd397c54 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj@@ -1,7 +1,7 @@(ns metabase-enterprise.dependencies.api(:require- [clojure.set :as set][clojure.string :as str]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.dependency-types :as deps.dependency-types][metabase-enterprise.dependencies.models.analysis-finding-error :as analysis-finding-error][metabase-enterprise.dependencies.models.dependency :as dependency]@@ -10,19 +10,14 @@[metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.api.util.handlers :as handlers]- [metabase.app-db.core :as mdb]- [metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as collection.root][metabase.documents.schema :as documents.schema][metabase.graph.core :as graph][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata]- [metabase.models.interface :as mi]- [metabase.permissions.core :as perms][metabase.request.core :as request][metabase.revisions.core :as revisions][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]@@ -187,180 +182,25 @@:segment [:id :name :description :created_at :creator_id :table_id]:measure [:id :name :description :created_at :creator_id :table_id]})-(defn- visible-entities-filter-clause- "Returns a HoneySQL WHERE clause for filtering dependency graph entities by user visibility.-- Accepts three arguments:- - `entity-type-field`: Database column name for entity type (e.g., :to_entity_type)- - `entity-id-field`: Database column name for entity ID (e.g., :to_entity_id)- - `include-archived-items`: How to handle archived items (:exclude, :all, :only). Defaults to :exclude.- This applies to both archived collections AND archived entities (cards/dashboards/documents/snippets).-- Returns a compound [:or ...] clause checking whether entities at those columns are readable.-- Handles different entity types:- - Superuser-only (:model/Sandbox): Only if api/*is-superuser?* is true- - Collection-based (:model/Card, :model/Dashboard, :model/Document, :model/NativeQuerySnippet):- Uses collection/visible-collection-filter-clause for collection filtering and adds archived entity filtering.- Native query snippets have additional restrictions for sandboxed users.- - Table: Uses perms/visible-table-filter-select with appropriate permissions. Tables are NOT filtered by- active/visibility_type regardless of `include-archived-items`, so dependencies broken by dropped or- hidden tables stay visible.- - Transform: Analysts can view any transform they have source view permission to."- ([entity-type-field entity-id-field]- (visible-entities-filter-clause entity-type-field entity-id-field nil))- ([entity-type-field entity-id-field {:keys [include-archived-items] :or {include-archived-items :exclude}}]- (into [:or]- (keep (fn [[entity-type model]]- (let [table-name (t2/table-name model)- id-column (keyword (name table-name) "id")]- (case model- ;; Sandbox is superuser-only- :model/Sandbox- (when api/*is-superuser?*- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field ^:allow-subquery {:select [:id] :from [table-name]}]])-- :model/Transform- (cond- api/*is-superuser?*- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field ^:allow-subquery {:select [:id] :from [table-name]}]]-- api/*is-data-analyst?*- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field- ^:allow-subquery- {:select [:id]- :from [table-name]- :where [:in :source_database_id- (perms/visible-database-filter-select- {:user-id api/*current-user-id*- :is-superuser? api/*is-superuser?*- :is-data-analyst? api/*is-data-analyst?*}- {:perms/create-queries :query-builder})]}]])-- ;; Collection-based entities with archived field- (:model/Card :model/Dashboard :model/Document :model/NativeQuerySnippet)- (let [archived-column (keyword (name table-name) "archived")]- (when-not (and (= model :model/NativeQuerySnippet)- (or (perms/sandboxed-user?)- (not (perms/user-has-any-perms-of-type?- api/*current-user-id* :perms/create-queries))))- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field- ^:allow-subquery- {:select [:id]- :from [table-name]- :where [:and- ;; Filter by collection visibility- (collection/visible-collection-filter-clause- (keyword (name table-name) "collection_id")- {:include-archived-items include-archived-items}- {:current-user-id api/*current-user-id*- :is-superuser? api/*is-superuser?*})- ;; Filter by entity archived status- (case include-archived-items- :exclude [:= archived-column false]- :only [:= archived-column true]- :all nil)]}]]))-- ;; Table with visible-filter-clause; inactive/hidden tables are always included- ;; so that dependencies broken by dropped tables stay visible- :model/Table- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field- ^:allow-subquery- {:select [:id]- :from [table-name]- :where [:in id-column- (perms/visible-table-filter-select- :id- {:user-id api/*current-user-id*- :is-superuser? api/*is-superuser?*}- {:perms/view-data :unrestricted- :perms/create-queries :query-builder})]}]]-- ;; Segment/Measure with table permissions and archived filtering- (:model/Segment :model/Measure)- (let [archived-column (keyword (name table-name) "archived")- table-id-column (keyword (name table-name) "table_id")]- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field- ^:allow-subquery- {:select [:id]- :from [table-name]- :where [:and- ;; Check that user can see the table this entity belongs to- [:in table-id-column- ^:allow-subquery- {:select [:metabase_table.id]- :from [:metabase_table]- ;; using this clause because we had to change the mi/visible-filter-clause- ;; to allow returning CTE based filters- ;; TODO(ed 2025-12-16: support using CTES in filters in dependency graph)- :where [:in :metabase_table.id- (perms/visible-table-filter-select- :id- {:user-id api/*current-user-id*- :is-superuser? api/*is-superuser?*}- {:perms/view-data :unrestricted- :perms/create-queries :query-builder})]}]- ;; Filter by archived status- (case include-archived-items- :exclude [:= archived-column false]- :only [:= archived-column true]- :all nil)]}]])))))- deps.dependency-types/dependency-type->model)))--(defn- broken-entities-filter-clause- "Returns a HoneySQL WHERE clause for filtering to only broken entities.-- Accepts two arguments:- - `entity-type-field`: Database column name for entity type (e.g., :from_entity_type)- - `entity-id-field`: Database column name for entity ID (e.g., :from_entity_id)-- Returns a clause that joins with the analysis_finding table to filter to entities- that have failed analysis (analysis_finding.result = false)."- [entity-type-field entity-id-field]- (into [:or]- (keep (fn [[entity-type _model]]- [:and- [:= entity-type-field (name entity-type)]- [:in entity-id-field- ^:allow-subquery- {:select [:analyzed_entity_id]- :from [:analysis_finding]- :where [:and- [:= :analysis_finding.analyzed_entity_type (name entity-type)]- [:= :analysis_finding.result false]]}]])- deps.dependency-types/dependency-type->model)))+(defn- current-user-visibility+ "The current user, as the `:visible` filter-spec opts consumed by `metabase-enterprise.dependencies.db`."+ [{:keys [include-archived-items]}]+ (cond-> {:user-id api/*current-user-id* :is-superuser? api/*is-superuser?* :is-data-analyst? api/*is-data-analyst?*}+ include-archived-items (assoc :include-archived-items include-archived-items)))(defn- readable-graph-dependencies([](readable-graph-dependencies nil))([opts]- (dependency/filtered-graph-dependencies- (fn [entity-type-field entity-id-field]- (visible-entities-filter-clause entity-type-field entity-id-field opts)))))+ (dependency/filtered-graph-dependencies {:visible (current-user-visibility opts)})))(defn- readable-graph-dependents([](readable-graph-dependents nil))- ([{:keys [include-archived-items broken] :or {include-archived-items :exclude} :as _opts}]+ ([{:keys [include-archived-items broken] :or {include-archived-items :exclude}}](dependency/filtered-graph-dependents- (fn [entity-type-field entity-id-field]- (let [visibility-clause (visible-entities-filter-clause entity-type-field entity-id-field- {:include-archived-items include-archived-items})]- (if broken- [:and visibility-clause (broken-entities-filter-clause entity-type-field entity-id-field)]- visibility-clause))))))+ (cond-> {:visible (current-user-visibility {:include-archived-items include-archived-items})}+ broken (assoc :broken? true)))))(defn- node-usages"Calculates the count of direct dependents for all nodes in `nodes`, based on `graph`. "@@ -372,7 +212,7 @@(keep #(when (= (first %) :card)(second %))))card->type (when (seq all-cards)- (t2/select-fn->fn :id :type [:model/Card :id :type :card_schema] :id [:in all-cards]))]+ (dependencies.db/card-types-by-id all-cards))](update-vals children-map(fn [children](->> children@@ -391,12 +231,8 @@[nodes-by-type](letfn [(errors-by-source-type-and-id [[source-type ids]](when (seq ids)- (let [finding-errors (t2/select :model/AnalysisFindingError- {:where [:and- [:= :source_entity_type (name source-type)]- [:in :source_entity_id ids]- (visible-entities-filter-clause- :analyzed_entity_type :analyzed_entity_id)]})]+ (let [finding-errors (dependencies.db/finding-errors-from-sources+ source-type ids (current-user-visibility nil))](u/group-by (juxt :source_entity_type :source_entity_id)identity conj #{} finding-errors))))](->> nodes-by-type@@ -414,14 +250,8 @@error_detail (assoc :detail error_detail)))(errors-by-entity-type-and-id [[type ids]](when (seq ids)- (let [finding-errors (t2/select :model/AnalysisFindingError- {:where [:and- [:= :analyzed_entity_type (name type)]- [:in :analyzed_entity_id ids]- [:or- [:= :source_entity_type nil]- (visible-entities-filter-clause- :source_entity_type :source_entity_id)]]})]+ (let [finding-errors (dependencies.db/finding-errors-for-entities-with-visible-sources+ type ids (current-user-visibility nil))](u/group-by (juxt :analyzed_entity_type :analyzed_entity_id)normalize-finding-error conj #{} finding-errors))))](->> nodes-by-type@@ -458,9 +288,8 @@(into {}(mapcat (fn [[entity-type entity-ids]](when (seq entity-ids)- (let [model (deps.dependency-types/dependency-type->model entity-type)- fields (entity-select-fields entity-type)]- (->> (t2/select (into [model] fields) :id [:in entity-ids])+ (let [fields (entity-select-fields entity-type)]+ (->> (dependencies.db/instances-with-columns entity-type fields entity-ids)(hydrate-entities entity-type)(map (fn [entity][[entity-type (:id entity)] entity])))))))@@ -641,184 +470,6 @@(-> (into [] dependents-filter (expanded-nodes downstream-graph nodes {:include-errors? false}))(sort-dependents sort-column sort-direction))))-(defn- entity-type-config- [entity-type]- (let [root-collection (collection.root/root-collection-with-ui-details- (case entity-type- :transform :transforms- :snippet :snippets- nil))]- {:table-name (case entity-type- :card :report_card- :table :metabase_table- :transform :transform- :snippet :native_query_snippet- :dashboard :report_dashboard- :document :document- :sandbox :sandboxes- :segment :segment- :measure :measure)- :name-column (case entity-type- :table :entity.display_name- :sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]- :entity.name)- :location-column (case entity-type- :card [:case- [:not= :entity.dashboard_id nil] :dashboard.name- [:not= :entity.document_id nil] :document.name- :else [:coalesce :collection.name (:name root-collection)]]- :table :database.name- (:transform :snippet :dashboard :document) [:coalesce :collection.name (:name root-collection)]- :sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]- (:segment :measure) :table.display_name)}))--(defn- query-type-join-and-filter- [query-type entity-type]- (case query-type- :unreferenced {:join [:dependency [:and- [:= :dependency.to_entity_id :entity.id]- [:= :dependency.to_entity_type (name entity-type)]- (visible-entities-filter-clause- :dependency.from_entity_type- :dependency.from_entity_id)]]- :join-filter [:= :dependency.id nil]}- :broken {:join [:analysis_finding [:and- [:= :analysis_finding.analyzed_entity_id :entity.id]- [:= :analysis_finding.analyzed_entity_type (name entity-type)]]]- :join-filter [:= :analysis_finding.result false]}- :breaking {:join [:analysis_finding_error [:and- [:= :analysis_finding_error.source_entity_id :entity.id]- [:= :analysis_finding_error.source_entity_type (name entity-type)]- (visible-entities-filter-clause- :analysis_finding_error.analyzed_entity_type- :analysis_finding_error.analyzed_entity_id)]]- :join-filter [:!= :analysis_finding_error.id nil]}))--(defn- location-joins-for-entity- "Returns the set of join keywords needed for location-based operations."- [entity-type]- (case entity-type- :card #{:collection :dashboard :document}- (:transform :snippet :dashboard :document) #{:collection}- (:segment :measure) #{:table}- :table #{:database}- #{}))--(defn- build-optional-filters- [{:keys [query-type entity-type card-types query include-personal-collections]}- {:keys [name-column location-column]}]- (let [card-type-filter (when (and (= entity-type :card)- (seq card-types))- {:filter [:in :entity.type (mapv name card-types)]- :filter-joins #{}})- query-filter (when (and query (not= entity-type :sandbox))- (let [pattern (h2x/like-substring query)]- {:filter [:or- [:like [:lower name-column] pattern]- [:like [:lower location-column] pattern]]- :filter-joins (location-joins-for-entity entity-type)}))- database-filter (when (= entity-type :table)- {:filter [:and [:not :database.is_sample] [:not :database.is_audit]]- :filter-joins #{:database}})- ;; Hide system-managed (internal-user) content like Usage Analytics from the unreferenced- ;; list — analytics dashboards have nothing pointing at them by design and would just be- ;; noise. The breaking-items list intentionally still surfaces them, since broken analytics- ;; deps are real signals worth showing.- internal-content-filter (when-let [model (and (= query-type :unreferenced)- (case entity-type- :card :model/Card- :dashboard :model/Dashboard- nil))]- {:filter (mi/exclude-internal-content-hsql model :table-alias :entity)- :filter-joins #{}})- ;; note that tables are not filtered by active/visibility_type, so that dependencies- ;; broken by dropped tables stay visible- archived-filter (when-not (= query-type :breaking)- {:filter (case entity-type- (:card :dashboard :document :snippet :segment :measure)- [:= :entity.archived false]- nil)- :filter-joins #{}})- personal-filter (when-not include-personal-collections- (case entity-type- (:card :dashboard :document :snippet)- (let [personal-ids (t2/select-pks-vec :model/Collection- :personal_owner_id [:not= nil]- :location "/")]- (when (seq personal-ids)- {:filter [:or- [:= :entity.collection_id nil]- [:and- [:= :collection.personal_owner_id nil]- (into [:and]- (for [pid personal-ids]- [:not-like :collection.location (str "/" pid "/%")]))]]- :filter-joins #{:collection}}))- nil))- filter-results (keep identity- [card-type-filter query-filter database-filter- internal-content-filter archived-filter personal-filter])]- {:filters (keep :filter filter-results)- :filter-joins (reduce set/union #{} (map :filter-joins filter-results))}))--(defn- sort-key-cols-and-joins- [sort-column entity-type name-column location-column]- (case sort-column- :location {:sort-column location-column- :sort-joins (location-joins-for-entity entity-type)}- :dependents-errors {:sort-column ^:allow-subquery- {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))- [:concat :error_type "-" [:coalesce :error_detail ""]]- [:composite :error_type :error_detail])]]]]- :from [:analysis_finding_error]- :where [:and- [:= :source_entity_id :entity.id]- [:= :source_entity_type (name entity-type)]- (visible-entities-filter-clause- :analyzed_entity_type :analyzed_entity_id)]}- :sort-joins #{}}- :dependents-with-errors {:sort-column ^:allow-subquery- {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))- [:concat :analyzed_entity_id "-" :analyzed_entity_type]- [:composite :analyzed_entity_id :analyzed_entity_type])]]]]- :from [:analysis_finding_error]- :where [:and- [:= :source_entity_id :entity.id]- [:= :source_entity_type (name entity-type)]- (visible-entities-filter-clause- :analyzed_entity_type :analyzed_entity_id)]}- :sort-joins #{}}- {:sort-column name-column- :sort-joins #{}}))--(defn- build-left-joins- [base-join joins]- (cond-> base-join- (:database joins) (conj [:metabase_database :database] [:= :entity.db_id :database.id])- (:collection joins) (conj :collection [:= :entity.collection_id :collection.id])- (:dashboard joins) (conj [:report_dashboard :dashboard] [:= :entity.dashboard_id :dashboard.id])- (:document joins) (conj :document [:= :entity.document_id :document.id])- (:table joins) (conj [:metabase_table :table] [:= :entity.table_id :table.id])))--(defn- dependency-items-query- [{:keys [query-type entity-type sort-column] :as params}]- (let [{:keys [table-name name-column location-column] :as config} (entity-type-config entity-type)- {:keys [join join-filter]} (query-type-join-and-filter query-type entity-type)- {:keys [filters filter-joins]} (build-optional-filters params config)- {:keys [sort-column sort-joins]} (sort-key-cols-and-joins sort-column entity-type name-column location-column)- visible-filter (visible-entities-filter-clause (name entity-type) :entity.id- (when (= query-type :breaking)- {:include-archived-items :all}))- all-required-joins (set/union filter-joins sort-joins)- select-clause [[^:allow-raw-sql [:inline (name entity-type)] :entity_type]- [:entity.id :entity_id]- [sort-column :sort_key]]]- ^:allow-subquery- {(if (= query-type :breaking) :select-distinct :select) select-clause- :from [[table-name :entity]]- :left-join (build-left-joins join all-required-joins)- :where (into [:and join-filter visible-filter] (keep identity) filters)}))-(def ^:private breaking-items-sort-columns"Valid sort columns for /graph/broken and /graph/unreferenced endpoints."#{:name :location :dependents-with-errors :dependents-errors})@@ -875,25 +526,19 @@;; Sandboxes don't support query filtering, so exclude them when a query is providedquery (remove #{:sandbox}))card-types (if (sequential? card-types) card-types [card-types])- union-queries (map #(dependency-items-query {:query-type :unreferenced- :entity-type %- :card-types card-types- :query query- :include-personal-collections include-personal-collections- :sort-column sort-column})- selected-types)- union-query ^:allow-subquery {:union-all union-queries}- all-ids (->> (t2/query (assoc union-query- :order-by [[:sort_key sort-direction] [:entity_id sort-direction] [:entity_type sort-direction]]- :offset offset- :limit limit))- (map (fn [{:keys [entity_id entity_type]}]- [(keyword entity_type) entity_id])))+ item-params (merge (current-user-visibility nil)+ {:query-type :unreferenced+ :entity-types selected-types+ :card-types card-types+ :search-text query+ :include-personal-collections? include-personal-collections+ :sort-column sort-column+ :sort-direction sort-direction+ :offset offset+ :limit limit})+ all-ids (dependencies.db/dependency-item-ids item-params)downstream-graph (graph/cached-graph (readable-graph-dependents))- total (-> (t2/query {:select [[:%count.* :total]]- :from [[union-query :subquery]]})- first- :total)]+ total (dependencies.db/dependency-item-count item-params)]{:data (expanded-nodes downstream-graph all-ids {:include-errors? false}):limit limit:offset offset@@ -932,32 +577,25 @@;; Sandboxes don't support query filtering, so exclude them when a query is providedquery (remove #{:sandbox}))card-types (if (sequential? card-types) card-types [card-types])- union-queries (map #(dependency-items-query {:query-type :breaking- :entity-type %- :card-types card-types- :query query- :include-personal-collections include-personal-collections- :sort-column sort-column})- selected-types)- union-query ^:allow-subquery {:union-all union-queries}- all-ids (->> (t2/query (assoc union-query- :order-by [[:sort_key sort-direction] [:entity_id sort-direction] [:entity_type sort-direction]]- :offset offset- :limit limit))- (map (fn [{:keys [entity_id entity_type]}]- [(keyword entity_type) entity_id])))+ item-params (merge (current-user-visibility nil)+ {:query-type :breaking+ :entity-types selected-types+ :card-types card-types+ :search-text query+ :include-personal-collections? include-personal-collections+ :sort-column sort-column+ :sort-direction sort-direction+ :offset offset+ :limit limit})+ all-ids (dependencies.db/dependency-item-ids item-params)downstream-graph (graph/cached-graph (readable-graph-dependents))nodes-by-type (u/group-by first second all-ids)downstream-errors (node-downstream-errors nodes-by-type)- total (-> (t2/query {:select [[:%count.* :total]]- :from [[union-query :subquery]]})- first- :total)+ total (dependencies.db/dependency-item-count item-params)usages (node-usages downstream-graph all-ids)fetch-entity (fn [entity-type entity-id]- (let [model (deps.dependency-types/dependency-type->model entity-type)- fields (entity-select-fields entity-type)]- (t2/select-one (into [model] fields) :id entity-id)))+ (let [fields (entity-select-fields entity-type)]+ (dependencies.db/instance-with-columns entity-type fields entity-id)))data (into [](keep (fn [[entity-type entity-id]](when-let [entity (fetch-entity entity-type entity-id)]@@ -1019,34 +657,15 @@(not-empty (map name types))))dep-types (normalize-types dependent-types)card-types (normalize-types dependent-card-types)- where-clause (cond-> [:and- [:= :afe.source_entity_type (name entity-type)]- [:= :afe.source_entity_id id]- [:= :af.result false]- (visible-entities-filter-clause- :afe.analyzed_entity_type- :afe.analyzed_entity_id- {:include-archived-items :exclude})]- dep-types (conj [:in :afe.analyzed_entity_type dep-types])- card-types (conj [:or- [:!= :afe.analyzed_entity_type "card"]- [:in :rc.type card-types]]))- broken-entity-pairs- (t2/query (cond-> {:select-distinct [[:afe.analyzed_entity_type :entity_type]- [:afe.analyzed_entity_id :entity_id]]- :from [[:analysis_finding_error :afe]]- :join [[:analysis_finding :af]- [:and- [:= :af.analyzed_entity_type :afe.analyzed_entity_type]- [:= :af.analyzed_entity_id :afe.analyzed_entity_id]]]- :where where-clause}- card-types (assoc :left-join [[:report_card :rc]- [:and- [:= :afe.analyzed_entity_type "card"]- [:= :rc.id :afe.analyzed_entity_id]]])))+ broken-pairs (dependencies.db/broken-entity-pairs+ (merge (current-user-visibility nil)+ {:source-entity-type entity-type+ :source-entity-id id+ :dependent-types dep-types+ :dependent-card-types card-types}))nodes (map (fn [{:keys [entity_type entity_id]}][(keyword entity_type) entity_id])- broken-entity-pairs)+ broken-pairs)nodes-by-type (-> (group-by first nodes)(update-vals #(map second %)))](-> (into [] (cond-> (map (fn [[[entity-type entity-id] entity]]diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/core.clj b/enterprise/backend/src/metabase_enterprise/dependencies/core.cljindex d9db2c6969b..ce9a0411a92 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/core.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/core.clj@@ -4,6 +4,7 @@Call [[errors-from-proposed-edits]] to find out what things will break downstream of a set of new/updated entities."(:require[metabase-enterprise.dependencies.analysis :as deps.analysis]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.metadata-provider :as deps.provider][metabase-enterprise.dependencies.models.dependency :as deps.graph][metabase.lib-be.core :as lib-be]@@ -15,8 +16,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(mr/def ::entity-type[:enum :card :transform :snippet :table])@@ -86,15 +86,15 @@(defn- group-by-db [deps](let [by-db (volatile! {})](when (seq (:card deps))- (doseq [[db-id card-ids] (->> (t2/select [:model/Card :id :database_id :card_schema] :id [:in (:card deps)])+ (doseq [[db-id card-ids] (->> (dependencies.db/card-database-ids (:card deps))(u/group-by :database_id :id conj #{}))](vswap! by-db assoc-in [db-id :card] card-ids)))(when (seq (:table deps))- (doseq [[db-id table-ids] (->> (t2/select [:model/Table :id :db_id] :id [:in (:table deps)])+ (doseq [[db-id table-ids] (->> (dependencies.db/table-database-ids (:table deps))(u/group-by :db_id :id conj #{}))](vswap! by-db assoc-in [db-id :table] table-ids)))(when (seq (:transform deps))- (doseq [[db-id transform-ids] (->> (t2/select [:model/Transform :id :source] :id [:in (:transform deps)])+ (doseq [[db-id transform-ids] (->> (dependencies.db/transform-sources (:transform deps))(u/group-by #(get-in % [:source :query :database]) :id conj #{}))](if db-id(vswap! by-db assoc-in [db-id :transform] transform-ids)@@ -157,19 +157,11 @@#_(deps.provider/all-overrides mp)(check-query-soundness mp))- ;; Checking that we can properly group everything by database. Surprisingly fast even fetching everything.- (let [deps {:card (t2/select-fn-set :id :model/Card)- :transform (t2/select-fn-set :id :model/Transform)- :table (t2/select-fn-set :id :model/Table)}]- (group-by-db deps))-- (t2/select-fn-vec (juxt :id :name :active :table_id) :model/Field :id [:in [1065 1066 1067 1068 1069]])-- (t2/select-one :model/Card :id 124)+ (dependencies.db/card 124)(deps.graph/transitive-dependents {:transform [{:id 1}]})(deps.graph/transitive-dependents {:table [{:id 155}]})(metabase.premium-features.core/token-features)- (let [card (t2/select-one :model/Card :id 121)+ (let [card (dependencies.db/card 121)mp (lib-be/application-database-metadata-provider (:database_id card))](upstream-deps:card mp card)))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/db.clj b/enterprise/backend/src/metabase_enterprise/dependencies/db.cljnew file mode 100644index 00000000000..64ac847cb58--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/dependencies/db.clj@@ -0,0 +1,753 @@+(ns metabase-enterprise.dependencies.db+ "Application database queries for the dependencies module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods, and transactions."+ (:require+ [clojure.set :as set]+ [metabase-enterprise.dependencies.dependency-types :as deps.dependency-types]+ [metabase.app-db.core :as mdb]+ [metabase.collections.models.collection :as collection]+ [metabase.collections.models.collection.root :as collection.root]+ [metabase.models.interface :as mi]+ [metabase.permissions.core :as perms]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++;;; ------------------------------------------------ Graph edge restrictions ------------------------------------------------+;;; The dependency graph is traversed generically over every entity type the module knows about; these private+;;; helpers build the permission and type-allowlist fragments the graph and item-list queries below restrict edges+;;; and items by.++(defn- visible-entities-expr+ "Matches entities at `entity-type-field`/`entity-id-field` that are readable by the user described by `user-id`,+ `is-superuser?`, and `is-data-analyst?`, honoring `include-archived-items` (`:exclude`, `:all`, or `:only`,+ default `:exclude`; applies to both archived collections and archived entities).++ Handles different entity types:+ - Superuser-only (`:model/Sandbox`): only if `is-superuser?` is true+ - Collection-based (`:model/Card`, `:model/Dashboard`, `:model/Document`, `:model/NativeQuerySnippet`): filters+ by collection visibility and archived status. Native query snippets have additional restrictions for+ sandboxed users.+ - Table: filters by table visibility permissions. Tables are NOT filtered by active/visibility_type regardless+ of `include-archived-items`, so dependencies broken by dropped or hidden tables stay visible.+ - Transform: analysts can view any transform they have source view permission to."+ [entity-type-field entity-id-field {:keys [user-id is-superuser? is-data-analyst? include-archived-items]+ :or {include-archived-items :exclude}}]+ (into [:or]+ (keep (fn [[entity-type model]]+ (let [table-name (t2/table-name model)+ id-column (keyword (name table-name) "id")]+ (case model+ :model/Sandbox+ (when is-superuser?+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field ^:allow-subquery {:select [:id] :from [table-name]}]])++ :model/Transform+ (cond+ is-superuser?+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field ^:allow-subquery {:select [:id] :from [table-name]}]]++ is-data-analyst?+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field+ ^:allow-subquery+ {:select [:id]+ :from [table-name]+ :where [:in :source_database_id+ (perms/visible-database-filter-select+ {:user-id user-id+ :is-superuser? is-superuser?+ :is-data-analyst? is-data-analyst?}+ {:perms/create-queries :query-builder})]}]])++ (:model/Card :model/Dashboard :model/Document :model/NativeQuerySnippet)+ (let [archived-column (keyword (name table-name) "archived")]+ (when-not (and (= model :model/NativeQuerySnippet)+ (or (perms/sandboxed-user?)+ (not (perms/user-has-any-perms-of-type? user-id :perms/create-queries))))+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field+ ^:allow-subquery+ {:select [:id]+ :from [table-name]+ :where [:and+ (collection/visible-collection-filter-clause+ (keyword (name table-name) "collection_id")+ {:include-archived-items include-archived-items}+ {:current-user-id user-id+ :is-superuser? is-superuser?})+ (case include-archived-items+ :exclude [:= archived-column false]+ :only [:= archived-column true]+ :all nil)]}]]))++ :model/Table+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field+ ^:allow-subquery+ {:select [:id]+ :from [table-name]+ :where [:in id-column+ (perms/visible-table-filter-select+ :id+ {:user-id user-id :is-superuser? is-superuser?}+ {:perms/view-data :unrestricted :perms/create-queries :query-builder})]}]]++ (:model/Segment :model/Measure)+ (let [archived-column (keyword (name table-name) "archived")+ table-id-column (keyword (name table-name) "table_id")]+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field+ ^:allow-subquery+ {:select [:id]+ :from [table-name]+ :where [:and+ [:in table-id-column+ ^:allow-subquery+ {:select [:metabase_table.id]+ :from [:metabase_table]+ :where [:in :metabase_table.id+ (perms/visible-table-filter-select+ :id+ {:user-id user-id :is-superuser? is-superuser?}+ {:perms/view-data :unrestricted :perms/create-queries :query-builder})]}]+ (case include-archived-items+ :exclude [:= archived-column false]+ :only [:= archived-column true]+ :all nil)]}]])))))+ deps.dependency-types/dependency-type->model))++(defn- broken-entities-expr+ "Matches entities at `entity-type-field`/`entity-id-field` that have failed analysis (an AnalysisFinding with+ `:result` false)."+ [entity-type-field entity-id-field]+ (into [:or]+ (keep (fn [[entity-type _model]]+ [:and+ [:= entity-type-field (name entity-type)]+ [:in entity-id-field+ ^:allow-subquery+ {:select [:analyzed_entity_id]+ :from [:analysis_finding]+ :where [:and+ [:= :analysis_finding.analyzed_entity_type (name entity-type)]+ [:= :analysis_finding.result false]]}]]))+ deps.dependency-types/dependency-type->model))++(defn- allowed-entity-types-expr+ "Matches entities at `entity-type-field` whose type is one of `entity-types`."+ [entity-type-field entity-types]+ (into [:or] (map (fn [entity-type] [:= entity-type-field (name entity-type)])) entity-types))++(defn- entity-ids-expr+ "Matches entities at `entity-type-field`/`entity-id-field` that are of type `entity-type` and whose id is in+ `ids`."+ [entity-type-field entity-id-field {:keys [entity-type ids]}]+ [:and [:= entity-type-field (name entity-type)] [:in entity-id-field ids]])++(defn- edge-restriction-expr+ "The combined `:where` fragment for `restriction-spec` (nil for no filter), which may include `:visible` (opts for+ [[visible-entities-expr]]), `:broken?` (restrict to [[broken-entities-expr]]), `:types` (restrict to+ [[allowed-entity-types-expr]]), or `:entity-type` + `:ids` (restrict to [[entity-ids-expr]]). Combinable+ fragments are AND-ed together."+ [entity-type-field entity-id-field {:keys [visible broken? types entity-type ids]}]+ (let [fragments (cond-> []+ visible (conj (visible-entities-expr entity-type-field entity-id-field visible))+ broken? (conj (broken-entities-expr entity-type-field entity-id-field))+ types (conj (allowed-entity-types-expr entity-type-field types))+ (and entity-type ids) (conj (entity-ids-expr entity-type-field entity-id-field+ {:entity-type entity-type :ids ids})))]+ (case (count fragments)+ 0 nil+ 1 (first fragments)+ (into [:and] fragments))))++(defn dependency-edges+ "The Dependencies from the entities of type `entity-type` with `entity-ids`, where `src-type`/`src-id` name the+ Dependency columns identifying those entities and `dst-type`/`dst-id` name the columns identifying the related+ entities on the other side of the edge, optionally restricted by `destination-restriction` (applied to+ `dst-type`/`dst-id`) and `source-restriction` (applied to `src-type`/`src-id`) — see [[edge-restriction-expr]] for the+ filter spec shape."+ [{:keys [src-type src-id dst-type dst-id entity-type entity-ids destination-restriction source-restriction]}]+ (t2/select :model/Dependency+ {:where (into [:and+ [:= src-type (name entity-type)]+ [:in src-id entity-ids]]+ (keep identity)+ [(edge-restriction-expr dst-type dst-id destination-restriction)+ (edge-restriction-expr src-type src-id source-restriction)])}))++(defn finding-errors-from-sources+ "The AnalysisFindingErrors caused by any of the entities `source-entity-type` `source-entity-ids`, whose analyzed+ entity is visible to the user described by `user-id`, `is-superuser?`, and `is-data-analyst?`."+ [source-entity-type source-entity-ids {:keys [user-id is-superuser? is-data-analyst?]}]+ (t2/select :model/AnalysisFindingError+ {:where [:and+ [:= :source_entity_type (name source-entity-type)]+ [:in :source_entity_id source-entity-ids]+ (visible-entities-expr :analyzed_entity_type :analyzed_entity_id+ {:user-id user-id :is-superuser? is-superuser?+ :is-data-analyst? is-data-analyst?})]}))++(defn finding-errors-for-entities-with-visible-sources+ "The AnalysisFindingErrors analyzing any of the entities `entity-type` `entity-ids`, excluding those whose source+ entity exists but is not visible to the user described by `user-id`, `is-superuser?`, and `is-data-analyst?`."+ [entity-type entity-ids {:keys [user-id is-superuser? is-data-analyst?]}]+ (t2/select :model/AnalysisFindingError+ {:where [:and+ [:= :analyzed_entity_type (name entity-type)]+ [:in :analyzed_entity_id entity-ids]+ [:or+ [:= :source_entity_type nil]+ (visible-entities-expr :source_entity_type :source_entity_id+ {:user-id user-id :is-superuser? is-superuser?+ :is-data-analyst? is-data-analyst?})]]}))++;;; ------------------------------------------ Dependency item list queries -------------------------------------------+;;; The /graph/unreferenced and /graph/breaking endpoints union together one SELECT per entity type, each producing+;;; `entity_type`/`entity_id`/`sort_key` rows, then page and count that union. These private helpers build the+;;; per-entity-type SELECT and the pieces (joins, extra filters, sort expression) that make it up.++(defn- personal-root-collection-ids+ "The IDs of the personal Collections."+ []+ (t2/select-pks-vec :model/Collection :personal_owner_id [:not= nil] :location "/"))++(defn- entity-type-config+ "The table name and name/location column expressions to select an item list row for `entity-type`."+ [entity-type]+ (let [root-collection (collection.root/root-collection-with-ui-details+ (case entity-type+ :transform :transforms+ :snippet :snippets+ nil))]+ {:table-name (case entity-type+ :card :report_card+ :table :metabase_table+ :transform :transform+ :snippet :native_query_snippet+ :dashboard :report_dashboard+ :document :document+ :sandbox :sandboxes+ :segment :segment+ :measure :measure)+ :name-column (case entity-type+ :table :entity.display_name+ :sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]+ :entity.name)+ :location-column (case entity-type+ :card [:case+ [:not= :entity.dashboard_id nil] :dashboard.name+ [:not= :entity.document_id nil] :document.name+ :else [:coalesce :collection.name (:name root-collection)]]+ :table :database.name+ (:transform :snippet :dashboard :document) [:coalesce :collection.name (:name root-collection)]+ :sandbox [:cast :entity.id (if (= :mysql (mdb/db-type)) :char :text)]+ (:segment :measure) :table.display_name)}))++(defn- item-query-join+ "The join and join-filter for `query-type`, restricting the joined-in dependency/finding-error rows to those+ whose other-side entity passes `default-visible-restriction` (see [[edge-restriction-expr]]; this is independent of any+ archived-items override applied to the item's own visibility)."+ [query-type entity-type default-visible-restriction]+ (case query-type+ :unreferenced {:join [:dependency [:and+ [:= :dependency.to_entity_id :entity.id]+ [:= :dependency.to_entity_type (name entity-type)]+ (edge-restriction-expr :dependency.from_entity_type :dependency.from_entity_id+ default-visible-restriction)]]+ :join-filter [:= :dependency.id nil]}+ :broken {:join [:analysis_finding [:and+ [:= :analysis_finding.analyzed_entity_id :entity.id]+ [:= :analysis_finding.analyzed_entity_type (name entity-type)]]]+ :join-filter [:= :analysis_finding.result false]}+ :breaking {:join [:analysis_finding_error [:and+ [:= :analysis_finding_error.source_entity_id :entity.id]+ [:= :analysis_finding_error.source_entity_type (name entity-type)]+ (edge-restriction-expr :analysis_finding_error.analyzed_entity_type+ :analysis_finding_error.analyzed_entity_id+ default-visible-restriction)]]+ :join-filter [:!= :analysis_finding_error.id nil]}))++(defn- location-joins-for-entity+ "The set of join keywords needed for location-based operations on `entity-type`."+ [entity-type]+ (case entity-type+ :card #{:collection :dashboard :document}+ (:transform :snippet :dashboard :document) #{:collection}+ (:segment :measure) #{:table}+ :table #{:database}+ #{}))++(defn- optional-item-expr-and-joins+ "The extra `:where` fragments and joins for `params`' card-type, search-text, database, internal-content,+ archived, and personal-collection restrictions."+ [{:keys [query-type entity-type card-types search-text include-personal-collections?]}+ {:keys [name-column location-column]}]+ (let [card-type-expr (when (and (= entity-type :card) (seq card-types))+ {:expr [:in :entity.type (mapv name card-types)]+ :joins #{}})+ search-expr (when (and search-text (not= entity-type :sandbox))+ (let [pattern (h2x/like-substring search-text)]+ {:expr [:or+ [:like [:lower name-column] pattern]+ [:like [:lower location-column] pattern]]+ :joins (location-joins-for-entity entity-type)}))+ database-expr (when (= entity-type :table)+ {:expr [:and [:not :database.is_sample] [:not :database.is_audit]]+ :joins #{:database}})+ ;; Hide system-managed (internal-user) content like Usage Analytics from the unreferenced+ ;; list — analytics dashboards have nothing pointing at them by design and would just be+ ;; noise. The breaking-items list intentionally still surfaces them, since broken analytics+ ;; deps are real signals worth showing.+ internal-content-expr (when-let [model (and (= query-type :unreferenced)+ (case entity-type+ :card :model/Card+ :dashboard :model/Dashboard+ nil))]+ {:expr (mi/exclude-internal-content-hsql model :table-alias :entity)+ :joins #{}})+ ;; note that tables are not filtered by active/visibility_type, so that dependencies+ ;; broken by dropped tables stay visible+ archived-expr (when-not (= query-type :breaking)+ {:expr (case entity-type+ (:card :dashboard :document :snippet :segment :measure)+ [:= :entity.archived false]+ nil)+ :joins #{}})+ personal-expr (when-not include-personal-collections?+ (case entity-type+ (:card :dashboard :document :snippet)+ (let [personal-ids (personal-root-collection-ids)]+ (when (seq personal-ids)+ {:expr [:or+ [:= :entity.collection_id nil]+ [:and+ [:= :collection.personal_owner_id nil]+ (into [:and]+ (for [pid personal-ids]+ [:not-like :collection.location (str "/" pid "/%")]))]]+ :joins #{:collection}}))+ nil))+ results (keep identity [card-type-expr search-expr database-expr+ internal-content-expr archived-expr personal-expr])]+ {:exprs (keep :expr results)+ :joins (reduce set/union #{} (map :joins results))}))++(defn- sort-key-expr-and-joins+ "The sort expression and extra joins for `sort-column`, restricting the `dependents-errors`/`dependents-with-errors`+ counts to finding errors whose analyzed entity passes `default-visible-restriction` (see [[edge-restriction-expr]])."+ [sort-column entity-type name-column location-column default-visible-restriction]+ (case sort-column+ :location {:sort-expr location-column+ :joins (location-joins-for-entity entity-type)}+ :dependents-errors {:sort-expr ^:allow-subquery+ {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))+ [:concat :error_type "-" [:coalesce :error_detail ""]]+ [:composite :error_type :error_detail])]]]]+ :from [:analysis_finding_error]+ :where [:and+ [:= :source_entity_id :entity.id]+ [:= :source_entity_type (name entity-type)]+ (edge-restriction-expr :analyzed_entity_type :analyzed_entity_id default-visible-restriction)]}+ :joins #{}}+ :dependents-with-errors {:sort-expr ^:allow-subquery+ {:select [[[:count [:distinct (if (= :mysql (mdb/db-type))+ [:concat :analyzed_entity_id "-" :analyzed_entity_type]+ [:composite :analyzed_entity_id :analyzed_entity_type])]]]]+ :from [:analysis_finding_error]+ :where [:and+ [:= :source_entity_id :entity.id]+ [:= :source_entity_type (name entity-type)]+ (edge-restriction-expr :analyzed_entity_type :analyzed_entity_id default-visible-restriction)]}+ :joins #{}}+ {:sort-expr name-column+ :joins #{}}))++(defn- build-left-joins+ "`base-join` with the LEFT JOINs needed for `joins` (a set of `:database`, `:collection`, `:dashboard`,+ `:document`, and/or `:table`) appended."+ [base-join joins]+ (cond-> base-join+ (:database joins) (conj [:metabase_database :database] [:= :entity.db_id :database.id])+ (:collection joins) (conj :collection [:= :entity.collection_id :collection.id])+ (:dashboard joins) (conj [:report_dashboard :dashboard] [:= :entity.dashboard_id :dashboard.id])+ (:document joins) (conj :document [:= :entity.document_id :document.id])+ (:table joins) (conj [:metabase_table :table] [:= :entity.table_id :table.id])))++(defn- dependency-item-select+ "The per-entity-type SELECT that [[dependency-item-ids]] and [[dependency-item-count]] union together, matching+ `query-type` (`:unreferenced` or `:breaking`) items of `entity-type`, restricted to `card-types`, `search-text`,+ and `include-personal-collections?`, visible to the user described by `user-id`, `is-superuser?`, and+ `is-data-analyst?`, with `sort-column`'s expression selected as `:sort_key`. Throws when `user-id` is missing,+ since the visibility restriction must always be applied."+ [{:keys [query-type entity-type sort-column user-id is-superuser? is-data-analyst?] :as params}]+ (when-not user-id+ (throw (ex-info "dependency-item-select requires a user-id so the visibility restriction is always applied"+ {:query-type query-type :entity-type entity-type})))+ (let [{:keys [table-name name-column location-column] :as config} (entity-type-config entity-type)+ visible {:user-id user-id :is-superuser? is-superuser? :is-data-analyst? is-data-analyst?}+ default-visible-restriction {:visible visible}+ ;; The item's own visibility check includes archived items when listing what's breaking other entities,+ ;; so dependencies broken by an archived source still surface; nothing else is affected by this.+ item-visible-restriction (cond-> default-visible-restriction+ (= query-type :breaking) (assoc-in [:visible :include-archived-items] :all))+ {:keys [join join-filter]} (item-query-join query-type entity-type default-visible-restriction)+ {:keys [exprs joins]} (optional-item-expr-and-joins params config)+ {sort-expr :sort-expr sort-joins :joins} (sort-key-expr-and-joins sort-column entity-type name-column+ location-column default-visible-restriction)+ all-joins (set/union joins sort-joins)+ item-visible-expr (edge-restriction-expr (name entity-type) :entity.id item-visible-restriction)+ select-clause [[^:allow-raw-sql [:inline (name entity-type)] :entity_type]+ [:entity.id :entity_id]+ [sort-expr :sort_key]]]+ ^:allow-subquery+ {(if (= query-type :breaking) :select-distinct :select) select-clause+ :from [[table-name :entity]]+ :left-join (build-left-joins join all-joins)+ :where (into [:and join-filter item-visible-expr] (keep identity) exprs)}))++(defn dependency-item-ids+ "A page of `[entity-type entity-id]` pairs for `query-type` (`:unreferenced` or `:breaking`), restricted to+ `entity-types`, `card-types` (applied only to `:card` entities), `search-text` (nil for none), and+ `include-personal-collections?`; sorted by `sort-column` (`:name`, `:location`, `:dependents-errors`, or+ `:dependents-with-errors`) in `sort-direction`, skipping `offset` and returning up to `limit`. Entities are+ restricted to those visible to the user described by `user-id`, `is-superuser?`, and `is-data-analyst?`; throws+ when `user-id` is missing."+ [{:keys [entity-types sort-direction offset limit] :as params}]+ (let [union-query ^:allow-subquery {:union-all (mapv #(dependency-item-select (assoc params :entity-type %))+ entity-types)}]+ (->> (t2/query (assoc union-query+ :order-by [[:sort_key sort-direction] [:entity_id sort-direction] [:entity_type sort-direction]]+ :offset offset+ :limit limit))+ (map (fn [{:keys [entity_id entity_type]}] [(keyword entity_type) entity_id])))))++(defn dependency-item-count+ "The total count of items matching the same criteria as [[dependency-item-ids]] (ignoring sort direction, offset,+ and limit); throws when `user-id` is missing."+ [{:keys [entity-types] :as params}]+ (let [union-query ^:allow-subquery {:union-all (mapv #(dependency-item-select (assoc params :entity-type %))+ entity-types)}]+ (-> (t2/query {:select [[:%count.* :total]] :from [[union-query :subquery]]})+ first+ :total)))++(defn broken-entity-pairs+ "The `[:analyzed_entity_type :analyzed_entity_id]` pairs whose analysis failed and were caused by the entity+ `source-entity-type` `source-entity-id`, restricted to `dependent-types` and `dependent-card-types` (each nil+ for no restriction), visible to the user described by `user-id`, `is-superuser?`, and `is-data-analyst?`."+ [{:keys [source-entity-type source-entity-id dependent-types dependent-card-types+ user-id is-superuser? is-data-analyst?]}]+ (t2/query+ (cond-> {:select-distinct [[:afe.analyzed_entity_type :entity_type] [:afe.analyzed_entity_id :entity_id]]+ :from [[:analysis_finding_error :afe]]+ :join [[:analysis_finding :af]+ [:and+ [:= :af.analyzed_entity_type :afe.analyzed_entity_type]+ [:= :af.analyzed_entity_id :afe.analyzed_entity_id]]]+ :where (cond-> [:and+ [:= :afe.source_entity_type (name source-entity-type)]+ [:= :afe.source_entity_id source-entity-id]+ [:= :af.result false]+ (visible-entities-expr :afe.analyzed_entity_type :afe.analyzed_entity_id+ {:user-id user-id :is-superuser? is-superuser?+ :is-data-analyst? is-data-analyst?+ :include-archived-items :exclude})]+ dependent-types (conj [:in :afe.analyzed_entity_type dependent-types])+ dependent-card-types (conj [:or+ [:!= :afe.analyzed_entity_type "card"]+ [:in :rc.type dependent-card-types]]))}+ dependent-card-types (assoc :left-join [[:report_card :rc]+ [:and+ [:= :afe.analyzed_entity_type "card"]+ [:= :rc.id :afe.analyzed_entity_id]]]))))++;;; ---------------------------------------------------- Entities ----------------------------------------------------++(defn instances+ "The instances of the entity type `entity-type` with `ids`."+ [entity-type ids]+ (t2/select (deps.dependency-types/dependency-type->model entity-type) :id [:in ids]))++(defn instances-with-columns+ "The `columns` of the instances of the entity type `entity-type` with `ids`."+ [entity-type columns ids]+ (t2/select (into [(deps.dependency-types/dependency-type->model entity-type)] columns) :id [:in ids]))++(defn instance-with-columns+ "The `columns` of the instance of the entity type `entity-type` with `id`, or nil."+ [entity-type columns id]+ (t2/select-one (into [(deps.dependency-types/dependency-type->model entity-type)] columns) :id id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn card-types-by-id+ "A map of Card ID to type for `card-ids`."+ [card-ids]+ (t2/select-fn->fn :id :type [:model/Card :id :type :card_schema] :id [:in card-ids]))++(defn card-database-ids+ "The `:id`, `:database_id`, and `:card_schema` of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :database_id :card_schema] :id [:in card-ids]))++(defn set-card-result-metadata!+ "Set the result metadata of the Card with `card-id`."+ [card-id result-metadata]+ (t2/update! :model/Card card-id {:result_metadata result-metadata}))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn table-database-ids+ "The `:id` and `:db_id` of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :db_id] :id [:in table-ids]))++(defn table-id-by-name+ "The ID of the Table named `table-name` in `schema` of the Database with `db-id`, or nil."+ [db-id schema table-name]+ (t2/select-one-fn :id :model/Table :db_id db-id :schema schema :name table-name))++(defn transform-sources+ "The `:id` and `:source` of the Transforms with `transform-ids`."+ [transform-ids]+ (t2/select [:model/Transform :id :source] :id [:in transform-ids]))++(defn transform-ids-of-source-database+ "The IDs of the Transforms reading from the Database with `db-id`."+ [db-id]+ (t2/select-pks-set :model/Transform :source_database_id db-id))++;;; -------------------------------------------------- Dependencies --------------------------------------------------++(defn dependencies-from+ "The `:id`, `:to_entity_type`, and `:to_entity_id` of the Dependencies of the entity `entity-type` `entity-id`."+ [entity-type entity-id]+ (t2/select [:model/Dependency :id :to_entity_type :to_entity_id]+ :from_entity_type entity-type+ :from_entity_id entity-id))++(defn dependency-exists?+ "Whether the entity `from-type` `from-id` depends on the entity `to-type` `to-id`."+ [from-type from-id to-type to-id]+ (t2/exists? :model/Dependency+ :from_entity_type from-type :from_entity_id from-id+ :to_entity_type to-type :to_entity_id to-id))++(defn insert-dependencies!+ "Insert the Dependency `rows`."+ [rows]+ (t2/insert! :model/Dependency rows))++(defn retarget-dependency!+ "Point the Dependency of the entity `from-type` `from-id` on the entity `old-to-type` `old-to-id` at the entity+ `new-to-type` `new-to-id`."+ [from-type from-id old-to-type old-to-id new-to-type new-to-id]+ (t2/update! :model/Dependency+ {:from_entity_type from-type :from_entity_id from-id+ :to_entity_type old-to-type :to_entity_id old-to-id}+ {:to_entity_type new-to-type :to_entity_id new-to-id}))++(defn delete-dependencies!+ "Delete the Dependencies with `dependency-ids`."+ [dependency-ids]+ (t2/delete! :model/Dependency :id [:in dependency-ids]))++(defn delete-dependency!+ "Delete the Dependency of the entity `from-type` `from-id` on the entity `to-type` `to-id`."+ [from-type from-id to-type to-id]+ (t2/delete! :model/Dependency+ :from_entity_type from-type :from_entity_id from-id+ :to_entity_type to-type :to_entity_id to-id))++(defn delete-dependencies-from!+ "Delete the Dependencies of the entity `entity-type` `entity-id`."+ [entity-type entity-id]+ (t2/delete! :model/Dependency :from_entity_type entity-type :from_entity_id entity-id))++(defn downstream-table-ids-of-transform+ "The IDs of the Tables that depend on the Transform with `transform-id`."+ [transform-id]+ (t2/select-fn-set :from_entity_id :model/Dependency+ :from_entity_type :table+ :to_entity_type :transform+ :to_entity_id transform-id))++(defn delete-table-dependencies-on-transform!+ "Delete the Dependencies of the Tables with `table-ids` on the Transform with `transform-id`."+ [table-ids transform-id]+ (t2/delete! :model/Dependency+ :from_entity_type :table+ :from_entity_id [:in table-ids]+ :to_entity_type :transform+ :to_entity_id transform-id))++;;; ------------------------------------------------ Dependency status ------------------------------------------------++(defn dependency-status+ "The DependencyStatus of the entity `entity-type` `entity-id`, or nil."+ [entity-type entity-id]+ (t2/select-one :model/DependencyStatus :entity_type entity-type :entity_id entity-id))++(defn delete-dependency-status!+ "Delete the DependencyStatus of the entity `entity-type` `entity-id`."+ [entity-type entity-id]+ (t2/delete! :model/DependencyStatus :entity_type entity-type :entity_id entity-id))++(defn pending-retry-exists?+ "Whether a non-terminal DependencyStatus is waiting for a retry."+ []+ (t2/exists? :model/DependencyStatus :terminal false :next_retry_at [:not= nil]))++(defn instances-for-dependency-calculation+ "Up to `batch-size` instances of the entity type `entity-type` without a DependencyStatus, or whose status is+ stale or below `current-version`, is not terminal, and whose retry time has passed at `now`; stale ones first."+ [entity-type batch-size current-version now]+ (let [model (deps.dependency-types/dependency-type->model entity-type)+ table-name (t2/table-name model)+ id-field (keyword (name table-name) "id")+ table-wildcard (keyword (name table-name) "*")]+ (t2/select model+ {:select [table-wildcard]+ :from table-name+ :left-join [:dependency_status [:and+ [:= :dependency_status.entity_id id-field]+ [:= :dependency_status.entity_type (name entity-type)]]]+ :where [:or+ [:= :dependency_status.entity_id nil]+ [:and+ [:or+ [:= :dependency_status.stale true]+ [:< :dependency_status.dependency_analysis_version current-version]]+ [:= :dependency_status.terminal false]+ [:or+ [:is :dependency_status.next_retry_at nil]+ [:<= :dependency_status.next_retry_at now]]]]+ :order-by [[[:case [:= :dependency_status.stale true] [:inline 0] :else [:inline 1]]]]+ :limit batch-size})))++;;; ------------------------------------------------ Analysis findings ------------------------------------------------++(defn finding-id+ "The ID of the AnalysisFinding of the entity `entity-type` `entity-id`, or nil."+ [entity-type entity-id]+ (t2/select-one-fn :id [:model/AnalysisFinding :id]+ :analyzed_entity_type entity-type+ :analyzed_entity_id entity-id))++(defn insert-finding!+ "Insert the AnalysisFinding `row`."+ [row]+ (t2/insert! :model/AnalysisFinding row))++(defn update-finding!+ "Apply `changes` to the AnalysisFinding with `finding-id`."+ [finding-id changes]+ (t2/update! :model/AnalysisFinding finding-id changes))++(defn mark-findings-stale!+ "Mark the AnalysisFindings of the entities `entity-type` `entity-ids` as stale."+ [entity-type entity-ids]+ (t2/update! :model/AnalysisFinding+ :analyzed_entity_type entity-type+ :analyzed_entity_id [:in entity-ids]+ {:stale true}))++(defn stale-finding-exists?+ "Whether a stale AnalysisFinding exists."+ []+ (t2/exists? :model/AnalysisFinding :stale true))++(defn stale-finding-count+ "The number of stale AnalysisFindings."+ []+ (t2/count :model/AnalysisFinding :stale true))++(defn instances-for-analysis+ "Up to `batch-size` instances of the entity type `entity-type` whose AnalysisFinding is stale, missing, or below+ `current-version`; stale ones first, then the longest unanalyzed."+ [entity-type batch-size current-version]+ (let [model (deps.dependency-types/dependency-type->model entity-type)+ table-name (t2/table-name model)+ id-field (keyword (name table-name) "id")+ table-wildcard (keyword (name table-name) "*")]+ (t2/select model+ {:select [table-wildcard]+ :from table-name+ :left-join [:analysis_finding [:and+ [:= :analysis_finding.analyzed_entity_id id-field]+ [:= :analysis_finding.analyzed_entity_type (name entity-type)]]]+ :where [:or+ [:= :analysis_finding.stale true]+ [:<+ [:coalesce :analysis_finding.analysis_version 0]+ current-version]]+ :order-by [[[:case [:= :analysis_finding.stale true] [:inline 0] :else [:inline 1]]]+ [:analysis_finding.analyzed_at :asc]]+ :limit batch-size})))++(defn table-ids-with-outdated-findings+ "The IDs of the Tables of the Database with `db-id` whose dependents were analyzed before the Table or one of+ its Fields last changed."+ [db-id]+ (t2/select-fn-set :table_id :model/AnalysisFinding+ {:select [:field_updates/table_id]+ :from [[^:allow-subquery {:select [[:table/id :table_id]+ [:table/updated_at :last_table_update]+ [[:max :field/updated_at] :last_field_update]]+ :from [[(t2/table-name :model/Table) :table]]+ :left-join [[(t2/table-name :model/Field) :field]+ [:= :field/table_id :table/id]]+ :where [:= :table/db_id db-id]+ :group-by [:table/id+ :table/updated_at]}+ :field_updates]]+ :inner-join [[(t2/table-name :model/Dependency) :dep]+ [:and+ [:= :dep/to_entity_type "table"]+ [:= :field_updates/table_id :dep/to_entity_id]]+ [(t2/table-name :model/AnalysisFinding) :finding]+ [:and+ [:= :finding/analyzed_entity_type :dep/from_entity_type]+ [:= :finding/analyzed_entity_id :dep/from_entity_id]]]+ :where [:and+ [:!= :finding/analyzed_entity_id nil]+ [:or+ [:< :finding/analyzed_at :field_updates/last_table_update]+ [:< :finding/analyzed_at :field_updates/last_field_update]]]}))++;;; --------------------------------------------- Analysis finding errors ---------------------------------------------++(defn finding-errors-for-entity+ "The AnalysisFindingErrors of the entity `entity-type` `entity-id`."+ [entity-type entity-id]+ (t2/select :model/AnalysisFindingError :analyzed_entity_type entity-type :analyzed_entity_id entity-id))++(defn finding-errors-from-source+ "The AnalysisFindingErrors caused by the entity `source-type` `source-id`."+ [source-type source-id]+ (t2/select :model/AnalysisFindingError :source_entity_type source-type :source_entity_id source-id))++(defn insert-finding-errors!+ "Insert the AnalysisFindingError `rows`."+ [rows]+ (t2/insert! :model/AnalysisFindingError rows))++(defn delete-finding-errors-for-entity!+ "Delete the AnalysisFindingErrors of the entity `entity-type` `entity-id`."+ [entity-type entity-id]+ (t2/delete! :model/AnalysisFindingError :analyzed_entity_type entity-type :analyzed_entity_id entity-id))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj b/enterprise/backend/src/metabase_enterprise/dependencies/events.cljindex 9e0b1018623..d56f4e4a0fd 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.dependencies.events(:require+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.findings :as deps.findings][metabase-enterprise.dependencies.models.analysis-finding :as deps.analysis-finding][metabase-enterprise.dependencies.models.dependency :as models.dependency]@@ -9,8 +10,7 @@[metabase.events.core :as events][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]));; ## Maintaining the dependency graph;; The below listens for inserts, updates and deletes of cards, snippets and transforms in order to keep the@@ -45,8 +45,8 @@(methodical/defmethod events/publish-event! ::card-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :card :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :card :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :card (:id object))+ (dependencies.db/delete-dependency-status! :card (:id object))));; ### Snippets(events/derive! ::snippet-deps :metabase/event)@@ -64,8 +64,8 @@(methodical/defmethod events/publish-event! ::snippet-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :snippet :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :snippet :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :snippet (:id object))+ (dependencies.db/delete-dependency-status! :snippet (:id object))));; ### Transforms(events/derive! ::transform-deps :metabase/event)@@ -84,8 +84,8 @@[_ {:keys [id]}];; TODO: (Braden 09/18/2025) Shouldn't we be deleting the downstream deps for dead edges as well as upstream?(when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :transform :from_entity_id id)- (t2/delete! :model/DependencyStatus :entity_type :transform :entity_id id)))+ (dependencies.db/delete-dependencies-from! :transform id)+ (dependencies.db/delete-dependency-status! :transform id)));; On *executing* a transform, its (freshly synced) output table is made to depend on the transform.;; (And if the target has changed, the old table's dep on the transform is dropped.)@@ -96,7 +96,7 @@(defn- transform-table-deps! [{:keys [db-id output-schema output-table transform-id] :as _details}](let [;; output-table is a keyword like :my_schema/my_tabletable-name (name output-table)]- (when-let [table-id (t2/select-one-fn :id :model/Table :db_id db-id :schema output-schema :name table-name)]+ (when-let [table-id (dependencies.db/table-id-by-name db-id output-schema table-name)](models.dependency/replace-dependencies! :table table-id {:transform #{transform-id}}))))(methodical/defmethod events/publish-event! ::transform-run@@ -120,8 +120,8 @@(methodical/defmethod events/publish-event! ::dashboard-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :dashboard :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :dashboard :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :dashboard (:id object))+ (dependencies.db/delete-dependency-status! :dashboard (:id object))));; ### Documents(events/derive! ::document-deps :metabase/event)@@ -139,8 +139,8 @@(methodical/defmethod events/publish-event! ::document-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :document :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :document :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :document (:id object))+ (dependencies.db/delete-dependency-status! :document (:id object))));; ### Sandboxes(events/derive! ::sandbox-deps :metabase/event)@@ -158,8 +158,8 @@(methodical/defmethod events/publish-event! ::sandbox-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :sandbox :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :sandbox :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :sandbox (:id object))+ (dependencies.db/delete-dependency-status! :sandbox (:id object))));; ### Segments(events/derive! ::segment-deps :metabase/event)@@ -177,8 +177,8 @@(methodical/defmethod events/publish-event! ::segment-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :segment :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :segment :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :segment (:id object))+ (dependencies.db/delete-dependency-status! :segment (:id object))));; ### Measures(events/derive! ::measure-deps :metabase/event)@@ -196,8 +196,8 @@(methodical/defmethod events/publish-event! ::measure-delete[_ {:keys [object]}](when (premium-features/has-feature? :dependencies)- (t2/delete! :model/Dependency :from_entity_type :measure :from_entity_id (:id object))- (t2/delete! :model/DependencyStatus :entity_type :measure :entity_id (:id object))))+ (dependencies.db/delete-dependencies-from! :measure (:id object))+ (dependencies.db/delete-dependency-status! :measure (:id object))));; ## Checking dependents for breakage (analysis_finding staleness);;@@ -285,31 +285,7 @@Returns the set of table IDs which have dependents that need re-analysis, possibly empty."[db-id]- (t2/select-fn-set :table_id :model/AnalysisFinding- {:select [:field_updates/table_id]- :from [[^:allow-subquery {:select [[:table/id :table_id]- [:table/updated_at :last_table_update]- [[:max :field/updated_at] :last_field_update]]- :from [[(t2/table-name :model/Table) :table]]- :left-join [[(t2/table-name :model/Field) :field]- [:= :field/table_id :table/id]]- :where [:= :table/db_id db-id]- :group-by [:table/id- :table/updated_at]}- :field_updates]]- :inner-join [[(t2/table-name :model/Dependency) :dep]- [:and- [:= :dep/to_entity_type "table"]- [:= :field_updates/table_id :dep/to_entity_id]]- [(t2/table-name :model/AnalysisFinding) :finding]- [:and- [:= :finding/analyzed_entity_type :dep/from_entity_type]- [:= :finding/analyzed_entity_id :dep/from_entity_id]]]- :where [:and- [:!= :finding/analyzed_entity_id nil]- [:or- [:< :finding/analyzed_at :field_updates/last_table_update]- [:< :finding/analyzed_at :field_updates/last_field_update]]]}))+ (dependencies.db/table-ids-with-outdated-findings db-id))(events/derive! ::sync-completed-on-database :metabase/event)(events/derive! :event/sync-end ::sync-completed-on-database)@@ -351,7 +327,7 @@for dependency re-analysis. See the OSS declaration in `metabase.warehouses.models.database`.":feature :dependencies[db-id]- (when-let [transform-ids (not-empty (t2/select-pks-set :model/Transform :source_database_id db-id))]+ (when-let [transform-ids (not-empty (dependencies.db/transform-ids-of-source-database db-id))](deps.analysis-finding/mark-stale! :transform transform-ids)(deps.findings/mark-transitive-dependents-stale! {:transform transform-ids})(task.entity-check/trigger-entity-check-job!)))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.cljindex 0f8163e91e4..f83d9f0cc5f 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/metadata_update.clj@@ -3,6 +3,7 @@[clojure.core.cache :as cache][medley.core :as m][metabase-enterprise.dependencies.async :as async]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.dependency-types :as deps.dependency-types][metabase-enterprise.dependencies.metadata-provider :as deps.metadata-provider][metabase-enterprise.dependencies.models.dependency :as models.dependency]@@ -18,8 +19,7 @@[metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(defn- mbql-graph"Returns a graph that is limited to sandboxes, segments, measures, and mbql cards.@@ -27,14 +27,7 @@All other types of nodes are ignored and are neither included in the graph or traversed to find transitivedependents."[mp]- (-> (models.dependency/filtered-graph-dependents- nil- (fn [type-field _id-field]- [:or- [:= type-field "card"]- [:= type-field "sandbox"]- [:= type-field "segment"]- [:= type-field "measure"]]))+ (-> (models.dependency/filtered-graph-dependents nil {:types #{:card :sandbox :segment :measure}})(graph/filtered-graph (fn [[type id]](not (and (= type :card)(->> (lib.metadata/card mp id)@@ -188,7 +181,7 @@::graph/stop[node-id new-metadata]))))))](doseq [[card-id new-metadata] updates]- (t2/update! :model/Card card-id {:result_metadata new-metadata}))))+ (dependencies.db/set-card-result-metadata! card-id new-metadata))))(events/derive! ::update-card-dependents-metadata :metabase/event)(events/derive! :event/card-update ::update-card-dependents-metadata)diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding.cljindex ee9241bdb5a..7211b1dd3fa 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding.clj@@ -1,6 +1,6 @@(ns metabase-enterprise.dependencies.models.analysis-finding(:require- [metabase-enterprise.dependencies.dependency-types :as deps.dependency-types]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.models.analysis-finding-error :as deps.analysis-finding-error][metabase.models.interface :as mi][metabase.util :as u]@@ -49,15 +49,12 @@:analysis_version *current-analysis-finding-version*:result result:stale false}- existing-id (t2/select-one-fn :id [:model/AnalysisFinding :id]- :analyzed_entity_type type- :analyzed_entity_id instance-id)]+ existing-id (dependencies.db/finding-id type instance-id)](if existing-id- (t2/update! :model/AnalysisFinding existing-id update)- (t2/insert! :model/AnalysisFinding- (assoc update- :analyzed_entity_type type- :analyzed_entity_id instance-id)))+ (dependencies.db/update-finding! existing-id update)+ (dependencies.db/insert-finding! (assoc update+ :analyzed_entity_type type+ :analyzed_entity_id instance-id)))(deps.analysis-finding-error/replace-errors-for-entity!typeinstance-id@@ -72,44 +69,22 @@Entities without existing findings are ignored - they'll be picked up by the normal job flow."[entity-type entity-ids](doseq [batch (partition-all mark-stale-batch-size entity-ids)]- (t2/update! :model/AnalysisFinding- :analyzed_entity_type entity-type- :analyzed_entity_id [:in batch]- {:stale true})))+ (dependencies.db/mark-findings-stale! entity-type batch)))(defn has-stale-entities?"Check if there are any stale analysis records."[]- (t2/exists? :model/AnalysisFinding :stale true))+ (dependencies.db/stale-finding-exists?))(defn stale-entity-count"Number of analysis findings currently marked stale, across all entity types. Used by the entity-check drain loop todetect whether it is still making progress."[]- (t2/count :model/AnalysisFinding :stale true))+ (dependencies.db/stale-finding-count))(defn instances-for-analysis"Find a batch of instances of type `entity-type` and maximum size `batch-size` with missing, outdated,or stale AnalysisFindings.Prioritizes stale entities (stale=true) over outdated version entities."[entity-type batch-size]- (let [model (deps.dependency-types/dependency-type->model entity-type)- table-name (t2/table-name model)- id-field (keyword (name table-name) "id")- table-wildcard (keyword (name table-name) "*")]- (t2/select model- {:select [table-wildcard]- :from table-name- :left-join [:analysis_finding [:and- [:= :analysis_finding.analyzed_entity_id id-field]- [:= :analysis_finding.analyzed_entity_type (name entity-type)]]]- :where [:or- [:= :analysis_finding.stale true] ; stale analysis- [:< ; missing or outdated analysis- [:coalesce :analysis_finding.analysis_version 0]- *current-analysis-finding-version*]]- ;; stale first, then oldest-analyzed first so a sub-backlog batch round-robins through- ;; the stale set instead of starving a DB-arbitrary subset.- :order-by [[[:case [:= :analysis_finding.stale true] [:inline 0] :else [:inline 1]]]- [:analysis_finding.analyzed_at :asc]]- :limit batch-size})))+ (dependencies.db/instances-for-analysis entity-type batch-size *current-analysis-finding-version*))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding_error.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding_error.cljindex 8ba45839374..cf097f37590 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding_error.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/analysis_finding_error.clj@@ -3,6 +3,7 @@with source entity information. This enables querying errors by the data source thatcauses them (e.g., which cards are broken because table X removed column Y?)."(:require+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.dependency-types :as deps.dependency-types][metabase.lib.schema.validate :as lib.schema.validate][metabase.models.interface :as mi]@@ -51,32 +52,26 @@entity-id :- ms/PositiveInterrors :- [:sequential ::error-input]](t2/with-transaction [_conn]- (t2/delete! :model/AnalysisFindingError- :analyzed_entity_type entity-type- :analyzed_entity_id entity-id)+ (dependencies.db/delete-finding-errors-for-entity! entity-type entity-id)(when (seq errors)- (t2/insert! :model/AnalysisFindingError- (mapv (fn [{:keys [error-type error-detail source-entity-type source-entity-id]}]- {:analyzed_entity_type (name entity-type)- :analyzed_entity_id entity-id- :error_type error-type- :error_detail error-detail- :source_entity_type (some-> source-entity-type name)- :source_entity_id source-entity-id})- errors)))))+ (dependencies.db/insert-finding-errors!+ (mapv (fn [{:keys [error-type error-detail source-entity-type source-entity-id]}]+ {:analyzed_entity_type (name entity-type)+ :analyzed_entity_id entity-id+ :error_type error-type+ :error_detail error-detail+ :source_entity_type (some-> source-entity-type name)+ :source_entity_id source-entity-id})+ errors)))))(mu/defn errors-by-source :- [:sequential ::analysis-finding-error]"Get all errors caused by a specific source entity."[source-entity-type :- [:maybe ::lib.schema.validate/source-entity-type]source-entity-id :- ms/PositiveInt]- (t2/select :model/AnalysisFindingError- :source_entity_type source-entity-type- :source_entity_id source-entity-id))+ (dependencies.db/finding-errors-from-source source-entity-type source-entity-id))(mu/defn errors-for-entity :- [:sequential ::analysis-finding-error]"Get all errors for a specific analyzed entity."[entity-type :- ::deps.dependency-types/dependency-typesentity-id :- ms/PositiveInt]- (t2/select :model/AnalysisFindingError- :analyzed_entity_type entity-type- :analyzed_entity_id entity-id))+ (dependencies.db/finding-errors-for-entity entity-type entity-id))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.cljindex 79048bdc654..8b228b4068f 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.dependencies.models.dependency(:require[clojure.set :as set]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.dependency-types :as deps.dependency-types][metabase.graph.core :as graph][metabase.lib.core :as lib]@@ -25,30 +26,26 @@:to_entity_type mi/transform-keyword})(defn- deps-children- "Get dependency children with optional database-level filtering.+ "Get dependency children with optional visibility filtering.Returns a map from [src-type src-id] tuples to sets of [dst-type dst-id] tuples representing dependencies.- When `destination-filter-fn` is provided, it should be a function accepting two arguments- (entity-type-field, entity-id-field) and returning a HoneySQL WHERE clause for filtering destination entities.-- When `source-filter-fn` is provided, it should be a function accepting two arguments- (entity-type-field, entity-id-field) and returning a HoneySQL WHERE clause for filtering destination entities."- ([{:keys [src-type src-id dst-type dst-id key-seq destination-filter-fn source-filter-fn]}]- (let [base-filter (cond-> [:and]- destination-filter-fn (conj (destination-filter-fn dst-type dst-id))- source-filter-fn (conj (source-filter-fn src-type src-id)))]- (transduce (map (fn [[entity-type entity-keys]]- (let [full-filter (conj base-filter- [:= src-type (name entity-type)]- [:in src-id entity-keys])- deps (t2/select :model/Dependency {:where full-filter})]- (u/group-by (juxt src-type src-id)- (juxt dst-type dst-id)- conj #{}- deps))))- merge {}- (u/group-by first second key-seq)))))+ `destination-filter` and `source-filter` are filter specs (see `metabase-enterprise.dependencies.db`'s+ `edge-restriction-expr`: nil, `{:visible {...}}`, `{:broken? true}`, `{:types #{...}}`, or+ `{:entity-type ... :ids #{...}}`) restricting the destination (child) and source (parent) side of each edge,+ respectively."+ ([{:keys [src-type src-id dst-type dst-id key-seq destination-filter source-filter]}]+ (transduce (map (fn [[entity-type entity-keys]]+ (let [deps (dependencies.db/dependency-edges+ {:src-type src-type :src-id src-id :dst-type dst-type :dst-id dst-id+ :entity-type entity-type :entity-ids entity-keys+ :destination-restriction destination-filter :source-restriction source-filter})]+ (u/group-by (juxt src-type src-id)+ (juxt dst-type dst-id)+ conj #{}+ deps))))+ merge {}+ (u/group-by first second key-seq))))(defn- key-dependents"Get the dependent entity keys for the entity keys in `key-seq`.@@ -56,24 +53,19 @@Entity keys are [entity-type entity-id] tuples. Returns a map from source entity keysto sets of dependent (downstream) entity keys.- When `destination-filter-fn` is provided, it should be a function accepting two arguments- (entity-type-field, entity-id-field) and returning a HoneySQL WHERE clause for filtering- the child side of a dependency.-- When `source-filter-fn` is provided, it should be a function accepting two arguments- (entity-type-field, entity-id-field) and returning a HoneySQL WHERE clause for filtering- the child side of a dependency."+ `destination-filter` and `source-filter` are filter specs restricting the dependent (child) and queried (parent)+ side of each edge, respectively — see [[deps-children]]."([key-seq](key-dependents key-seq nil nil))- ([key-seq destination-filter-fn source-filter-fn]+ ([key-seq destination-filter source-filter](deps-children- {:src-type :to_entity_type- :src-id :to_entity_id- :dst-type :from_entity_type- :dst-id :from_entity_id- :key-seq key-seq- :destination-filter-fn destination-filter-fn- :source-filter-fn source-filter-fn})))+ {:src-type :to_entity_type+ :src-id :to_entity_id+ :dst-type :from_entity_type+ :dst-id :from_entity_id+ :key-seq key-seq+ :destination-filter destination-filter+ :source-filter source-filter})))(defn direct-dependents"Returns the direct dependents for the given entity key sequence."@@ -86,24 +78,19 @@Entity keys are [entity-type entity-id] tuples. Returns a map from source entity keysto sets of dependency (upstream) entity keys.- When `destination-filter-fn` is provided, it should be a function accepting two arguments- (entity-type-field, entity-id-field) and returning a HoneySQL WHERE clause for filtering- the child side of a dependency.-- When `source-filter-fn` is provided, it should be a function accepting two arguments- (entity-type-field, entity-id-field) and returning a HoneySQL WHERE clause for filtering- the child side of a dependency."+ `destination-filter` and `source-filter` are filter specs restricting the dependency (child) and queried (parent)+ side of each edge, respectively — see [[deps-children]]."([key-seq](key-dependencies key-seq nil nil))- ([key-seq destination-filter-fn source-filter-fn]+ ([key-seq destination-filter source-filter](deps-children- {:src-type :from_entity_type- :src-id :from_entity_id- :dst-type :to_entity_type- :dst-id :to_entity_id- :key-seq key-seq- :destination-filter-fn destination-filter-fn- :source-filter-fn source-filter-fn})))+ {:src-type :from_entity_type+ :src-id :from_entity_id+ :dst-type :to_entity_type+ :dst-id :to_entity_id+ :key-seq key-seq+ :destination-filter destination-filter+ :source-filter source-filter})))(p/deftype+ DependencyGraph [children-fn]graph/Graph@@ -121,45 +108,38 @@(->DependencyGraph key-dependencies))(defn- filtered-graph- "Create a dependency graph with database-level filtering.+ "Create a dependency graph with visibility filtering.Arguments:- `key-fn`: Either key-dependencies or key-dependents, determining graph direction- - `destination-filter-fn`: Function accepting (entity-type-field, entity-id-field)- and returning a HoneySQL WHERE clause that will filter the child side of a dependency- - `source-filter-fn`: Function accepting (entity-type-field, entity-id-field) and- returning a HoneySQL WHERE clause that will filter the parent side of a dependency"-- [key-fn destination-filter-fn source-filter-fn]+ - `destination-filter`: Filter spec restricting the child side of a dependency — see [[deps-children]]+ - `source-filter`: Filter spec restricting the parent side of a dependency"+ [key-fn destination-filter source-filter](->DependencyGraph(fn [key-seq]- (key-fn key-seq destination-filter-fn source-filter-fn))))+ (key-fn key-seq destination-filter source-filter))))(defn filtered-graph-dependencies"Create a permission-aware dependency graph for finding upstream dependencies.Arguments:- - `destination-filter-fn`: Function accepting (entity-type-field, entity-id-field)- and returning a HoneySQL WHERE clause for filtering destination entities- - `source-filter-fn`: Optional function accepting (entity-type-field, entity-id-field)- and returning a HoneySQL WHERE clause that will filter the parent side of a dependency"- ([destination-filter-fn]- (filtered-graph-dependencies destination-filter-fn nil))- ([destination-filter-fn source-filter-fn]- (filtered-graph key-dependencies destination-filter-fn source-filter-fn)))+ - `destination-filter`: Filter spec restricting destination entities — see [[deps-children]]+ - `source-filter`: Optional filter spec restricting the parent side of a dependency"+ ([destination-filter]+ (filtered-graph-dependencies destination-filter nil))+ ([destination-filter source-filter]+ (filtered-graph key-dependencies destination-filter source-filter)))(defn filtered-graph-dependents"Create a permission-aware dependency graph for finding downstream dependents.Arguments:- - `destination-filter-fn`: Function accepting (entity-type-field, entity-id-field)- and returning a HoneySQL WHERE clause for filtering destination entities- - `source-filter-fn`: Optional function accepting (entity-type-field, entity-id-field)- and returning a HoneySQL WHERE clause that will filter the parent side of a dependency"- ([destination-filter-fn]- (filtered-graph-dependents destination-filter-fn nil))- ([destination-filter-fn source-filter-fn]- (filtered-graph key-dependents destination-filter-fn source-filter-fn)))+ - `destination-filter`: Filter spec restricting destination entities — see [[deps-children]]+ - `source-filter`: Optional filter spec restricting the parent side of a dependency"+ ([destination-filter]+ (filtered-graph-dependents destination-filter nil))+ ([destination-filter source-filter]+ (filtered-graph key-dependents destination-filter source-filter)))(defn entities->nodes"Converts a map of entities `{entity-type [{:id 1, ...} ...]}` or entity IDs `{entity-type [1]}` into a list of nodes@@ -216,11 +196,10 @@group-nodes)](into {}(mapcat (fn [[node-type ids]]- (let [model (deps.dependency-types/dependency-type->model node-type)]- (t2/select-fn-vec (fn [entity]- [[node-type (:id entity)]- (is-native-entity? node-type entity)])- model :id [:in ids]))))+ (mapv (fn [entity]+ [[node-type (:id entity)]+ (is-native-entity? node-type entity)])+ (dependencies.db/instances node-type ids))))grouped)))(defn transitive-mbql-dependents@@ -255,9 +234,7 @@"Replace the dependencies of the entity of type `entity-type` with id `entity-id` withthe ones specified in `dependencies-by-type`. "[entity-type entity-id dependencies-by-type]- (let [current-dependencies (t2/select [:model/Dependency :id :to_entity_type :to_entity_id]- :from_entity_type entity-type- :from_entity_id entity-id)+ (let [current-dependencies (dependencies.db/dependencies-from entity-type entity-id)to-remove (keep (fn [{:keys [id to_entity_type to_entity_id]}](when-not (get-in dependencies-by-type [to_entity_type to_entity_id])id))@@ -272,9 +249,9 @@:to_entity_id (ensure-entity-id to-entity-id)})](t2/with-transaction [_conn](when (seq to-remove)- (t2/delete! :model/Dependency :id [:in to-remove]))+ (dependencies.db/delete-dependencies! to-remove))(when (seq to-add)- (t2/insert! :model/Dependency to-add)))))+ (dependencies.db/insert-dependencies! to-add)))))(defn swap-dependency!"Efficiently swap a dependency from old-source to new-source during replacement operations.@@ -289,14 +266,9 @@- old-source: The source being replaced, as [source-type source-id] (e.g., [:card 783])- new-source: The new source, as [source-type source-id] (e.g., [:table 164])"[entity-type entity-id [old-source-type old-source-id] [new-source-type new-source-id]]- (let [already-present? (t2/exists? :model/Dependency- :from_entity_type entity-type :from_entity_id entity-id- :to_entity_type new-source-type :to_entity_id new-source-id)]+ (let [already-present? (dependencies.db/dependency-exists? entity-type entity-id new-source-type new-source-id)](if already-present?- (t2/delete! :model/Dependency- :from_entity_type entity-type :from_entity_id entity-id- :to_entity_type old-source-type :to_entity_id old-source-id)- (t2/update! :model/Dependency- {:from_entity_type entity-type :from_entity_id entity-id- :to_entity_type old-source-type :to_entity_id old-source-id}- {:to_entity_type new-source-type :to_entity_id new-source-id}))))+ (dependencies.db/delete-dependency! entity-type entity-id old-source-type old-source-id)+ (dependencies.db/retarget-dependency! entity-type entity-id+ old-source-type old-source-id+ new-source-type new-source-id))))diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.cljindex b2848ea4fb5..8f28846bfda 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.dependencies.models.dependency-status(:require[java-time.api :as t]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.dependency-types :as deps.dependency-types][metabase-enterprise.dependencies.models.dependency :as models.dependency][metabase.app-db.core :as app-db]@@ -61,41 +62,15 @@Returns full entity objects. Prioritizes stale over outdated.Uses Java time (not DB time) so tests with [[mt/with-clock]] work correctly."[entity-type batch-size]- (let [model (deps.dependency-types/dependency-type->model entity-type)- table-name (t2/table-name model)- id-field (keyword (name table-name) "id")- table-wildcard (keyword (name table-name) "*")- now (t/offset-date-time)]- (t2/select model- {:select [table-wildcard]- :from table-name- :left-join [:dependency_status [:and- [:= :dependency_status.entity_id id-field]- [:= :dependency_status.entity_type (name entity-type)]]]- :where [:or- ;; No status row yet — needs initial processing.- [:= :dependency_status.entity_id nil]- [:and- ;; Needs processing: stale or version outdated- [:or- [:= :dependency_status.stale true]- [:< :dependency_status.dependency_analysis_version- models.dependency/current-dependency-analysis-version]]- ;; Not terminally broken- [:= :dependency_status.terminal false]- ;; Retry delay has elapsed (or no delay set)- [:or- [:is :dependency_status.next_retry_at nil]- [:<= :dependency_status.next_retry_at now]]]]- :order-by [[[:case [:= :dependency_status.stale true] [:inline 0] :else [:inline 1]]]]- :limit batch-size})))+ (dependencies.db/instances-for-dependency-calculation entity-type+ batch-size+ models.dependency/current-dependency-analysis-version+ (t/offset-date-time)))(defn has-pending-retries?"Returns true if there are any entities waiting to be retried (not terminal, with a set retry time)."[]- (t2/exists? :model/DependencyStatus- :terminal false- :next_retry_at [:not= nil]))+ (dependencies.db/pending-retry-exists?))(defn has-stale-or-outdated?"Returns true if there are any entities needing dependency calculation: no status row yet,diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj b/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.cljindex 60838ba00bf..38413b7234b 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj@@ -12,6 +12,7 @@[clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t][metabase-enterprise.dependencies.calculation :as deps.calculation]+ [metabase-enterprise.dependencies.db :as dependencies.db][metabase-enterprise.dependencies.dependency-types :as deps.dependency-types][metabase-enterprise.dependencies.models.dependency :as models.dependency][metabase-enterprise.dependencies.models.dependency-status :as deps.dependency-status]@@ -51,12 +52,9 @@(defmethod post-deps-cleanup! :transform [_ {:keys [id target] :as transform}](let [db-id (transforms/transform-source-database transform)- downstream-table-ids (t2/select-fn-set :from_entity_id :model/Dependency- :from_entity_type :table- :to_entity_type :transform- :to_entity_id id)+ downstream-table-ids (dependencies.db/downstream-table-ids-of-transform id)downstream-tables (when (seq downstream-table-ids)- (t2/select :model/Table :id [:in downstream-table-ids]))+ (dependencies.db/tables downstream-table-ids))outdated-tables (remove (fn [table](and (= (:schema table) (:schema target))(= (:name table) (:name target))@@ -67,11 +65,7 @@downstream-table-ids)](when-let [outdated-downstream-table-ids (seq (into (set not-found-table-ids)(map :id) outdated-tables))]- (t2/delete! :model/Dependency- :from_entity_type :table- :from_entity_id [:in outdated-downstream-table-ids]- :to_entity_type :transform- :to_entity_id id))))+ (dependencies.db/delete-table-dependencies-on-transform! outdated-downstream-table-ids id))));;; ------------------------------ Backfill orchestration ------------------------------@@ -109,9 +103,7 @@(deps.dependency-status/record-failure!entity-type id max-retries(deps.settings/dependency-backfill-delay-minutes))- (let [{:keys [fail_count terminal]} (t2/select-one :model/DependencyStatus- :entity_type entity-type- :entity_id id)]+ (let [{:keys [fail_count terminal]} (dependencies.db/dependency-status entity-type id)](if terminal(log/errorf "Entity %s %s failed %d times, marking as terminally broken: %s"type-name id fail_count (ex-message e))diff --git a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.cljindex 6ecdcecd6ac..ec9411854f6 100644--- a/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj+++ b/enterprise/backend/src/metabase_enterprise/embedding_hub/api.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.embedding-hub.api(:require+ [metabase-enterprise.embedding-hub.db :as embedding-hub.db][metabase-enterprise.sso.settings :as sso-settings][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -7,70 +8,41 @@[metabase.audit-app.core :as audit][metabase.embedding.settings :as embedding.settings][metabase.permissions.core :as perms]- [metabase.premium-features.core :as premium-features]- [toucan2.core :as t2]))+ [metabase.premium-features.core :as premium-features]))(defn- has-user-added-database? []- (or (t2/exists? :model/Database {:where [:and- [:= :is_sample false]- [:= :is_audit false]]})+ (or (embedding-hub.db/user-database-exists?);; check for CSV uploads to sample db;; as the sample db is excluded from the above query- (when-let [sample-db-id (t2/select-one-pk :model/Database :is_sample true)]- (t2/exists? :model/Table {:where [:and- [:= :active true]- [:= :is_upload true]- [:= :db_id sample-db-id]]}))))+ (when-let [sample-db-id (embedding-hub.db/sample-database-id)]+ (embedding-hub.db/upload-table-exists-in-database? sample-db-id))))(defn- has-user-created-dashboard? [](let [example-dashboard-id (appearance/example-dashboard-id)audit-collection-ids (filter some? [(when-let [audit-coll (audit/default-audit-collection)] (:id audit-coll))(when-let [custom-coll (audit/default-custom-reports-collection)] (:id custom-coll))])]- (t2/exists? :model/Dashboard {:where (cond-> [:and- [:= :archived false]]- example-dashboard-id (conj [:not= :id example-dashboard-id])- (seq audit-collection-ids) (conj [:or- [:is :collection_id nil]- [:not-in :collection_id audit-collection-ids]]))})))+ (embedding-hub.db/user-dashboard-exists? example-dashboard-id audit-collection-ids)))(defn- has-configured-sandboxes? [](and (premium-features/has-feature? :sandboxes)- (t2/exists? :model/Sandbox)))+ (embedding-hub.db/sandbox-exists?)))(defn- has-configured-sso? [](or (and (premium-features/has-feature? :sso-jwt) (sso-settings/jwt-enabled-and-configured))(and (premium-features/has-feature? :sso-saml) (sso-settings/saml-enabled) (sso-settings/saml-configured))))(defn- has-user-created-models? []- (t2/exists? :model/Card {:where [:and- [:= :type "model"]- [:= :archived false]- [:or- [:and- [:!= :collection_id (:id (audit/default-audit-collection))]- [:not [:exists ^:allow-subquery- {:select [1]- :from [[(t2/table-name :model/Collection) :sample_coll]]- :where [:and- [:= :sample_coll.is_sample true]- [:= :sample_coll.id :report_card.collection_id]]}]]]- [:is :collection_id nil]]]}))+ (embedding-hub.db/user-model-exists? (:id (audit/default-audit-collection))))(defn- has-user-created-tenants? []- (t2/exists? :model/Tenant :is_active true))+ (embedding-hub.db/active-tenant-exists?))(defn- has-shared-tenant-collections? []- (t2/exists? :model/Collection {:where [:and- [:= :namespace "shared-tenant-collection"]- [:= :archived false]]}))+ (embedding-hub.db/shared-tenant-collection-exists?))(defn- shared-collection-has-dashboards? []- (when-let [shared-coll-id (t2/select-one-pk :model/Collection {:where [:and- [:= :namespace "shared-tenant-collection"]- [:= :archived false]]})]- (t2/exists? :model/Dashboard {:where [:and- [:= :collection_id shared-coll-id]- [:= :archived false]]})))+ (when-let [shared-coll-id (embedding-hub.db/shared-tenant-collection-id)]+ (embedding-hub.db/unarchived-dashboard-exists-in-collection? shared-coll-id)))(defn- has-configured-data-segregation-strategy? [];; Check if any of the 3 data segregation strategies are enabled:@@ -78,20 +50,20 @@;; 2. Connection Impersonation;; 3. Database Routing(or (has-configured-sandboxes?)- (t2/exists? :model/ConnectionImpersonation)- (t2/exists? :model/DatabaseRouter)))+ (embedding-hub.db/impersonation-exists?)+ (embedding-hub.db/database-router-exists?)))(defn- active-data-segregation-strategy [](cond(has-configured-sandboxes?) "row-column-level-security"- (t2/exists? :model/ConnectionImpersonation) "connection-impersonation"- (t2/exists? :model/DatabaseRouter) "database-routing"+ (embedding-hub.db/impersonation-exists?) "connection-impersonation"+ (embedding-hub.db/database-router-exists?) "database-routing":else nil))(defn- has-published-guest-embed? [];; Check if at least one card or dashboard has embedding enabled (is published as a guest embed)- (or (t2/exists? :model/Card :enable_embedding true)- (t2/exists? :model/Dashboard :enable_embedding true)))+ (or (embedding-hub.db/embedded-card-exists?)+ (embedding-hub.db/embedded-dashboard-exists?)))(defn- embedding-hub-checklist [](let [enable-tenants? (and (perms/use-tenants)diff --git a/enterprise/backend/src/metabase_enterprise/embedding_hub/db.clj b/enterprise/backend/src/metabase_enterprise/embedding_hub/db.cljnew file mode 100644index 00000000000..752c67f93eb--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/embedding_hub/db.clj@@ -0,0 +1,105 @@+(ns metabase-enterprise.embedding-hub.db+ "Application database queries for the embedding-hub module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn user-database-exists?+ "Whether a non-sample, non-audit Database exists."+ []+ (t2/exists? :model/Database {:where [:and+ [:= :is_sample false]+ [:= :is_audit false]]}))++(defn sample-database-id+ "The ID of the sample Database, or nil."+ []+ (t2/select-one-pk :model/Database :is_sample true))++(defn upload-table-exists-in-database?+ "Whether the Database with `database-id` holds an active uploaded Table."+ [database-id]+ (t2/exists? :model/Table {:where [:and+ [:= :active true]+ [:= :is_upload true]+ [:= :db_id database-id]]}))++(defn user-dashboard-exists?+ "Whether an unarchived Dashboard exists other than `example-dashboard-id` and outside the Collections with+ `excluded-collection-ids`."+ [example-dashboard-id excluded-collection-ids]+ (t2/exists? :model/Dashboard {:where (cond-> [:and+ [:= :archived false]]+ example-dashboard-id (conj [:not= :id example-dashboard-id])+ (seq excluded-collection-ids) (conj [:or+ [:is :collection_id nil]+ [:not-in :collection_id excluded-collection-ids]]))}))++(defn sandbox-exists?+ "Whether any Sandbox exists."+ []+ (t2/exists? :model/Sandbox))++(defn user-model-exists?+ "Whether an unarchived model Card exists outside the sample Collections and the Collection with+ `audit-collection-id`."+ [audit-collection-id]+ (t2/exists? :model/Card {:where [:and+ [:= :type "model"]+ [:= :archived false]+ [:or+ [:and+ [:!= :collection_id audit-collection-id]+ [:not [:exists ^:allow-subquery+ {:select [1]+ :from [[(t2/table-name :model/Collection) :sample_coll]]+ :where [:and+ [:= :sample_coll.is_sample true]+ [:= :sample_coll.id :report_card.collection_id]]}]]]+ [:is :collection_id nil]]]}))++(defn active-tenant-exists?+ "Whether an active Tenant exists."+ []+ (t2/exists? :model/Tenant :is_active true))++(defn shared-tenant-collection-exists?+ "Whether an unarchived shared tenant Collection exists."+ []+ (t2/exists? :model/Collection {:where [:and+ [:= :namespace "shared-tenant-collection"]+ [:= :archived false]]}))++(defn shared-tenant-collection-id+ "The ID of an unarchived shared tenant Collection, or nil."+ []+ (t2/select-one-pk :model/Collection {:where [:and+ [:= :namespace "shared-tenant-collection"]+ [:= :archived false]]}))++(defn unarchived-dashboard-exists-in-collection?+ "Whether an unarchived Dashboard exists in the Collection with `collection-id`."+ [collection-id]+ (t2/exists? :model/Dashboard {:where [:and+ [:= :collection_id collection-id]+ [:= :archived false]]}))++(defn impersonation-exists?+ "Whether any ConnectionImpersonation exists."+ []+ (t2/exists? :model/ConnectionImpersonation))++(defn database-router-exists?+ "Whether any DatabaseRouter exists."+ []+ (t2/exists? :model/DatabaseRouter))++(defn embedded-card-exists?+ "Whether any Card has embedding enabled."+ []+ (t2/exists? :model/Card :enable_embedding true))++(defn embedded-dashboard-exists?+ "Whether any Dashboard has embedding enabled."+ []+ (t2/exists? :model/Dashboard :enable_embedding true))diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/db.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/db.cljnew file mode 100644index 00000000000..57b430c29cb--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/db.clj@@ -0,0 +1,69 @@+(ns metabase-enterprise.entity-retrieval.db+ "Application database queries for the entity-retrieval module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn library-cards-in-collections+ "The ID, name, description, and type of the unarchived metric and model Cards in the Collections with+ `collection-ids`, optionally narrowed to just `id`."+ [collection-ids id]+ (t2/select [:model/Card :id :name :description :type :card_schema]+ {:where [:and+ [:in :collection_id collection-ids]+ [:= :archived false]+ [:in :type ["metric" "model"]]+ (when id [:= :id id])]}))++(defn library-tables-in-collections+ "The ID, names, and description of the active published Tables in the Collections with `collection-ids`, optionally+ narrowed to just `id`."+ [collection-ids id]+ (t2/select [:model/Table :id :name :display_name :description]+ {:where [:and+ [:in :collection_id collection-ids]+ [:= :is_published true]+ [:= :active true]+ (when id [:= :id id])]}))++(defn library-measures-of-tables+ "The ID, name, and description of the unarchived Measures on the Tables with `table-ids`, optionally narrowed to+ just `id`."+ [table-ids id]+ (t2/select [:model/Measure :id :name :description]+ {:where [:and+ [:in :table_id table-ids]+ [:= :archived false]+ (when id [:= :id id])]}))++(defn library-segments-of-tables+ "The ID, name, and description of the unarchived Segments on the Tables with `table-ids`, optionally narrowed to+ just `id`."+ [table-ids id]+ (t2/select [:model/Segment :id :name :description]+ {:where [:and+ [:in :table_id table-ids]+ [:= :archived false]+ (when id [:= :id id])]}))++(defn measure-table-id+ "The Table ID of the Measure with `id`."+ [id]+ (t2/select-one-fn :table_id :model/Measure :id id))++(defn segment-table-id+ "The Table ID of the Segment with `id`."+ [id]+ (t2/select-one-fn :table_id :model/Segment :id id))++(defn ai-contexts+ "The entity type, entity ID, and AI context of every OsiAiContext."+ []+ (t2/select [:model/OsiAiContext :entity_type :entity_local_id :ai_context]))++(defn ai-context+ "The AI context of the entity of `entity-type` with `entity-local-id`."+ [entity-local-id entity-type]+ (t2/select-one-fn :ai_context :model/OsiAiContext+ :entity_local_id entity-local-id+ :entity_type entity-type))diff --git a/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.clj b/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.cljindex 3621b37da52..39d23accaf5 100644--- a/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.clj+++ b/enterprise/backend/src/metabase_enterprise/entity_retrieval/reconcile.clj@@ -25,6 +25,7 @@[honey.sql :as sql][honey.sql.helpers :as sql.helpers][medley.core :as m]+ [metabase-enterprise.entity-retrieval.db :as entity-retrieval.db][metabase-enterprise.entity-retrieval.index-table :as index-table][metabase-enterprise.semantic-search.embedding :as embedding][metabase.collections.core :as collections]@@ -32,8 +33,7 @@[metabase.util :as u][metabase.util.log :as log][next.jdbc :as jdbc]- [next.jdbc.result-set :as jdbc.rs]- [toucan2.core :as t2])+ [next.jdbc.result-set :as jdbc.rs])(:import(java.sql Connection)))@@ -159,28 +159,20 @@(defn- library-cards [lib-ids id];; :card_schema is mandatory in any column-scoped Card SELECT (toucan guard). Card :type is keywordized;; (:metric / :model); the entity_type is its name string.- (->> (apply t2/select [:model/Card :id :name :description :type :card_schema]- (cond-> [:collection_id [:in lib-ids], :archived false, :type [:in ["metric" "model"]]]- id (conj :id id)))+ (->> (entity-retrieval.db/library-cards-in-collections lib-ids id)(map (fn [c] (->library-entity (name (:type c)) (:id c) (:name c) (:description c))))))(defn- library-tables [lib-ids id];; A published table's user-facing label is its display_name; fall back to the raw name.- (->> (apply t2/select [:model/Table :id :name :display_name :description]- (cond-> [:collection_id [:in lib-ids], :is_published true, :active true]- id (conj :id id)))+ (->> (entity-retrieval.db/library-tables-in-collections lib-ids id)(map (fn [t] (->library-entity "table" (:id t) (or (:display_name t) (:name t)) (:description t))))))(defn- library-measures [table-ids id]- (->> (apply t2/select [:model/Measure :id :name :description]- (cond-> [:table_id [:in table-ids], :archived false]- id (conj :id id)))+ (->> (entity-retrieval.db/library-measures-of-tables table-ids id)(map (fn [mv] (->library-entity "measure" (:id mv) (:name mv) (:description mv))))))(defn- library-segments [table-ids id]- (->> (apply t2/select [:model/Segment :id :name :description]- (cond-> [:table_id [:in table-ids], :archived false]- id (conj :id id)))+ (->> (entity-retrieval.db/library-segments-of-tables table-ids id)(map (fn [s] (->library-entity "segment" (:id s) (:name s) (:description s))))))(defn- library-entities@@ -212,9 +204,9 @@(#{"measure" "segment"} entity-type);; A measure/segment is a member only when its parent table is a current library table.- (when-let [table-id (t2/select-one-fn :table_id- (if (= entity-type "measure") :model/Measure :model/Segment)- :id entity-local-id)]+ (when-let [table-id (if (= entity-type "measure")+ (entity-retrieval.db/measure-table-id entity-local-id)+ (entity-retrieval.db/segment-table-id entity-local-id))](when (seq (library-tables lib-ids table-id))(first (if (= entity-type "measure")(library-measures [table-id] entity-local-id)@@ -243,7 +235,7 @@card's live metric/model type). One row per card is guaranteed by the normalized storage key."[](u/index-by entity-class :ai_context- (t2/select [:model/OsiAiContext :entity_type :entity_local_id :ai_context])))+ (entity-retrieval.db/ai-contexts)))(defn- dedup-by-doc-id [docs];; distinct-by doc_id so an exact duplicate (same doc_type and text, e.g. a synonym listed twice)@@ -266,9 +258,8 @@(if-let [member (library-entity entity-type entity-local-id)];; Match ai_context by the normalized storage type: a card's row is stored as `card`, so look it up by;; `card` whichever live label (metric/model) drove this targeted run.- (let [ai-ctx (t2/select-one-fn :ai_context :model/OsiAiContext- :entity_local_id entity-local-id- :entity_type (entity-retrieval/normalize-entity-type entity-type))]+ (let [ai-ctx (entity-retrieval.db/ai-context entity-local-id+ (entity-retrieval/normalize-entity-type entity-type))](dedup-by-doc-id (entity->docs member ai-ctx)))[]))diff --git a/enterprise/backend/src/metabase_enterprise/erd/db.clj b/enterprise/backend/src/metabase_enterprise/erd/db.cljnew file mode 100644index 00000000000..e16d23b4838--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/erd/db.clj@@ -0,0 +1,34 @@+(ns metabase-enterprise.erd.db+ "Application database queries for the erd module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.warehouse-schema.models.table :as schema.table]+ [toucan2.core :as t2]))++(defn active-tables-in-database+ "The `columns` of the active Tables in the Database with `database-id`. `opts` may restrict the result: a+ `:table-ids` key restricts to those IDs (even when its value is empty), and a `:schema` key restricts to that+ schema (`\"\"` matches both nil and empty-string schemas)."+ [columns database-id {:keys [table-ids schema] :as opts}]+ (t2/select :model/Table+ {:select columns+ :where (cond-> [:and [:= :db_id database-id] [:= :active true]]+ (contains? opts :table-ids) (conj [:in :id table-ids])+ (contains? opts :schema) (conj (if (= schema "")+ [:or [:= :schema nil] [:= :schema ""]]+ [:= :schema schema])))}))++(defn active-fields-for-tables+ "The active Fields of the Tables with `table-ids`, in field order."+ [table-ids]+ (t2/select :model/Field {:where [:and+ [:in :table_id table-ids]+ [:= :active true]]+ :order-by schema.table/field-order-rule}))++(defn active-fields+ "The active Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field {:where [:and+ [:in :id field-ids]+ [:= :active true]]}))diff --git a/enterprise/backend/src/metabase_enterprise/erd/impl.clj b/enterprise/backend/src/metabase_enterprise/erd/impl.cljindex 3727dc42233..3c1283dead7 100644--- a/enterprise/backend/src/metabase_enterprise/erd/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/erd/impl.clj@@ -3,6 +3,7 @@one-layer FK expansion, and response building."(:require[clojure.set :as set]+ [metabase-enterprise.erd.db :as erd.db][metabase.api.common :as api][metabase.models.interface :as mi][metabase.permissions.core :as perms]@@ -10,7 +11,6 @@[metabase.util.i18n :refer [tru]][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]- [metabase.warehouse-schema.models.table :as schema.table][toucan2.core :as t2]));;; -------------------------------------------------- Schema --------------------------------------------------@@ -82,16 +82,6 @@[:id :db_id :name :display_name :schema :is_published :collection_id:description :owner_user_id :owner_email :visibility_type])-(defn- schema-clause- "The rest of the database API treats a blank schema name as the union of nil- and empty-string schemas. Keep that convention here too."- [schema]- (if (= schema "")- [:or- [:= :schema nil]- [:= :schema ""]]- [:= :schema schema]))-(defn- index-by-id [xs](into {} (map (juxt :id identity)) xs))@@ -99,20 +89,14 @@"Fetch readable, active tables in `database-id`.Optional `table-ids` restricts by IDs; optional `schema` restricts by schema.`schema=\"\"` matches both nil and empty-string schemas."- [database-id & {:keys [table-ids schema] :as opts}]+ [database-id & {:keys [table-ids] :as opts}](if (and (contains? opts :table-ids) (empty? table-ids))[]- (let [where (cond-> [:and- [:= :db_id database-id]- [:= :active true]]- (contains? opts :table-ids) (conj [:in :id table-ids])- (contains? opts :schema) (conj (schema-clause schema)))]+ (do(perms/prime-table-perms-cache (if (contains? opts :table-ids){:table-ids (set table-ids)}{:db-ids #{database-id}}))- (->> (t2/select :model/Table- {:select table-select-columns- :where where})+ (->> (erd.db/active-tables-in-database table-select-columns database-id opts)(filter mi/can-read?)))))(defn- readable-table-ids@@ -127,20 +111,13 @@as table metadata view (`/api/table/:id/query_metadata`)."[table-ids](when (seq table-ids)- (t2/select :model/Field- {:where [:and- [:in :table_id table-ids]- [:= :active true]]- :order-by schema.table/field-order-rule})))+ (erd.db/active-fields-for-tables table-ids)))(defn- fetch-fields-by-ids"Fetch active fields by ID."[field-ids](when (seq field-ids)- (t2/select :model/Field- {:where [:and- [:in :id field-ids]- [:= :active true]]})))+ (erd.db/active-fields field-ids)))(defn- discover-fk-targets"Given a collection of fields, find FK target field IDs that point to tablesdiff --git a/enterprise/backend/src/metabase_enterprise/gsheets/api.clj b/enterprise/backend/src/metabase_enterprise/gsheets/api.cljindex 2ceaed91806..c896b0db93c 100644--- a/enterprise/backend/src/metabase_enterprise/gsheets/api.clj+++ b/enterprise/backend/src/metabase_enterprise/gsheets/api.clj@@ -3,6 +3,7 @@[java-time.api :as t][medley.core :as m][metabase-enterprise.gsheets.constants :as gsheets.constants]+ [metabase-enterprise.gsheets.db :as gsheets.db][metabase-enterprise.gsheets.settings:as gsheets.settings:refer [gsheets gsheets!]]@@ -18,8 +19,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import (java.time Instant)));; # Google Sheets Integration@@ -227,7 +227,7 @@(api.macros/defendpoint :post "/connection" :- :gsheets/response"Hook up a new google drive folder or sheet that will be watched and have its content ETL'd into Metabase."[{} {} {:keys [url]} :- [:map [:url ms/NonBlankString]]]- (let [attached-dwh (t2/select-one-fn :id :model/Database :is_attached_dwh true)]+ (let [attached-dwh (gsheets.db/attached-dwh-database-id)](when-not (some? attached-dwh)(analytics.event/track-event! :snowplow/simple_event {:event "sheets_connected" :event_detail "fail - no dwh"})(throw-error 400 (tru "No attached dwh found.") nil))@@ -256,7 +256,7 @@[](or (gsheets)(do (log/warn "CACHE MISS ON GSHEETS")- (some-> (t2/select-one :model/Setting :key "gsheets")+ (some-> (gsheets.db/setting "gsheets"):valuejson/decode+kw))))@@ -390,15 +390,15 @@(comment;; need an "attached dwh" locally?- (t2/update! :model/Database 1- {:is_attached_dwh true- :settings- (str "{\"auto-cruft-tables\":[\".*_dlt_loads$\",\".*_dlt_pipeline_state$\",\".*_dlt_sentinel_table$\",\".*_dlt_spreadsheet_info$\",\".*_dlt_version$\"],"- "\"auto-cruft-columns\":[\"^_dlt_id$\",\"^_dlt_load_id$\"]}")})+ (gsheets.db/update-database! 1+ {:is_attached_dwh true+ :settings+ (str "{\"auto-cruft-tables\":[\".*_dlt_loads$\",\".*_dlt_pipeline_state$\",\".*_dlt_sentinel_table$\",\".*_dlt_spreadsheet_info$\",\".*_dlt_version$\"],"+ "\"auto-cruft-columns\":[\"^_dlt_id$\",\"^_dlt_load_id$\"]}")})(do;; This is what the notify endpoint calls to do a sync on the attached dwh:#_{:clj-kondo/ignore [:metabase/modules]}(require '[metabase.sync.sync-metadata :as sync-metadata])(sync-metadata/sync-db-metadata!- (t2/select-one :model/Database :is_attached_dwh true))))+ (gsheets.db/attached-dwh-database))))diff --git a/enterprise/backend/src/metabase_enterprise/gsheets/db.clj b/enterprise/backend/src/metabase_enterprise/gsheets/db.cljnew file mode 100644index 00000000000..9f0c98b4fa5--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/gsheets/db.clj@@ -0,0 +1,25 @@+(ns metabase-enterprise.gsheets.db+ "Application database queries for the gsheets module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn attached-dwh-database-id+ "The ID of the attached data warehouse Database, or nil."+ []+ (t2/select-one-fn :id :model/Database :is_attached_dwh true))++(defn attached-dwh-database+ "The attached data warehouse Database, or nil."+ []+ (t2/select-one :model/Database :is_attached_dwh true))++(defn setting+ "The Setting with `setting-key`, or nil."+ [setting-key]+ (t2/select-one :model/Setting :key setting-key))++(defn update-database!+ "Apply `changes` to the Database with `database-id`."+ [database-id changes]+ (t2/update! :model/Database database-id changes))diff --git a/enterprise/backend/src/metabase_enterprise/gsheets/settings.clj b/enterprise/backend/src/metabase_enterprise/gsheets/settings.cljindex 1940128b8a6..a7a0bf7e823 100644--- a/enterprise/backend/src/metabase_enterprise/gsheets/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/gsheets/settings.clj@@ -2,6 +2,7 @@(:require[clojure.set :as set][metabase-enterprise.gsheets.constants :as gsheets.constants]+ [metabase-enterprise.gsheets.db :as gsheets.db][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting :refer [defsetting]][metabase.util :as u]@@ -9,8 +10,7 @@[metabase.util.json :as json][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(mr/def :gsheets/response[:or@@ -93,7 +93,7 @@:folder-upload-time :created-at})(dissoc :status)(cond->- (and (seq (dissoc value :status)) (nil? (:db-id value))) (assoc :db-id (t2/select-one-fn :id :model/Database :is_attached_dwh true)))+ (and (seq (dissoc value :status)) (nil? (:db-id value))) (assoc :db-id (gsheets.db/attached-dwh-database-id)))(u/prog1 (when-not (= (set (keys <>)) (set (keys value)))(setting/set-value-of-type! :json :gsheets <>)))))@@ -123,6 +123,6 @@(or;; This NEEDS to be up to date between instances on a cluster, so:;; we are going around the settings cache:- (some-> (t2/select-one :model/Setting :key "gsheets") :value json/decode+kw migrate-gsheet-value)+ (some-> (gsheets.db/setting "gsheets") :value json/decode+kw migrate-gsheet-value)(u/prog1 gsheets.constants/not-connected(setting/set-value-of-type! :json :gsheets <>)))))diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/api.clj b/enterprise/backend/src/metabase_enterprise/impersonation/api.cljindex 5223928029b..9c60fd9fade 100644--- a/enterprise/backend/src/metabase_enterprise/impersonation/api.clj+++ b/enterprise/backend/src/metabase_enterprise/impersonation/api.clj@@ -1,9 +1,9 @@(ns metabase-enterprise.impersonation.api(:require+ [metabase-enterprise.impersonation.db :as impersonation.db][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST API@@ -22,8 +22,8 @@[:db_id {:optional true} [:maybe ms/PositiveInt]]]](api/check-superuser)(if (and group_id db_id)- (t2/select-one :model/ConnectionImpersonation :group_id group_id :db_id db_id)- (t2/select :model/ConnectionImpersonation {:order-by [[:id :asc]]})))+ (impersonation.db/impersonation-for-group-and-database group_id db_id)+ (impersonation.db/all-impersonations)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -34,6 +34,6 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](api/check-superuser)- (api/check-404 (t2/select-one :model/ConnectionImpersonation :id id))- (t2/delete! :model/ConnectionImpersonation :id id)+ (api/check-404 (impersonation.db/impersonation id))+ (impersonation.db/delete-impersonation! id)api/generic-204-no-content)diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/db.clj b/enterprise/backend/src/metabase_enterprise/impersonation/db.cljnew file mode 100644index 00000000000..54bd3636f52--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/impersonation/db.clj@@ -0,0 +1,81 @@+(ns metabase-enterprise.impersonation.db+ "Application database queries for the impersonation module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [toucan2.core :as t2]))++(defn impersonation+ "The ConnectionImpersonation with `impersonation-id`, or nil."+ [impersonation-id]+ (t2/select-one :model/ConnectionImpersonation :id impersonation-id))++(defn impersonation-for-group-and-database+ "The ConnectionImpersonation of the group with `group-id` on the Database with `database-id`, or nil."+ [group-id database-id]+ (t2/select-one :model/ConnectionImpersonation :group_id group-id :db_id database-id))++(defn all-impersonations+ "Every ConnectionImpersonation, in ID order."+ []+ (t2/select :model/ConnectionImpersonation {:order-by [[:id :asc]]}))++(defn impersonations-for-groups+ "The ConnectionImpersonations of the groups with `group-ids`."+ [group-ids]+ (t2/select :model/ConnectionImpersonation :group_id [:in group-ids]))++(defn impersonations-for-groups-and-database+ "The ConnectionImpersonations of the groups with `group-ids` on the Database with `database-id`."+ [group-ids database-id]+ (t2/select :model/ConnectionImpersonation :group_id [:in group-ids] :db_id database-id))++(defn impersonations-matching+ "The ConnectionImpersonations narrowed by the optional `database-id`, `group-id`, and `group-ids`, excluding the+ Database with `excluded-database-id` when given."+ [database-id group-id group-ids excluded-database-id]+ (t2/select :model/ConnectionImpersonation+ {:where [:and+ (when database-id [:= :db_id database-id])+ (when group-id [:= :group_id group-id])+ (when group-ids [:in :group_id group-ids])+ (when excluded-database-id [:not [:= :db_id excluded-database-id]])]}))++(defn impersonation-exists-for-database?+ "Whether the Database with `database-id` has a ConnectionImpersonation."+ [database-id]+ (t2/exists? :model/ConnectionImpersonation :db_id database-id))++(defn insert-impersonation!+ "Insert `impersonation` and return the new instance."+ [impersonation]+ (first (t2/insert-returning-instances! :model/ConnectionImpersonation impersonation)))++(defn delete-impersonation!+ "Delete the ConnectionImpersonation with `impersonation-id`."+ [impersonation-id]+ (t2/delete! :model/ConnectionImpersonation :id impersonation-id))++(defn delete-impersonations-for-group-and-database!+ "Delete the ConnectionImpersonations of the group with `group-id` on the Database with `database-id`."+ [group-id database-id]+ (t2/delete! :model/ConnectionImpersonation :group_id group-id :db_id database-id))++(defn view-data-permission-values+ "The set of database-level view-data permission values `group-ids` hold on the Database with `database-id`."+ [database-id group-ids]+ (t2/select-fn-set :perm_value :model/DataPermissions+ {:where [:and+ [:= :db_id database-id]+ [:= :table_id nil]+ [:= :perm_type "perms/view-data"]+ [:in :group_id group-ids]]}))++(defn group-ids-for-user+ "The IDs of the PermissionsGroups the User with `user-id` belongs to."+ [user-id]+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/driver.clj b/enterprise/backend/src/metabase_enterprise/impersonation/driver.cljindex 4a9c01829c7..9b9b2b77e70 100644--- a/enterprise/backend/src/metabase_enterprise/impersonation/driver.clj+++ b/enterprise/backend/src/metabase_enterprise/impersonation/driver.clj@@ -2,6 +2,7 @@(:require[clojure.set :as set][clojure.string :as str]+ [metabase-enterprise.impersonation.db :as impersonation.db][metabase-enterprise.sandbox.api.util :as sandbox.api.util][metabase.api.common :as api][metabase.driver :as driver]@@ -11,8 +12,7 @@[metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]- [metabase.warehouse-schema.models.field :as field]- [toucan2.core :as t2])+ [metabase.warehouse-schema.models.field :as field])(:import(java.sql Connection)))@@ -31,14 +31,7 @@(let [non-impersonated-group-ids (set/difference (set group-ids)(set (map :group_id impersonations)))perm-values (when (seq non-impersonated-group-ids)- (t2/select-fn-set :perm_value- :model/DataPermissions- {:where- [:and- [:= :db_id (u/the-id db-or-id)]- [:= :table_id nil]- [:= :perm_type (u/qualified-name :perms/view-data)]- [:in :group_id non-impersonated-group-ids]]}))]+ (impersonation.db/view-data-permission-values (u/the-id db-or-id) non-impersonated-group-ids))];; Just check if any other non-impersonated groups have unrestricted access to the DB. We don't need to worry;; about block permissions here because it would have been enforced earlier in the QP middleware stack.(not (contains? perm-values :unrestricted))))@@ -48,7 +41,7 @@[db-or-id](boolean(when (and db-or-id (premium-features/enable-advanced-permissions?))- (t2/exists? :model/ConnectionImpersonation :db_id (u/id db-or-id)))))+ (impersonation.db/impersonation-exists-for-database? (u/id db-or-id)))))(defn enforced-impersonations-for-db"Returns the connection impersonation policies which should be enforced for the provided DB for the current user, if@@ -59,11 +52,9 @@Note: this returns a list of policies. Typically a user should only be in one group with an impersonation policy at a time,but there may be policies in multiple groups if they use the same user attribute."[db-or-id]- (let [group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id api/*current-user-id*)+ (let [group-ids (impersonation.db/group-ids-for-user api/*current-user-id*)conn-impersonations (when (seq group-ids)- (t2/select :model/ConnectionImpersonation- :group_id [:in group-ids]- :db_id (u/the-id db-or-id)))]+ (impersonation.db/impersonations-for-groups-and-database group-ids (u/the-id db-or-id)))](when (and (seq conn-impersonations) (sandboxed? db-or-id))(throw (ex-info (tru "Conflicting sandboxing and impersonation policies found."){:user-id api/*current-user-id*@@ -92,7 +83,7 @@role (get user-attributes role-attribute)database (if (map? database-or-id)database-or-id- (t2/select-one :model/Database :id (u/the-id database-or-id)))+ (impersonation.db/database (u/the-id database-or-id)))default-role (driver.sql/default-database-role (driver.u/database->driver database) database)](cond(nil? role)diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/models.clj b/enterprise/backend/src/metabase_enterprise/impersonation/models.cljindex d2f4a052102..eccb1c14162 100644--- a/enterprise/backend/src/metabase_enterprise/impersonation/models.clj+++ b/enterprise/backend/src/metabase_enterprise/impersonation/models.clj@@ -3,6 +3,7 @@certain permission groups when running queries."(:require[medley.core :as m]+ [metabase-enterprise.impersonation.db :as impersonation.db][metabase.audit-app.core :as audit][metabase.models.interface :as mi][metabase.premium-features.core :refer [defenterprise]]@@ -24,12 +25,10 @@[graph & {:keys [group-ids group-id db-id audit-db?]}](m/deep-mergegraph- (let [impersonations (t2/select :model/ConnectionImpersonation- {:where [:and- (when db-id [:= :db_id db-id])- (when group-id [:= :group_id group-id])- (when group-ids [:in :group_id group-ids])- (when-not audit-db? [:not [:= :db_id audit/audit-db-id]])]})]+ (let [impersonations (impersonation.db/impersonations-matching db-id+ group-id+ group-ids+ (when-not audit-db? audit/audit-db-id))](reduce (fn [acc {:keys [db_id group_id]}](assoc-in acc [group_id db_id :view-data] :impersonated)){}@@ -43,11 +42,8 @@(doall(for [impersonation impersonations](do- (t2/delete! :model/ConnectionImpersonation- :group_id (:group_id impersonation)- :db_id (:db_id impersonation))- (-> (t2/insert-returning-instances! :model/ConnectionImpersonation impersonation)- first)))))+ (impersonation.db/delete-impersonations-for-group-and-database! (:group_id impersonation) (:db_id impersonation))+ (impersonation.db/insert-impersonation! impersonation)))))(defn- delete-impersonations-for-group-database! [{:keys [group-id database-id]} changes](log/debugf "Deleting unneeded Connection Impersonations for Group %d for Database %d. Graph changes: %s"@@ -60,7 +56,7 @@:blocked "is now BLOCKED from all non-data-perms access""now has granular (sandboxed) data access")database-id)- (t2/delete! :model/ConnectionImpersonation :group_id group-id :db_id database-id)))+ (impersonation.db/delete-impersonations-for-group-and-database! group-id database-id)))(defn- delete-impersonations-for-group! [{:keys [group-id]} changes](log/debugf "Deleting unneeded Connection Impersonation policies for Group %d. Graph changes: %s" group-id (pr-str changes))diff --git a/enterprise/backend/src/metabase_enterprise/impersonation/util.clj b/enterprise/backend/src/metabase_enterprise/impersonation/util.cljindex 279ebc0a999..715517f8a6a 100644--- a/enterprise/backend/src/metabase_enterprise/impersonation/util.clj+++ b/enterprise/backend/src/metabase_enterprise/impersonation/util.clj@@ -1,10 +1,10 @@(ns metabase-enterprise.impersonation.util(:require+ [metabase-enterprise.impersonation.db :as impersonation.db][metabase-enterprise.impersonation.driver :as impersonation.driver][metabase.api.common :refer [*current-user-id* *is-superuser?*]][metabase.premium-features.core :refer [defenterprise]]- [metabase.util.i18n :refer [tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [tru]]))(defenterprise impersonation-enforced-for-db?"Returns a boolean if the current user has a connection impersonation policy which should be enforced for the provided@@ -30,10 +30,10 @@(boolean(when-not *is-superuser?*(if *current-user-id*- (let [group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id *current-user-id*)]+ (let [group-ids (impersonation.db/group-ids-for-user *current-user-id*)](seq(when (seq group-ids)- (t2/select :model/ConnectionImpersonation :group_id [:in group-ids]))))+ (impersonation.db/impersonations-for-groups group-ids))));; If no *current-user-id* is bound we can't check for impersonations, so we should throw in this case to avoid;; returning `false` for users who should actually be using impersonation.(throw (ex-info (str (tru "No current user found"))diff --git a/enterprise/backend/src/metabase_enterprise/library/api.clj b/enterprise/backend/src/metabase_enterprise/library/api.cljindex a33fea17595..c80c464dd05 100644--- a/enterprise/backend/src/metabase_enterprise/library/api.clj+++ b/enterprise/backend/src/metabase_enterprise/library/api.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.library.api(:require+ [metabase-enterprise.library.db :as library.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -27,8 +28,8 @@(defn- add-here-and-below [collection](let [descendent-ids (map :id (collection/descendants-flat collection))- below-card-types (t2/select-fn-set :type [:model/Card :type] :collection_id [:in descendent-ids])- below-tables? (t2/exists? :model/Table :is_published true :collection_id [:in descendent-ids])]+ below-card-types (library.db/card-types-in-collections descendent-ids)+ below-tables? (library.db/published-table-in-collections? descendent-ids)];; This function is only used on the root Library which cannot have items directly in it;; So can assume :here is only collection, and all descendants are :below(assoc collection :here #{"collection"}@@ -46,28 +47,11 @@_body](if-let [library (collections/library-collection)](-> (api/read-check library)- (t2/hydrate- :can_write- :effective_children)+ (t2/hydrate :can_write :effective_children)(add-here-and-below)(assoc :model "collection")){:data nil}))-(defn- select-collections- []- (t2/select :model/Collection- {:where [:and- [:in :type [collection/library-collection-type- collection/library-data-collection-type- collection/library-metrics-collection-type]]- (collection/visible-collection-filter-clause- :id- {:include-archived-items :exclude- :include-trash-collection? false- :permission-level :read- :archive-operation-id nil})]- :order-by [[:%lower.name :asc]]}))-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;@@ -76,7 +60,7 @@"This matches /api/collection/tree but only returns the library collection."[_route-params_query]- (let [collections (-> (select-collections)+ (let [collections (-> (library.db/library-collections)(t2/hydrate :can_write))collection-type-ids (reduce (fn [acc {collection-id :collection_id, card-type :type, :as _card}](update acc (case (keyword card-type)@@ -86,9 +70,7 @@{:dataset #{}:metric #{}:card #{}}- (t2/reducible-query {:select-distinct [:collection_id :type]- :from [:report_card]- :where [:= :archived false]}))]+ (library.db/unarchived-card-collection-types-reducible))](collection/collections->tree collection-type-ids collections)))(def ^{:arglists '([request respond raise])} routesdiff --git a/enterprise/backend/src/metabase_enterprise/library/db.clj b/enterprise/backend/src/metabase_enterprise/library/db.cljnew file mode 100644index 00000000000..c3156f579c6--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/library/db.clj@@ -0,0 +1,44 @@+(ns metabase-enterprise.library.db+ "Application database queries for the library module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.collections.models.collection :as collection]+ [toucan2.core :as t2]))++(defn card-types-in-collections+ "The set of Card types present in the Collections with `collection-ids`."+ [collection-ids]+ (t2/select-fn-set :type [:model/Card :type] :collection_id [:in collection-ids]))++(defn published-table-in-collections?+ "Whether a published Table exists in the Collections with `collection-ids`."+ [collection-ids]+ (t2/exists? :model/Table :is_published true :collection_id [:in collection-ids]))++(defn library-collections+ "The readable Library, Library-data, and Library-metrics Collections, ordered by name."+ []+ (t2/select :model/Collection+ {:where [:and+ [:in :type [collection/library-collection-type+ collection/library-data-collection-type+ collection/library-metrics-collection-type]]+ (collection/visible-collection-filter-clause+ :id+ {:include-archived-items :exclude+ :include-trash-collection? false+ :permission-level :read+ :archive-operation-id nil})]+ :order-by [[:%lower.name :asc]]}))++(defn collection-type+ "The type of the Collection with `collection-id`."+ [collection-id]+ (t2/select-one-fn :type [:model/Collection :type] :id collection-id))++(defn unarchived-card-collection-types-reducible+ "Reducible distinct Collection ID and Card type pairs of the unarchived Cards."+ []+ (t2/reducible-query {:select-distinct [:collection_id :type]+ :from [:report_card]+ :where [:= :archived false]}))diff --git a/enterprise/backend/src/metabase_enterprise/library/validation.clj b/enterprise/backend/src/metabase_enterprise/library/validation.cljindex 7baec10fad7..9a7004c5b32 100644--- a/enterprise/backend/src/metabase_enterprise/library/validation.clj+++ b/enterprise/backend/src/metabase_enterprise/library/validation.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.library.validation(:require[clojure.set :as set]+ [metabase-enterprise.library.db :as library.db][metabase.collections.models.collection :as collection][metabase.premium-features.core :refer [defenterprise]][toucan2.core :as t2]))@@ -26,7 +27,7 @@:feature :library[content-type collection-id](when collection-id- (let [collection-type (t2/select-one-fn :type [:model/Collection :type] :id collection-id)]+ (let [collection-type (library.db/collection-type collection-id)](when-let [{:keys [allowed-content-types error-message]} (some-> collection-typelibrary-collection-content-specs)](when-not (allowed-content-types content-type)@@ -48,6 +49,6 @@(when (and (collection/is-library-collection? (:id collection))(contains? change-keys :location)(when-let [parent-id (collection/location-path->parent-id (:location collection))]- (not= (:type collection) (t2/select-one-fn :type :model/Collection :id parent-id))))+ (not= (:type collection) (library.db/collection-type parent-id))))(throw (ex-info "Cannot move a Library collection outside the Library" {}))))true)diff --git a/enterprise/backend/src/metabase_enterprise/mcp/db.clj b/enterprise/backend/src/metabase_enterprise/mcp/db.cljnew file mode 100644index 00000000000..db284d48c53--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mcp/db.clj@@ -0,0 +1,40 @@+(ns metabase-enterprise.mcp.db+ "Application database queries for the mcp module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn session-log-exists?+ "Whether an McpSessionLog with `session-id` exists."+ [session-id]+ (t2/exists? :model/McpSessionLog :id session-id))++(defn session-client-identity+ "The client name and version of the McpSessionLog with `session-id`, or nil."+ [session-id]+ (t2/select-one [:model/McpSessionLog :client_name :client_version] :id session-id))++(defn insert-session-log!+ "Insert the McpSessionLog `row`."+ [row]+ (t2/insert! :model/McpSessionLog row))++(defn end-session-log!+ "Stamp `ended_at` on the McpSessionLog with `session-id`."+ [session-id]+ (t2/update! :model/McpSessionLog :id session-id {:ended_at :%now}))++(defn insert-tool-call-log!+ "Insert the McpToolCallLog `row`."+ [row]+ (t2/insert! :model/McpToolCallLog row))++(defn delete-tool-call-logs-created-before!+ "Delete the McpToolCallLogs created before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/McpToolCallLog {:where [:< :created_at cutoff]}))++(defn delete-session-logs-created-before!+ "Delete the McpSessionLogs created before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/McpSessionLog {:where [:< :created_at cutoff]}))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.clj b/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.cljindex 7aaab831b86..02d079428bb 100644--- a/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.clj+++ b/enterprise/backend/src/metabase_enterprise/mcp/task/mcp_usage_trimmer.clj@@ -8,10 +8,10 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.mcp.db :as mcp.db][metabase.metabot.settings :as metabot.settings][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(org.quartz DisallowConcurrentExecution)))@@ -30,8 +30,8 @@;; Each table is pruned independently by its own created_at. Tool-call rows are;; self-contained (identity is denormalized onto them, no session link), so pruning a;; session row can never orphan a tool call.- (let [calls (t2/delete! :model/McpToolCallLog {:where [:< :created_at cutoff]})- sessions (t2/delete! :model/McpSessionLog {:where [:< :created_at cutoff]})]+ (let [calls (mcp.db/delete-tool-call-logs-created-before! cutoff)+ sessions (mcp.db/delete-session-logs-created-before! cutoff)](log/infof "MCP usage log cleanup complete. Deleted %d tool-call and %d session rows."(or calls 0) (or sessions 0)))))))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/usage.clj b/enterprise/backend/src/metabase_enterprise/mcp/usage.cljindex c4052206c82..d466cf565b5 100644--- a/enterprise/backend/src/metabase_enterprise/mcp/usage.clj+++ b/enterprise/backend/src/metabase_enterprise/mcp/usage.clj@@ -8,12 +8,12 @@best-effort: a failure is logged and swallowed so logging never fails the MCP request andadds negligible latency."(:require+ [metabase-enterprise.mcp.db :as mcp.db][metabase.analytics.core :as analytics][metabase.analytics.settings :as analytics.settings][metabase.mcp.usage :as mcp.usage][metabase.premium-features.core :refer [defenterprise]]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -52,7 +52,7 @@(when (and session-id;; mcp-remote fires a throwaway transport-probe handshake; never record it(not (mcp.usage/proxy-probe? (:name client-info)))- (not (t2/exists? :model/McpSessionLog :id session-id)))+ (not (mcp.db/session-log-exists? session-id)))(let [;; `pii-fields-from` returns the gated PII columns only when;; `analytics-pii-retention-enabled` is on (nil otherwise). Allowlist the two columns;; `mcp_session_log` actually has — selecting explicitly (rather than dissoc-ing the@@ -61,13 +61,13 @@pii (select-keys (analytics/pii-fields-from {:user-agent user-agent:ip-address ip-address})[:user_agent :ip_address])]- (t2/insert! :model/McpSessionLog- (merge {:id session-id- :user_id user-id- :tenant_id tenant-id- :client_name (mcp.usage/detect-client (:name client-info))- :client_version (truncate (:version client-info) client-version-max-length)}- pii))))+ (mcp.db/insert-session-log!+ (merge {:id session-id+ :user_id user-id+ :tenant_id tenant-id+ :client_name (mcp.usage/detect-client (:name client-info))+ :client_version (truncate (:version client-info) client-version-max-length)}+ pii))))(catch Throwable e(log/warnf "Failed to record MCP session: %s" (ex-message e)))))@@ -78,7 +78,7 @@[session-id](try(when session-id- (t2/update! :model/McpSessionLog :id session-id {:ended_at :%now}))+ (mcp.db/end-session-log! session-id))(catch Throwable e(log/warnf "Failed to record MCP session end: %s" (ex-message e)))))@@ -96,7 +96,7 @@:client_version (truncate (:version client-info) client-version-max-length)}session-id- (t2/select-one [:model/McpSessionLog :client_name :client_version] :id session-id)+ (mcp.db/session-client-identity session-id):else nil))@@ -118,18 +118,18 @@pii (select-keys (analytics/pii-fields-from {:user-agent user-agent:ip-address ip-address})[:user_agent :ip_address :sanitized_user_agent])]- (t2/insert! :model/McpToolCallLog- (merge {:tool_name (or (not-empty (truncate tool-name tool-name-max-length))- unknown-tool-name)- :user_id user-id- :client_name client_name- :client_version client_version- :tenant_id tenant-id- :status status- :duration_ms duration-ms- :error_code error-code- :error_message (when (analytics.settings/analytics-pii-retention-enabled)- (truncate error-message error-message-max-length))}- pii)))+ (mcp.db/insert-tool-call-log!+ (merge {:tool_name (or (not-empty (truncate tool-name tool-name-max-length))+ unknown-tool-name)+ :user_id user-id+ :client_name client_name+ :client_version client_version+ :tenant_id tenant-id+ :status status+ :duration_ms duration-ms+ :error_code error-code+ :error_message (when (analytics.settings/analytics-pii-retention-enabled)+ (truncate error-message error-message-max-length))}+ pii)))(catch Throwable e(log/warnf "Failed to record MCP tool call: %s" (ex-message e)))))diff --git a/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.cljindex f6ac8773752..17c253f94eb 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.metabot.api.permissions"`/api/ee/ai-controls/permissions` routes for managing metabot permissions per group."(:require+ [metabase-enterprise.metabot.db :as metabot.db][metabase-enterprise.metabot.models.metabot-permissions :as metabot-perms][metabase-enterprise.metabot.settings :as metabot-settings][metabase.api.common :as api]@@ -77,11 +78,11 @@(doseq [{:keys [group_id perm_type perm_value]} permissions](let [perm-type-kw (keyword perm_type)perm-value-kw (keyword perm_value)]- (if (t2/exists? :model/MetabotPermissions :group_id group_id :perm_type perm-type-kw)- (t2/update! :model/MetabotPermissions {:group_id group_id :perm_type perm-type-kw} {:perm_value perm-value-kw})- (t2/insert! :model/MetabotPermissions {:group_id group_id- :perm_type perm-type-kw- :perm_value perm-value-kw})))))+ (if (metabot.db/permission-exists? group_id perm-type-kw)+ (metabot.db/update-permission-value! group_id perm-type-kw perm-value-kw)+ (metabot.db/insert-permission! {:group_id group_id+ :perm_type perm-type-kw+ :perm_value perm-value-kw})))))(permissions-response))(defn- switch-mode!@@ -92,7 +93,7 @@[advanced?](try(t2/with-transaction [_conn]- (t2/delete! :model/MetabotPermissions {:where (metabot-perms/hidden-groups-clause advanced?)})+ (metabot.db/delete-hidden-group-permissions! advanced?)(metabot-settings/metabot-advanced-permissions! advanced?))(catch Throwable e(setting/restore-cache!)diff --git a/enterprise/backend/src/metabase_enterprise/metabot/db.clj b/enterprise/backend/src/metabase_enterprise/metabot/db.cljnew file mode 100644index 00000000000..ac85307f3bd--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/metabot/db.clj@@ -0,0 +1,170 @@+(ns metabase-enterprise.metabot.db+ "Application database queries for the metabot module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods, and transactions."+ (:require+ [metabase.permissions.core :as perms]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn- default-group-ids+ "The IDs of the groups visible only in simple mode: All Users and, on tenant instances, All tenant users."+ []+ [(u/the-id (perms/all-users-group)) (u/the-id (perms/all-external-users-group))])++(defn- visible-groups-expr+ "Matches the groups the admin UI shows in the mode selected by `advanced?`: Administrators, All Users, and All+ tenant users in simple mode, every other group in group-level mode."+ [advanced?]+ (if advanced?+ [:not-in :group_id (default-group-ids)]+ [:in :group_id (conj (default-group-ids) (u/the-id (perms/admin-group)))]))++(defn all-groups+ "Every PermissionsGroup, in ID order."+ []+ (t2/select :model/PermissionsGroup {:order-by [[:id :asc]]}))++(defn all-stored-permissions+ "Every MetabotPermissions row, ordered by group and permission type."+ []+ (t2/select :model/MetabotPermissions {:order-by [[:group_id :asc] [:perm_type :asc]]}))++(defn visible-permissions-for-user+ "The MetabotPermissions rows of the groups of the User with `user-id` that the mode selected by `advanced?` shows."+ [user-id advanced?]+ (t2/select :model/MetabotPermissions+ {:where [:and+ [:in :group_id+ ^:allow-subquery+ {:select [:group_id]+ :from [(t2/table-name :model/PermissionsGroupMembership)]+ :where [:= :user_id user-id]}]+ (visible-groups-expr advanced?)]}))++(defn permission-exists?+ "Whether the group with `group-id` has a MetabotPermissions row of `perm-type`."+ [group-id perm-type]+ (t2/exists? :model/MetabotPermissions :group_id group-id :perm_type perm-type))++(defn update-permission-value!+ "Set the value of the MetabotPermissions row of `perm-type` for the group with `group-id`."+ [group-id perm-type perm-value]+ (t2/update! :model/MetabotPermissions {:group_id group-id :perm_type perm-type} {:perm_value perm-value}))++(defn insert-permission!+ "Insert the MetabotPermissions `row`."+ [row]+ (t2/insert! :model/MetabotPermissions row))++(defn delete-hidden-group-permissions!+ "Delete the MetabotPermissions rows of the groups the mode selected by `advanced?` hides."+ [advanced?]+ (t2/delete! :model/MetabotPermissions {:where [:not (visible-groups-expr advanced?)]}))++(defn group-limits+ "Every MetabotGroupLimit, in group order."+ []+ (t2/select :model/MetabotGroupLimit {:order-by [[:group_id :asc]]}))++(defn group-limit+ "The MetabotGroupLimit of the group with `group-id`, or nil."+ [group-id]+ (t2/select-one :model/MetabotGroupLimit :group_id group-id))++(defn max-usage-for-user+ "The `:max_usage` row holding the largest group limit of the User with `user-id`, or nil if any of their groups+ is unlimited."+ [user-id]+ (t2/query-one {:select [[[:case+ [:= [[:count :*]] [[:count :gl.max_usage]]]+ [[:max :gl.max_usage]]]+ :max_usage]]+ :from [[:permissions_group_membership :pgm]]+ :left-join [[:metabot_group_limit :gl] [:= :pgm.group_id :gl.group_id]]+ :where [:= :pgm.user_id user-id]}))++(defn insert-group-limit!+ "Insert the MetabotGroupLimit `row`."+ [row]+ (t2/insert! :model/MetabotGroupLimit row))++(defn update-group-limit!+ "Set the maximum usage of the MetabotGroupLimit with `limit-id`."+ [limit-id max-usage]+ (t2/update! :model/MetabotGroupLimit limit-id {:max_usage max-usage}))++(defn delete-group-limit!+ "Delete the MetabotGroupLimit of the group with `group-id`."+ [group-id]+ (t2/delete! :model/MetabotGroupLimit :group_id group-id))++(defn instance-limit+ "The MetabotInstanceLimit of the Tenant with `tenant-id` (nil for the instance-wide limit), or nil."+ [tenant-id]+ (t2/select-one :model/MetabotInstanceLimit :tenant_id tenant-id))++(defn tenant-limits+ "The MetabotInstanceLimits of tenants, ordered by tenant."+ []+ (t2/select :model/MetabotInstanceLimit :tenant_id [:not= nil] {:order-by [[:tenant_id :asc]]}))++(defn insert-instance-limit!+ "Insert the MetabotInstanceLimit `row`."+ [row]+ (t2/insert! :model/MetabotInstanceLimit row))++(defn update-instance-limit!+ "Set the maximum usage of the MetabotInstanceLimit with `limit-id`."+ [limit-id max-usage]+ (t2/update! :model/MetabotInstanceLimit limit-id {:max_usage max-usage}))++(defn delete-instance-limit!+ "Delete the MetabotInstanceLimit of the Tenant with `tenant-id`."+ [tenant-id]+ (t2/delete! :model/MetabotInstanceLimit :tenant_id tenant-id))++(defn insert-usage-log!+ "Insert the AiUsageLog `row`."+ [row]+ (t2/insert! :model/AiUsageLog row))++(defn- usage-window-expr+ [period-start user-id tenant-id]+ [:and+ [:>= :created_at period-start]+ (when user-id [:= :user_id user-id])+ (when tenant-id [:= :tenant_id tenant-id])])++(defn usage-token-sum+ "The `:sum` row of tokens logged since `period-start`, narrowed by the optional `user-id` and `tenant-id`."+ [period-start user-id tenant-id]+ (t2/query-one {:select [[[:sum :total_tokens] :sum]]+ :from [:ai_usage_log]+ :where (usage-window-expr period-start user-id tenant-id)}))++(defn usage-message-count+ "The `:cnt` row of messages logged since `period-start`, narrowed by the optional `user-id` and `tenant-id`."+ [period-start user-id tenant-id]+ (t2/query-one {:select [[[:count :*] :cnt]]+ :from [:ai_usage_log]+ :where (usage-window-expr period-start user-id tenant-id)}))++(defn delete-usage-logs-created-before!+ "Delete the AiUsageLogs created before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/AiUsageLog {:where [:< :created_at cutoff]}))++(defn transform+ "The Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/Transform :id transform-id))++(defn transforms+ "The Transforms with `transform-ids`."+ [transform-ids]+ (t2/select :model/Transform :id [:in transform-ids]))++(defn cards+ "The Cards with `card-ids`."+ [card-ids]+ (t2/select :model/Card :id [:in card-ids]))diff --git a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.clj b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.cljindex d4cabf96ee1..2fc12f50841 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_group_limit.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.metabot.models.metabot-group-limit(:require+ [metabase-enterprise.metabot.db :as metabot.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -13,33 +14,27 @@(defn all-group-limits"Returns all group-level limits, ordered by group_id."[]- (t2/select :model/MetabotGroupLimit {:order-by [[:group_id :asc]]}))+ (metabot.db/group-limits))(defn group-limit"Returns the limit for a specific group, or nil if none is set."[group-id]- (t2/select-one :model/MetabotGroupLimit :group_id group-id))+ (metabot.db/group-limit group-id))(defn limit-for-user"Returns the maximum `max_usage` across all group limits for groups the user belongs to.Returns nil if the user has any groups with a null (unlimited) limit"[user-id](:max_usage- (t2/query-one {:select [[[:case- [:= [[:count :*]] [[:count :gl.max_usage]]]- [[:max :gl.max_usage]]]- :max_usage]]- :from [[:permissions_group_membership :pgm]]- :left-join [[:metabot_group_limit :gl] [:= :pgm.group_id :gl.group_id]]- :where [:= :pgm.user_id user-id]})))+ (metabot.db/max-usage-for-user user-id)))(defn set-group-limit!"Sets or removes the limit for a specific group. Pass nil to remove (unlimited).Returns the updated row, or nil if removed."[group-id max-usage](if (nil? max-usage)- (t2/delete! :model/MetabotGroupLimit :group_id group-id)+ (metabot.db/delete-group-limit! group-id)(if-let [existing (group-limit group-id)]- (t2/update! :model/MetabotGroupLimit (:id existing) {:max_usage max-usage})- (t2/insert! :model/MetabotGroupLimit {:group_id group-id :max_usage max-usage})))+ (metabot.db/update-group-limit! (:id existing) max-usage)+ (metabot.db/insert-group-limit! {:group_id group-id :max_usage max-usage})))(group-limit group-id))diff --git a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.clj b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.cljindex e6cd572715d..9892b773887 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_instance_limit.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.metabot.models.metabot-instance-limit(:require+ [metabase-enterprise.metabot.db :as metabot.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -14,20 +15,20 @@"Returns the limit for a given tenant, or the instance-wide limit when `tenant-id` is nil.Returns nil if no limit is set."[tenant-id]- (t2/select-one :model/MetabotInstanceLimit :tenant_id tenant-id))+ (metabot.db/instance-limit tenant-id))(defn set-instance-limit!"Sets or removes the limit for a given tenant (or instance-wide when `tenant-id` is nil).Pass nil for `max-usage` to remove the limit. Returns the updated row, or nil if removed."[tenant-id max-usage](if (nil? max-usage)- (t2/delete! :model/MetabotInstanceLimit :tenant_id tenant-id)+ (metabot.db/delete-instance-limit! tenant-id)(if-let [existing (instance-limit tenant-id)]- (t2/update! :model/MetabotInstanceLimit (:id existing) {:max_usage max-usage})- (t2/insert! :model/MetabotInstanceLimit {:tenant_id tenant-id :max_usage max-usage})))+ (metabot.db/update-instance-limit! (:id existing) max-usage)+ (metabot.db/insert-instance-limit! {:tenant_id tenant-id :max_usage max-usage})))(instance-limit tenant-id))(defn all-tenant-limits"Returns all tenant-level limits (where tenant_id is not null), ordered by tenant_id."[]- (t2/select :model/MetabotInstanceLimit :tenant_id [:not= nil] {:order-by [[:tenant_id :asc]]}))+ (metabot.db/tenant-limits))diff --git a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.cljindex 557a9dde09f..5faa60291a4 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.clj@@ -1,10 +1,9 @@(ns metabase-enterprise.metabot.models.metabot-permissions"Toucan2 model registration and DB helpers for `:model/MetabotPermissions`."(:require+ [metabase-enterprise.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.models.interface :as mi]- [metabase.permissions.core :as perms]- [metabase.util :as u][methodical.core :as methodical][toucan2.core :as t2]))@@ -18,28 +17,6 @@{:perm_type mi/transform-keyword:perm_value mi/transform-keyword})-(defn- default-group-ids- "Return the IDs of groups visible only in simple mode: All Users and, on tenant instances, All tenant users."- []- [(u/the-id (perms/all-users-group)) (u/the-id (perms/all-external-users-group))])--(defn visible-groups-clause- "Return a HoneySQL predicate that matches groups visible in the admin UI for the mode selected by `advanced?`.-- Simple mode shows Administrators, All Users, and All tenant users. Group-level mode shows all other groups."- [advanced?]- (if advanced?- [:not-in :group_id (default-group-ids)]- [:in :group_id (conj (default-group-ids) (u/the-id (perms/admin-group)))]))--(defn hidden-groups-clause- "Return a HoneySQL predicate that matches groups hidden in the admin UI for the mode selected by `advanced?`.-- This is the complement of `visible-groups-clause`. Rows that match this predicate are deleted when switching- modes."- [advanced?]- [:not (visible-groups-clause advanced?)])-(defn permissions-for-group"Returns the full set of permissions for a group, filling in defaults for any missing perm types."[group-id stored-perms]@@ -53,8 +30,8 @@(defn all-permissions"Returns all metabot permissions for all groups, filling in defaults for missing entries."[]- (let [groups (t2/select :model/PermissionsGroup {:order-by [[:id :asc]]})- stored (t2/select :model/MetabotPermissions {:order-by [[:group_id :asc] [:perm_type :asc]]})+ (let [groups (metabot.db/all-groups)+ stored (metabot.db/all-stored-permissions)by-group (group-by :group_id stored)]{:permissions (vec (mapcat (fn [{:keys [id]}](permissions-for-group id (get by-group id [])))diff --git a/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/permissions.cljindex 7102877f804..a2107c67ae1 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj@@ -3,11 +3,10 @@Resolves per-group permissions from the database, taking the most permissive value across the user's groupsthat the active permission mode shows."(:require- [metabase-enterprise.metabot.models.metabot-permissions :as metabot-perms]+ [metabase-enterprise.metabot.db :as metabot.db][metabase-enterprise.metabot.settings :as metabot-settings][metabase.metabot.scope :as scope]- [metabase.premium-features.core :refer [defenterprise]]- [toucan2.core :as t2]))+ [metabase.premium-features.core :refer [defenterprise]]))(defenterprise resolve-user-permissions"Resolve the effective metabot permissions for a user by taking the most permissive value across the groups@@ -17,21 +16,11 @@[user-id](if-not user-idscope/all-yes-permissions- (let [stored (t2/select :model/MetabotPermissions- {:where [:and- [:in :group_id- ^:allow-subquery- {:select [:group_id]- :from [(t2/table-name :model/PermissionsGroupMembership)]- :where [:= :user_id user-id]}]- ;; Ignore permission rows for groups hidden by the active mode. An unseen- ;; :yes would otherwise override every visible :no (#80394). Mode switches- ;; delete these rows, but serialization imports and API writes for hidden- ;; groups can recreate them. A mode change through `PUT /api/setting` can- ;; leave them behind. They can also remain on instances that switched modes- ;; before this fix.- (metabot-perms/visible-groups-clause- (metabot-settings/metabot-advanced-permissions))]})+ ;; Ignore permission rows for groups hidden by the active mode. An unseen :yes would otherwise override every+ ;; visible :no (#80394). Mode switches delete these rows, but serialization imports and API writes for hidden+ ;; groups can recreate them. A mode change through `PUT /api/setting` can leave them behind. They can also+ ;; remain on instances that switched modes before this fix.+ (let [stored (metabot.db/visible-permissions-for-user user-id (metabot-settings/metabot-advanced-permissions))by-type (group-by :perm_type stored)](reduce-kv(fn [acc perm-type default-value]diff --git a/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.clj b/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.cljindex 47f839d529f..fed977d6076 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/task/ai_usage_trimmer.clj@@ -5,10 +5,10 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.metabot.db :as metabot.db][metabase.metabot.settings :as metabot.settings][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(org.quartz DisallowConcurrentExecution)))@@ -25,7 +25,7 @@(do(log/infof "Trimming AI usage log rows older than %d days." (long retention-days))(let [cutoff (t/minus (t/offset-date-time) (t/days (long retention-days)))- deleted (t2/delete! :model/AiUsageLog {:where [:< :created_at cutoff]})]+ deleted (metabot.db/delete-usage-logs-created-before! cutoff)](log/infof "AI usage log cleanup complete. Deleted %d rows." (or deleted 0)))))))(task/defjob ^{DisallowConcurrentExecution truediff --git a/enterprise/backend/src/metabase_enterprise/metabot/tools/dependencies.clj b/enterprise/backend/src/metabase_enterprise/metabot/tools/dependencies.cljindex ab53a85c3b9..fe0add3e37c 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/tools/dependencies.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/tools/dependencies.clj@@ -1,12 +1,12 @@(ns metabase-enterprise.metabot.tools.dependencies(:require[metabase-enterprise.dependencies.core :as dependencies]+ [metabase-enterprise.metabot.db :as metabot.db][metabase.api.common :as api][metabase.lib-be.core :as lib-be][metabase.metabot.tools.util :as metabot.tools.u][metabase.models.interface :as mi]- [metabase.premium-features.core :refer [defenterprise]]- [toucan2.core :as t2]))+ [metabase.premium-features.core :refer [defenterprise]]))(def ^:private ^:dynamic *max-reported-broken-transforms* 10)@@ -22,13 +22,13 @@(disj broken-transform-ids edited-transform-id)))(take *max-reported-broken-transforms* broken-transform-ids))broken-transforms (when (seq transforms-to-report)- (->> (t2/select :model/Transform :id [:in transforms-to-report])+ (->> (metabot.db/transforms transforms-to-report)(filter mi/can-read?)(map #(select-keys % [:id :name]))))broken-card-ids (set (keys card-errors))cards-to-report (take *max-reported-broken-transforms* broken-card-ids)broken-cards (when (seq cards-to-report)- (->> (t2/select :model/Card :id [:in cards-to-report])+ (->> (metabot.db/cards cards-to-report)(filter mi/can-read?)(map #(select-keys % [:id :name]))))]{:success (empty? broken-transform-ids)@@ -50,7 +50,7 @@:feature :none[{:keys [id source]}](try- (let [transform-to-check (api/check-404 (t2/select-one :model/Transform :id id))+ (let [transform-to-check (api/check-404 (metabot.db/transform id))_ (api/read-check transform-to-check)result (if (= (keyword (:type source)) :query)(let [database-id (-> source :query :database)diff --git a/enterprise/backend/src/metabase_enterprise/metabot/usage.clj b/enterprise/backend/src/metabase_enterprise/metabot/usage.cljindex 6105ee78c54..4304476828b 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/usage.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/usage.clj@@ -2,13 +2,13 @@"Enterprise implementation of metabot usage logging and limit checking."(:require[clojure.core.memoize :as memoize]+ [metabase-enterprise.metabot.db :as metabot.db][metabase-enterprise.metabot.models.metabot-group-limit :as group-limit][metabase-enterprise.metabot.models.metabot-instance-limit :as instance-limit][metabase-enterprise.metabot.settings :as metabot.settings][metabase.api.common :as api][metabase.premium-features.core :refer [defenterprise]]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.time DayOfWeek LocalDate YearMonth ZoneOffset)(java.time.temporal TemporalAdjusters)))@@ -68,20 +68,20 @@(let [cache-creation (or cache-creation-tokens 0)cache-read (or cache-read-tokens 0)total-tokens (+ prompt-tokens completion-tokens)]- (t2/insert! :model/AiUsageLog- {:source source- :model model- :prompt_tokens prompt-tokens- :completion_tokens completion-tokens- :total_tokens total-tokens- :cache_creation_tokens cache-creation- :cache_read_tokens cache-read- :user_id (or user-id api/*current-user-id*)- :tenant_id (or tenant-id (some-> api/*current-user* deref :tenant_id))- :conversation_id conversation-id- :profile_id (some-> profile-id name)- :request_id request-id- :ai_proxied ai-proxied}))+ (metabot.db/insert-usage-log!+ {:source source+ :model model+ :prompt_tokens prompt-tokens+ :completion_tokens completion-tokens+ :total_tokens total-tokens+ :cache_creation_tokens cache-creation+ :cache_read_tokens cache-read+ :user_id (or user-id api/*current-user-id*)+ :tenant_id (or tenant-id (some-> api/*current-user* deref :tenant_id))+ :conversation_id conversation-id+ :profile_id (some-> profile-id name)+ :request_id request-id+ :ai_proxied ai-proxied}))(catch Exception e(log/warnf "Failed to log LLM usage to ai_usage_log: %s" (ex-message e))))))@@ -99,34 +99,25 @@ZoneOffset/UTC)))(defn- usage-query- "Query ai_usage_log for current-period usage. `where-clauses` are additional HoneySQL where conditions.+ "Query ai_usage_log for current-period usage, narrowed by the optional `user-id` and `tenant-id`.Returns a token sum or row count depending on `metabot-limit-unit`."- [where-clauses]+ [& {:keys [user-id tenant-id]}](let [limit-type (metabot.settings/metabot-limit-unit)- start (period-start)- base-where [:and- [:>= :created_at start]]- full-where (if (seq where-clauses)- (into base-where where-clauses)- base-where)]+ start (period-start)](case limit-type:tokens- (quot (or (:sum (t2/query-one {:select [[[:sum :total_tokens] :sum]]- :from [:ai_usage_log]- :where full-where}))+ (quot (or (:sum (metabot.db/usage-token-sum start user-id tenant-id))0)1000000):messages- (:cnt (t2/query-one {:select [[[:count :*] :cnt]]- :from [:ai_usage_log]- :where full-where})))))+ (:cnt (metabot.db/usage-message-count start user-id tenant-id)))))(defn- check-instance-limit"Check the instance-wide limit. Returns an error message string if exceeded, nil otherwise."[](when-let [max-usage (:max_usage (instance-limit/instance-limit nil))]- (let [usage (usage-query [])]+ (let [usage (usage-query)](when (>= usage max-usage)(metabot.settings/metabot-quota-reached-message)))))@@ -135,7 +126,7 @@[tenant-id](when tenant-id(when-let [max-usage (:max_usage (instance-limit/instance-limit tenant-id))]- (let [usage (usage-query [[:= :tenant_id tenant-id]])]+ (let [usage (usage-query :tenant-id tenant-id)](when (>= usage max-usage)(metabot.settings/metabot-quota-reached-message))))))@@ -144,7 +135,7 @@[user-id](when user-id(when-let [max-usage (group-limit/limit-for-user user-id)]- (let [usage (usage-query [[:= :user_id user-id]])]+ (let [usage (usage-query :user-id user-id)](when (>= usage max-usage)(metabot.settings/metabot-quota-reached-message))))))diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.cljindex 57389bef7b0..75fa4758bad 100644--- a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj@@ -1,20 +1,17 @@(ns metabase-enterprise.metabot-analytics.conversations- "Data-access layer for the metabot analytics API. Builds and runs the- HoneySQL queries that back the `/api/ee/metabot-analytics/conversations`- endpoints, and assembles the response shapes the handlers return.+ "Data-access layer for the metabot analytics API. Delegates queries to+ `metabase-enterprise.metabot-analytics.db` and assembles the response shapes+ the `/api/ee/metabot-analytics/conversations` handlers return.Handlers in `metabase-enterprise.metabot-analytics.api` should stay thin —auth, param coercion, and delegation to the functions here."(:require+ [metabase-enterprise.metabot-analytics.db :as metabot-analytics.db][metabase-enterprise.metabot-analytics.queries :as analytics.queries][metabase.api.common :as api][metabase.metabot.persistence :as metabot-persistence][metabase.metabot.tools :as metabot.tools]- [metabase.permissions.core :as perms]- [metabase.query-processor.parameters.dates :as qp.parameters.dates][metabase.slackbot.api :as slackbot.api]- [metabase.util.date-2 :as u.date]- [metabase.util.i18n :refer [tru]][toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -22,103 +19,12 @@(def ^:private default-limit 50)(def ^:private default-offset 0)-(defn- date-string->constraints- "Parse a serialized date-param string into half-open HoneySQL predicates on `col`.- Throws 400 on a malformed string. Returns nil when no bound is produced."- [col date-string]- (let [{:keys [start end]}- (try- (qp.parameters.dates/date-string->range date-string {:inclusive-end? false})- (catch Exception e- (throw (ex-info (tru "Failed to parse datetime value: {0}" date-string)- {:status-code 400}- e))))- start (some-> start u.date/parse)- end (some-> end u.date/parse)- parts (cond-> []- start (conj [:>= col start])- end (conj [:< col end]))]- (when (seq parts)- (into [:and] parts))))--(defn- list-where-clause- "Compose a conjunctive WHERE from optional filters. Returns `nil` when no- filter applies so the caller can `cond->` cleanly."- [{:keys [user-id group-id tenant-id date]}]- (let [clauses (cond-> []- user-id (conj [:= :c.user_id user-id])- (seq date) (conj (date-string->constraints :c.created_at date))- (and group-id (not= group-id (:id (perms/all-users-group))))- (conj [:exists ^:allow-subquery {:select [1]- :from [[:permissions_group_membership :pgm]]- :where [:and- [:= :pgm.user_id :c.user_id]- [:= :pgm.group_id group-id]]}])- tenant-id- (conj [:exists ^:allow-subquery {:select [1]- :from [[:core_user :u]]- :where [:and- [:= :u.id :c.user_id]- [:= :u.tenant_id tenant-id]]}]))- clauses (remove nil? clauses)]- (when (seq clauses)- (into [:and] clauses))))-(defn- trim-user"Trim a hydrated core_user down to the minimal shape the frontend uses(`MetabotUserInfo`)."[user](some-> user (select-keys [:id :email :first_name :last_name :tenant_id])))-(def ^:private sort-columns- "Allow-list of API sort keys → vectors of HoneySQL ORDER BY expressions (sans- direction). A vector lets a single sort key emit multiple ORDER BY terms that- share the same direction (e.g. user sort orders by first_name then last_name)."- {"created_at" [:c.created_at]- "title" [:c.title]- "message_count" [:message_count]- "total_tokens" [:total_tokens]- "cache_read_tokens" [:cache_read_tokens]- "user" [[:lower [:min :u.first_name]]- [:lower [:min :u.last_name]]]- "profile_id" [:profile_id]- "ip_address" [:c.ip_address]})--(def ^:private list-query- "Conversation rows with aggregate stats, including deleted attempts. Messages- a fork copied in from its origin are counted here — the list describes the- thread as the reader sees it. `v_metabot_conversations.new_message_count` is- the usage-metric counterpart that leaves them out."- {:select [:c.*- [[:count :m.id] :message_count]- [[:count [:case [:= :m.role "user"] 1]] :user_message_count]- [[:count [:case [:= :m.role "assistant"] 1]] :assistant_message_count]- [[:coalesce [:sum :m.total_tokens] 0] :total_tokens]- [[:max :m.created_at] :last_message_at]- [^:allow-subquery {:select [:mm.profile_id]- :from [[:metabot_message :mm]]- :where [:and- [:= :mm.conversation_id :c.id]- [:= :mm.role "assistant"]]- :order-by [[:mm.created_at :asc] [:mm.id :asc]]- :limit 1}- :profile_id]- ;; Cache tokens are only recorded per LLM call in `ai_usage_log`- ;; (`metabot_message` stores prompt+completion only), so this is a- ;; correlated subquery rather than another one-to-many join, which- ;; would fan out against the `metabot_message` join and inflate- ;; every aggregate above.- [[:coalesce- ^:allow-subquery {:select [[[:sum :aul.cache_read_tokens]]]- :from [[:ai_usage_log :aul]]- :where [:= :aul.conversation_id :c.id]}- 0]- :cache_read_tokens]]- :from [[:metabot_conversation :c]]- :left-join [[:metabot_message :m] [:= :m.conversation_id :c.id]- [:core_user :u] [:= :u.id :c.user_id]]- :group-by [:c.id]})-(defn- row->summary"Reshape a raw list-query row into the response shape the frontend expects:renames the conversation's `:id` to `:conversation_id`, trims the hydrated@@ -152,8 +58,7 @@[rows](let [conversation-ids (map :id rows)messages-by-conv (when (seq conversation-ids)- (->> (t2/select [:model/MetabotMessage :conversation_id :data :data_version]- :conversation_id [:in conversation-ids])+ (->> (metabot-analytics.db/message-data-for-conversations conversation-ids)(group-by :conversation_id)))](map (fn [row](let [msgs (get messages-by-conv (:id row) [])]@@ -169,25 +74,17 @@and a serialized `date` parameter string, plus sorting by an allow-listed`sort-by` column in either direction (defaults to newest-first)."[{:keys [limit offset user-id group-id tenant-id date sort-by sort-dir]}]- (let [limit (or limit default-limit)- offset (or offset default-offset)- where (list-where-clause {:user-id user-id- :group-id group-id- :tenant-id tenant-id- :date date})- sort-exprs (get sort-columns sort-by [:c.created_at])- direction (if (= sort-dir "asc") :asc :desc)- order-by (conj (mapv #(vector % direction) sort-exprs)- [:c.id :asc])- total (:count (t2/query-one (cond-> {:select [[[:count :*] :count]]- :from [[:metabot_conversation :c]]}- where (assoc :where where))))- rows (t2/select :model/MetabotConversation- (cond-> (assoc list-query- :order-by order-by- :limit limit- :offset offset)- where (assoc :where where)))]+ (let [limit (or limit default-limit)+ offset (or offset default-offset)+ direction (if (= sort-dir "asc") :asc :desc)+ params {:user-id user-id :group-id group-id :tenant-id tenant-id :date date}+ total (metabot-analytics.db/conversation-count params)+ rows (metabot-analytics.db/list-conversations+ (assoc params+ :sort-by sort-by+ :sort-direction direction+ :limit limit+ :offset offset))]{:data (->> (t2/hydrate rows :user)hydrate-tool-counts(map row->summary))@@ -206,23 +103,7 @@thread can yield multiple rows for the same message — so the submitter ishydrated as `:user` for display."[conversation-id]- (let [rows (t2/select :model/MetabotFeedback- {:select [:metabot_feedback.id- :metabot_feedback.message_id- :metabot_feedback.user_id- [:mm.external_id :external_id]- :metabot_feedback.positive- :metabot_feedback.issue_type- :metabot_feedback.freeform_feedback- :metabot_feedback.created_at- :metabot_feedback.updated_at]- :from [:metabot_feedback]- :join [[:metabot_message :mm]- [:= :mm.id :metabot_feedback.message_id]]- :where [:= :mm.conversation_id conversation-id]- :order-by [[:metabot_feedback.created_at :asc]- [:metabot_feedback.message_id :asc]- [:metabot_feedback.user_id :asc]]})]+ (let [rows (metabot-analytics.db/feedback-for-conversation conversation-id)](t2/hydrate rows :user)))(defn- fork-boundary-external-id@@ -239,11 +120,9 @@(defn fetch-conversation-detail"Fetch a conversation detail or throw a 404."[conversation-id]- (let [conversation (t2/select-one :model/MetabotConversation :id conversation-id)]+ (let [conversation (metabot-analytics.db/conversation conversation-id)](api/check-404 conversation)- (let [all-messages (t2/select :model/MetabotMessage- :conversation_id conversation-id- {:order-by [[:created_at :asc] [:id :asc]]})+ (let [all-messages (metabot-analytics.db/messages-for-conversation conversation-id)forked-from (:forked_from_conversation_id conversation)hydrated (t2/hydrate conversation :user)]{:conversation_id (:id conversation)diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/db.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/db.cljnew file mode 100644index 00000000000..5d34d1fab37--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/db.clj@@ -0,0 +1,161 @@+(ns metabase-enterprise.metabot-analytics.db+ "Application database queries for the metabot-analytics module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.permissions.core :as perms]+ [metabase.query-processor.parameters.dates :as qp.parameters.dates]+ [metabase.util.date-2 :as u.date]+ [metabase.util.i18n :refer [tru]]+ [toucan2.core :as t2]))++(defn conversation+ "The MetabotConversation with `conversation-id`, or nil."+ [conversation-id]+ (t2/select-one :model/MetabotConversation :id conversation-id))++(defn- date-range-expr+ "A half-open predicate on `col` from the serialized date-param string `date-string`. Throws 400 on a malformed+ string. Returns nil when no bound is produced."+ [col date-string]+ (let [{:keys [start end]}+ (try+ (qp.parameters.dates/date-string->range date-string {:inclusive-end? false})+ (catch Exception e+ (throw (ex-info (tru "Failed to parse datetime value: {0}" date-string)+ {:status-code 400}+ e))))+ start (some-> start u.date/parse)+ end (some-> end u.date/parse)+ parts (cond-> []+ start (conj [:>= col start])+ end (conj [:< col end]))]+ (when (seq parts)+ (into [:and] parts))))++(defn- conversation-list-expr+ "The `:where` fragment restricting `metabot_conversation` rows aliased `:c` to `user-id`, `group-id`, `tenant-id`,+ and `date` (each nil for no restriction; `date` is a serialized date-param string). Returns nil when none apply."+ [{:keys [user-id group-id tenant-id date]}]+ (let [exprs (cond-> []+ user-id (conj [:= :c.user_id user-id])+ (seq date) (conj (date-range-expr :c.created_at date))+ (and group-id (not= group-id (:id (perms/all-users-group))))+ (conj [:exists ^:allow-subquery {:select [1]+ :from [[:permissions_group_membership :pgm]]+ :where [:and+ [:= :pgm.user_id :c.user_id]+ [:= :pgm.group_id group-id]]}])+ tenant-id+ (conj [:exists ^:allow-subquery {:select [1]+ :from [[:core_user :u]]+ :where [:and+ [:= :u.id :c.user_id]+ [:= :u.tenant_id tenant-id]]}]))+ exprs (remove nil? exprs)]+ (when (seq exprs)+ (into [:and] exprs))))++(def ^:private sort-columns+ "Allow-list of API sort keys → vectors of ORDER BY expressions (sans+ direction). A vector lets a single sort key emit multiple ORDER BY terms that+ share the same direction (e.g. user sort orders by first_name then last_name)."+ {"created_at" [:c.created_at]+ "title" [:c.title]+ "message_count" [:message_count]+ "total_tokens" [:total_tokens]+ "cache_read_tokens" [:cache_read_tokens]+ "user" [[:lower [:min :u.first_name]]+ [:lower [:min :u.last_name]]]+ "profile_id" [:profile_id]+ "ip_address" [:c.ip_address]})++(def ^:private conversation-list-select+ "Conversation rows with aggregate stats, including deleted attempts. Messages+ a fork copied in from its origin are counted here — the list describes the+ thread as the reader sees it. `v_metabot_conversations.new_message_count` is+ the usage-metric counterpart that leaves them out."+ {:select [:c.*+ [[:count :m.id] :message_count]+ [[:count [:case [:= :m.role "user"] 1]] :user_message_count]+ [[:count [:case [:= :m.role "assistant"] 1]] :assistant_message_count]+ [[:coalesce [:sum :m.total_tokens] 0] :total_tokens]+ [[:max :m.created_at] :last_message_at]+ [^:allow-subquery {:select [:mm.profile_id]+ :from [[:metabot_message :mm]]+ :where [:and+ [:= :mm.conversation_id :c.id]+ [:= :mm.role "assistant"]]+ :order-by [[:mm.created_at :asc] [:mm.id :asc]]+ :limit 1}+ :profile_id]+ ;; Cache tokens are only recorded per LLM call in `ai_usage_log`+ ;; (`metabot_message` stores prompt+completion only), so this is a+ ;; correlated subquery rather than another one-to-many join, which+ ;; would fan out against the `metabot_message` join and inflate+ ;; every aggregate above.+ [[:coalesce+ ^:allow-subquery {:select [[[:sum :aul.cache_read_tokens]]]+ :from [[:ai_usage_log :aul]]+ :where [:= :aul.conversation_id :c.id]}+ 0]+ :cache_read_tokens]]+ :from [[:metabot_conversation :c]]+ :left-join [[:metabot_message :m] [:= :m.conversation_id :c.id]+ [:core_user :u] [:= :u.id :c.user_id]]+ :group-by [:c.id]})++(defn list-conversations+ "A page of conversation summary rows (see [[conversation-list-select]]), restricted to `user-id`, `group-id`,+ `tenant-id`, and `date` (each nil for no restriction), sorted by the allow-listed `sort-by` column name in+ `sort-direction` (`:asc` or `:desc`), skipping `offset` and returning up to `limit`."+ [{:keys [user-id group-id tenant-id date sort-by sort-direction offset limit]}]+ (let [where (conversation-list-expr {:user-id user-id :group-id group-id :tenant-id tenant-id :date date})+ sort-exprs (get sort-columns sort-by [:c.created_at])+ order-by (conj (mapv #(vector % sort-direction) sort-exprs)+ [:c.id :asc])]+ (t2/select :model/MetabotConversation+ (cond-> (assoc conversation-list-select+ :order-by order-by+ :limit limit+ :offset offset)+ where (assoc :where where)))))++(defn conversation-count+ "The total count of conversations matching the same criteria as [[list-conversations]] (ignoring sort, offset,+ and limit)."+ [{:keys [user-id group-id tenant-id date]}]+ (let [where (conversation-list-expr {:user-id user-id :group-id group-id :tenant-id tenant-id :date date})]+ (:count (t2/query-one (cond-> {:select [[[:count :*] :count]]+ :from [[:metabot_conversation :c]]}+ where (assoc :where where))))))++(defn messages-for-conversation+ "The MetabotMessages of the MetabotConversation with `conversation-id`, oldest first."+ [conversation-id]+ (t2/select :model/MetabotMessage :conversation_id conversation-id {:order-by [[:created_at :asc] [:id :asc]]}))++(defn message-data-for-conversations+ "The conversation, data, and data version of the MetabotMessages of the MetabotConversations with+ `conversation-ids`."+ [conversation-ids]+ (t2/select [:model/MetabotMessage :conversation_id :data :data_version] :conversation_id [:in conversation-ids]))++(defn feedback-for-conversation+ "The MetabotFeedback rows on the messages of the MetabotConversation with `conversation-id`, oldest first."+ [conversation-id]+ (t2/select :model/MetabotFeedback+ {:select [:metabot_feedback.id+ :metabot_feedback.message_id+ :metabot_feedback.user_id+ [:mm.external_id :external_id]+ :metabot_feedback.positive+ :metabot_feedback.issue_type+ :metabot_feedback.freeform_feedback+ :metabot_feedback.created_at+ :metabot_feedback.updated_at]+ :from [:metabot_feedback]+ :join [[:metabot_message :mm] [:= :mm.id :metabot_feedback.message_id]]+ :where [:= :mm.conversation_id conversation-id]+ :order-by [[:metabot_feedback.created_at :asc]+ [:metabot_feedback.message_id :asc]+ [:metabot_feedback.user_id :asc]]}))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/core.clj b/enterprise/backend/src/metabase_enterprise/mfa/core.cljindex 0b0c317ba8f..5f0f040e8d3 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/core.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/core.clj@@ -4,6 +4,7 @@Consumers outside this module must go through this namespace; they must not require mfa.gate,or mfa.settings directly."(:require+ [metabase-enterprise.mfa.db :as mfa.db][metabase-enterprise.mfa.gate :as gate][metabase-enterprise.mfa.settings][metabase-enterprise.mfa.verification :as verification]@@ -11,8 +12,7 @@[metabase.premium-features.core :refer [defenterprise]][metabase.util.i18n :refer [tru]][metabase.util.log :as log]- [potemkin :as p]- [toucan2.core :as t2]))+ [potemkin :as p]))(comment metabase-enterprise.mfa.settings/keep-me)@@ -59,7 +59,7 @@;; nil = no confirmed enrollment — same message, no oracle semantics(throw (ex-info (tru "Authentication session expired. Please log in again."){:status-code 401})))- user-email (t2/select-one-fn :email :model/User :id user-id)]+ user-email (mfa.db/user-email user-id)](try(messages/send-mfa-login-code-email! user-email code)(catch Throwable ediff --git a/enterprise/backend/src/metabase_enterprise/mfa/db.clj b/enterprise/backend/src/metabase_enterprise/mfa/db.cljnew file mode 100644index 00000000000..b1659f07de7--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mfa/db.clj@@ -0,0 +1,127 @@+(ns metabase-enterprise.mfa.db+ "Application database queries for the mfa module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for transactions."+ (:require+ [clojure.string :as str]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(def ^:private totp-provider "totp")++(def ^:private confirmed-totp-exists+ ;; enrollment state is the auth_identity.confirmed_at COLUMN (queryable), not the encrypted credentials JSON+ [:exists ^:allow-subquery {:select [1]+ :from [:auth_identity]+ :where [:and+ [:= :auth_identity.user_id :core_user.id]+ [:= :auth_identity.provider totp-provider]+ [:not= :auth_identity.confirmed_at nil]]}])++(def ^:private unenrolled-user-where+ ;; active personal users without a confirmed TOTP enrollment+ [:and+ [:= :core_user.is_active true]+ [:= :core_user.type "personal"]+ [:not confirmed-totp-exists]])++(def ^:private list-columns+ [:id :email :first_name :last_name :sso_source :is_active :is_superuser])++(def ^:private enrolled-at-select+ ;; a correlated scalar subselect rather than a join: the unique (user_id, provider) constraint guarantees at most+ ;; one row, and joining would force qualifying every selected column, since auth_identity also has+ ;; id/created_at/updated_at+ [[^:allow-subquery {:select [:auth_identity.confirmed_at]+ :from [:auth_identity]+ :where [:and+ [:= :auth_identity.user_id :core_user.id]+ [:= :auth_identity.provider totp-provider]]}+ :enrolled_at]])++(defn- user-list-where+ "Where clause of the admin user lists: enrolled users (deliberately unfiltered beyond the enrollment itself, so+ deactivated users appear and an admin can still remove their enrollment) or unenrolled active personal users,+ optionally narrowed by a name or email `search` the way the People page searches. Uses untable-qualified+ `:%lower.x` columns since `.` in `:%lower.x` splits on the column name, not a table qualifier — fine here+ because neither list query joins."+ [enrolled? search]+ (cond-> [:and (if enrolled? confirmed-totp-exists unenrolled-user-where)]+ (not (str/blank? search))+ (conj (let [pattern (h2x/like-substring search)]+ [:or+ [:like :%lower.first_name pattern]+ [:like :%lower.last_name pattern]+ [:like :%lower.email pattern]]))))++(defn user+ "The User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User :id user-id))++(defn user-email+ "The email of the User with `user-id`."+ [user-id]+ (t2/select-one-fn :email :model/User :id user-id))++(defn lock-user+ "The `:id` row of the User with `user-id`, locked for update."+ [user-id]+ (t2/select-one [:model/User :id] :id user-id {:for :update}))++(defn totp-identity+ "The TOTP AuthIdentity of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/AuthIdentity :user_id user-id :provider totp-provider))++(defn lock-totp-identity+ "The TOTP AuthIdentity of the User with `user-id`, locked for update, or nil."+ [user-id]+ (t2/select-one :model/AuthIdentity :user_id user-id :provider totp-provider {:for :update}))++(defn password-credentials+ "The password credentials of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one-fn :credentials :model/AuthIdentity :user_id user-id :provider "password"))++(defn insert-auth-identity!+ "Insert the AuthIdentity `row`."+ [row]+ (t2/insert! :model/AuthIdentity row))++(defn update-auth-identity!+ "Apply `changes` to the AuthIdentity with `auth-identity-id`."+ [auth-identity-id changes]+ (t2/update! :model/AuthIdentity auth-identity-id changes))++(defn delete-totp-identity!+ "Delete the TOTP AuthIdentity of the User with `user-id`, returning the number deleted."+ [user-id]+ (t2/delete! :model/AuthIdentity :user_id user-id :provider totp-provider))++(defn confirmed-totp-count+ "The number of confirmed TOTP enrollments."+ []+ (t2/count :model/AuthIdentity :provider totp-provider :confirmed_at [:not= nil]))++(defn unenrolled-user-count+ "The number of active personal Users without a confirmed TOTP enrollment."+ []+ (t2/count :model/User {:where unenrolled-user-where}))++(defn user-list+ "The name-ordered admin list of enrolled (with their enrollment time) or unenrolled Users matching `search`, paged+ by the optional `limit` and `offset`."+ [enrolled? search limit offset]+ (t2/select :model/User+ (cond-> {:select (cond-> list-columns enrolled? (into enrolled-at-select))+ :where (user-list-where enrolled? search)+ :order-by [[:%lower.first_name :asc]+ [:%lower.last_name :asc]+ [:id :asc]]}+ ;; a nil limit would emit `LIMIT NULL`+ limit (assoc :limit limit :offset offset))))++(defn user-list-count+ "The number of enrolled or unenrolled Users matching `search`."+ [enrolled? search]+ (t2/count :model/User {:where (user-list-where enrolled? search)}))diff --git a/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj b/enterprise/backend/src/metabase_enterprise/mfa/enrollment.cljindex 9c08b54ea14..dcb50fed76c 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/enrollment.clj@@ -13,6 +13,7 @@`metabase-enterprise.mfa.verification`."(:require[java-time.api :as t]+ [metabase-enterprise.mfa.db :as mfa.db][metabase-enterprise.mfa.recovery-codes :as recovery-codes][metabase-enterprise.mfa.totp :as totp][metabase-enterprise.mfa.verification :as verification]@@ -45,19 +46,16 @@;; serialize concurrent enrollments for the same user by locking the User row: with no totp;; row yet there is nothing else to lock, and racing inserts would abort the transaction on;; the unique (user_id, provider) constraint- (t2/select-one [:model/User :id] :id user-id {:for :update})- (let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider "totp"- {:for :update})]+ (mfa.db/lock-user user-id)+ (let [auth-identity (mfa.db/lock-totp-identity user-id)](when-not (some-> auth-identity verification/confirmed?)(let [secret (totp/generate-secret)credentials {:secret secret}](if auth-identity- (t2/update! :model/AuthIdentity (:id auth-identity) {:credentials credentials})- (t2/insert! :model/AuthIdentity {:user_id user-id- :provider "totp"- :credentials credentials}))+ (mfa.db/update-auth-identity! (:id auth-identity) {:credentials credentials})+ (mfa.db/insert-auth-identity! {:user_id user-id+ :provider "totp"+ :credentials credentials}))secret)))))(defn confirm-enrollment!@@ -67,26 +65,23 @@failure or when there is no pending enrollment."[user-id code](t2/with-transaction [_conn]- (when-let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider "totp"- {:for :update})]+ (when-let [auth-identity (mfa.db/lock-totp-identity user-id)](when-not (verification/confirmed? auth-identity)(when-let [secret (verification/stored-secret auth-identity)](when-let [step (totp/matching-time-step secret code)](let [codes (recovery-codes/generate-codes)]- (t2/update! :model/AuthIdentity (:id auth-identity)- {:confirmed_at (t/instant)- :credentials (assoc (:credentials auth-identity)- :last_used_step step- :recovery_codes (mapv u.password/hash-bcrypt codes))})+ (mfa.db/update-auth-identity! (:id auth-identity)+ {:confirmed_at (t/instant)+ :credentials (assoc (:credentials auth-identity)+ :last_used_step step+ :recovery_codes (mapv u.password/hash-bcrypt codes))})codes)))))))(defn disable!"Remove `user-id`'s TOTP enrollment entirely (re-auth is the caller's responsibility). True whensomething was removed."[user-id]- (pos? (t2/delete! :model/AuthIdentity :user_id user-id :provider "totp")))+ (pos? (mfa.db/delete-totp-identity! user-id)));;; -------------------------------------------------- Recovery-code management --------------------------------------------------@@ -96,15 +91,12 @@plaintext; only bcrypt hashes are stored. Nil when the user has no confirmed enrollment."[user-id](t2/with-transaction [_conn]- (when-let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider "totp"- {:for :update})]+ (when-let [auth-identity (mfa.db/lock-totp-identity user-id)](when (verification/confirmed? auth-identity)(let [codes (recovery-codes/generate-codes)]- (t2/update! :model/AuthIdentity (:id auth-identity)- {:credentials (assoc (:credentials auth-identity)- :recovery_codes (mapv u.password/hash-bcrypt codes))})+ (mfa.db/update-auth-identity! (:id auth-identity)+ {:credentials (assoc (:credentials auth-identity)+ :recovery_codes (mapv u.password/hash-bcrypt codes))})codes)))))(defn recovery-codes-remainingdiff --git a/enterprise/backend/src/metabase_enterprise/mfa/management.clj b/enterprise/backend/src/metabase_enterprise/mfa/management.cljindex b62b1f816ec..4dbb4d9ccfa 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/management.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/management.clj@@ -11,6 +11,7 @@recovery code), so a stolen password alone can never remove or weaken 2FA."(:require[clojure.string :as str]+ [metabase-enterprise.mfa.db :as mfa.db][metabase-enterprise.mfa.enrollment :as enrollment][metabase-enterprise.mfa.settings :as mfa.settings][metabase-enterprise.mfa.throttling :as mfa.throttling]@@ -25,7 +26,6 @@[metabase.request.core :as request][metabase.sso.core :as sso][metabase.util.encryption :as encryption]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [tru]][metabase.util.log :as log][metabase.util.malli.schema :as ms]@@ -67,13 +67,13 @@(boolean(when-not (str/blank? password)(or (when-let [{:keys [password_hash password_salt]}- (t2/select-one-fn :credentials :model/AuthIdentity :user_id user-id :provider "password")]+ (mfa.db/password-credentials user-id)](and password_hash (u.password/verify-password password password_salt password_hash)))(when (sso/ldap-enabled);; an unreachable directory fails closed: re-auth is denied (the user retries when the;; directory is back; admin/remove needs no re-auth), never an unhandled 500(try- (when-let [user-email (t2/select-one-fn :email :model/User user-id)]+ (when-let [user-email (mfa.db/user-email user-id)](when-let [user-info (sso/find-user user-email)](sso/verify-password user-info password)))(catch Exception e@@ -113,7 +113,7 @@(let [secret (or (enrollment/start-enrollment! api/*current-user-id*)(throw (ex-info (tru "Two-factor authentication is already set up. Disable it before re-enrolling."){:status-code 400})))- user-email (t2/select-one-fn :email :model/User api/*current-user-id*)]+ user-email (mfa.db/user-email api/*current-user-id*)]{:secret secret:otpauth_uri (totp/otpauth-uri {:issuer (or (appearance/site-name) "Metabase"):account user-email@@ -131,7 +131,7 @@(fn [](or (enrollment/confirm-enrollment! api/*current-user-id* code)(throw (invalid-code-ex)))))- user (t2/select-one :model/User :id api/*current-user-id*)]+ user (mfa.db/user api/*current-user-id*)](messages/send-mfa-enabled-email! (:email user))(events/publish-event! :event/mfa-enrolled {:object user}){:recovery_codes codes}))@@ -149,7 +149,7 @@(when-not (verification/verify-attempt! api/*current-user-id* code nil)(throw (invalid-code-ex)))(enrollment/disable! api/*current-user-id*))))- (let [user (t2/select-one :model/User :id api/*current-user-id*)]+ (let [user (mfa.db/user api/*current-user-id*)](messages/send-mfa-disabled-email! (:email user))(events/publish-event! :event/mfa-disabled {:object user}))api/generic-204-no-content)@@ -191,35 +191,11 @@(throw (ex-info (tru "You cannot administratively remove your own two-factor authentication. Please use the normal removal method in your account settings."){:status-code 400})))(when (enrollment/disable! user-id)- (let [user (t2/select-one :model/User :id user-id)]+ (let [user (mfa.db/user user-id)](messages/send-mfa-removed-by-admin-email! (:email user))(events/publish-event! :event/mfa-disabled {:object user})))api/generic-204-no-content)-(def ^:private confirmed-totp-exists- ;; enrollment state is the auth_identity.confirmed_at COLUMN (queryable), not the encrypted- ;; credentials JSON- [:exists ^:allow-subquery {:select [1]- :from [:auth_identity]- :where [:and- [:= :auth_identity.user_id :core_user.id]- [:= :auth_identity.provider "totp"]- [:not= :auth_identity.confirmed_at nil]]}])--(def ^:private unenrolled-user-where- ;; active personal users without a confirmed TOTP enrollment- [:and- [:= :core_user.is_active true]- [:= :core_user.type "personal"]- [:not confirmed-totp-exists]])--(def ^:private enrolled-user-where- ;; Deliberately unfiltered beyond the enrollment itself, so this matches `enrolled_count`: that- ;; counts auth_identity rows, and the unique (user_id, provider) constraint makes it 1:1 with- ;; users. Deactivated users therefore appear here — correctly, since their enrollment still- ;; exists and an admin can still remove it.- confirmed-totp-exists)-(api.macros/defendpoint :get "/admin/overview" :- [:map[:encryption_key_set :boolean][:enrolled_count :int]@@ -229,57 +205,23 @@[](api/check-superuser){:encryption_key_set (encryption/default-encryption-enabled?)- :enrolled_count (t2/count :model/AuthIdentity :provider "totp" :confirmed_at [:not= nil])- :unenrolled_count (t2/count :model/User {:where unenrolled-user-where})})+ :enrolled_count (mfa.db/confirmed-totp-count)+ :unenrolled_count (mfa.db/unenrolled-user-count)});;; -------------------------------------------------- Admin user lists ---------------------------------------------------(def ^:private list-columns- [:id :email :first_name :last_name :sso_source :is_active :is_superuser])--(def ^:private enrolled-at-select- ;; a correlated scalar subselect rather than a join: the unique (user_id, provider) constraint- ;; guarantees at most one row, and joining would force qualifying every selected column, since- ;; auth_identity also has id/created_at/updated_at- [[^:allow-subquery {:select [:auth_identity.confirmed_at]- :from [:auth_identity]- :where [:and- [:= :auth_identity.user_id :core_user.id]- [:= :auth_identity.provider "totp"]]}- :enrolled_at]])--(defn- search-where- "Mirrors the People page's search (`metabase.users.models.user/query-clause`, which is private).- Note `:%lower.x` splits on `.` and so cannot be table-qualified — fine here because neither list- query joins."- [query]- (when-not (str/blank? query)- (let [pattern (h2x/like-substring query)]- [:or- [:like :%lower.first_name pattern]- [:like :%lower.last_name pattern]- [:like :%lower.email pattern]])))-(defn- user-list-response- "Name-ordered, offset-paged list of users matching `where`, in the standard- {:data :total :limit :offset} envelope."- [where extra-select query]- (let [search (search-where query)- where (cond-> [:and where]- search (conj search))]- {:data (t2/select :model/User- (cond-> {:select (into list-columns extra-select)- :where where- :order-by [[:%lower.first_name :asc]- [:%lower.last_name :asc]- [:id :asc]]}- ;; (request/limit) is nil on an unpaged request, and `:limit nil` would- ;; emit `LIMIT NULL`- (request/paged?) (assoc :limit (request/limit)- :offset (request/offset))))- :total (t2/count :model/User {:where where})- :limit (request/limit)- :offset (request/offset)}))+ "Name-ordered, offset-paged list of enrolled or unenrolled users matching the name or email `query`, in the+ standard {:data :total :limit :offset} envelope."+ [enrolled? query]+ {:data (mfa.db/user-list enrolled?+ query+ ;; (request/limit) is nil on an unpaged request+ (when (request/paged?) (request/limit))+ (when (request/paged?) (request/offset)))+ :total (mfa.db/user-list-count enrolled? query)+ :limit (request/limit)+ :offset (request/offset)})(def ^:private admin-mfa-user-entries[[:id ms/PositiveInt]@@ -321,7 +263,7 @@[_route-params{:keys [query]} :- [:map [:query {:optional true} [:maybe :string]]]](api/check-superuser)- (user-list-response enrolled-user-where enrolled-at-select query))+ (user-list-response true query))(api.macros/defendpoint :get "/admin/unenrolled-users" :- UnenrolledUsersResponse"Admin: active users who have not set up a second factor. Matches `unenrolled_count` from@@ -332,7 +274,7 @@[_route-params{:keys [query]} :- [:map [:query {:optional true} [:maybe :string]]]](api/check-superuser)- (user-list-response unenrolled-user-where nil query))+ (user-list-response false query));;; -------------------------------------------------- Recovery codes --------------------------------------------------diff --git a/enterprise/backend/src/metabase_enterprise/mfa/verification.clj b/enterprise/backend/src/metabase_enterprise/mfa/verification.cljindex f95c9705036..eb33f310e47 100644--- a/enterprise/backend/src/metabase_enterprise/mfa/verification.clj+++ b/enterprise/backend/src/metabase_enterprise/mfa/verification.clj@@ -4,7 +4,7 @@one-time code, atomically consuming whichever credential is presented so a replayed orconcurrently submitted credential can never pass twice.- Row-level helpers (`provider-name`, `totp-identity`, `confirmed?`, `stored-secret`) live here+ Row-level helpers (`totp-identity`, `confirmed?`, `stored-secret`) live hereas the lower layer; `metabase-enterprise.mfa.enrollment` requires this namespace for them.One-time-use state lives in the same `:credentials` JSON column as the enrollment secret:@@ -13,6 +13,7 @@- `:recovery_codes` — bcrypt hashes of unused recovery codes; removed on use.- `:email_otp` — `{:hash ... :exp ...}` bcrypt hash of a pending emailed code; removed on use."(:require+ [metabase-enterprise.mfa.db :as mfa.db][metabase-enterprise.mfa.recovery-codes :as recovery-codes][metabase-enterprise.mfa.totp :as totp][metabase.util.password :as u.password]@@ -26,12 +27,10 @@;; validation accepts its rows (the default `validate` method applies).(derive :provider/totp :metabase.auth-identity.provider/provider)-(def ^:private provider-name "totp")-(defn totp-identity"The AuthIdentity row for `user-id`'s TOTP enrollment, or nil."[user-id]- (t2/select-one :model/AuthIdentity :user_id user-id :provider provider-name))+ (mfa.db/totp-identity user-id))(defn confirmed?"Has `auth-identity` been confirmed (i.e. is it a usable second factor)?@@ -71,8 +70,7 @@the successful verification — otherwise it would stay valid for its remaining ~10-minute TTL,including as re-auth for disable/regenerate."[auth-identity credentials jti]- (t2/update! :model/AuthIdentity (:id auth-identity)- {:credentials (-> credentials (dissoc :email_otp) (consume-jti jti))}))+ (mfa.db/update-auth-identity! (:id auth-identity) {:credentials (-> credentials (dissoc :email_otp) (consume-jti jti))}))(defn- totp-attempt!"When `code` is a valid, not-yet-used TOTP code: consume its time step (RFC 6238 §5.2) and return@@ -126,10 +124,7 @@[user-id code jti](t2/with-transaction [_conn](boolean- (when-let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider provider-name- {:for :update})]+ (when-let [auth-identity (mfa.db/lock-totp-identity user-id)](when (and (confirmed? auth-identity)(not (jti-used? (:credentials auth-identity) jti)))(or (totp-attempt! auth-identity code jti)@@ -142,15 +137,12 @@code for the caller to email, or nil when the user has no confirmed enrollment."[user-id](t2/with-transaction [_conn]- (when-let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider provider-name- {:for :update})]+ (when-let [auth-identity (mfa.db/lock-totp-identity user-id)](when (confirmed? auth-identity)(let [code (format "%06d" (.nextInt (SecureRandom.) 1000000))]- (t2/update! :model/AuthIdentity (:id auth-identity)- {:credentials (assoc (:credentials auth-identity)- :email_otp {:hash (u.password/hash-bcrypt code)- :exp (+ (quot (System/currentTimeMillis) 1000)- (* 10 60))})})+ (mfa.db/update-auth-identity! (:id auth-identity)+ {:credentials (assoc (:credentials auth-identity)+ :email_otp {:hash (u.password/hash-bcrypt code)+ :exp (+ (quot (System/currentTimeMillis) 1000)+ (* 10 60))})})code)))))diff --git a/enterprise/backend/src/metabase_enterprise/permission_debug/db.clj b/enterprise/backend/src/metabase_enterprise/permission_debug/db.cljnew file mode 100644index 00000000000..5feca7177b7--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/permission_debug/db.clj@@ -0,0 +1,44 @@+(ns metabase-enterprise.permission-debug.db+ "Application database queries for the permission-debug module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.permissions.core :as perms]+ [toucan2.core :as t2]))++(defn user-superuser?+ "Whether the User with `user-id` is a superuser."+ [user-id]+ (t2/select-one-fn :is_superuser :model/User :id user-id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn- blocked-tables-select+ [user-id tables-expr permissions-blocking permissions-granting]+ {:select [[:db.name :db_name] :blocked.schema [:blocked.name :table_name] [:pg.name :group_name]]+ :from [[:metabase_table :blocked]]+ :join [[(perms/select-tables-and-groups-granting-perm+ {:user-id user-id :is-superuser? false}+ permissions-blocking) :perm_grant] [:= :blocked.id :perm_grant.id]+ [:metabase_database :db] [:= :blocked.db_id :db.id]+ [:permissions_group :pg] [:= :perm_grant.group_id :pg.id]]+ :where [:and tables-expr+ [:not+ [:in :blocked.id (perms/visible-table-filter-select+ :id+ {:user-id user-id :is-superuser? false}+ permissions-granting)]]]})++(defn blocked-tables-in-database+ "The `[db-name schema table-name group-name]` rows of every Table in the Database with `database-id` blocked (per+ `permissions-blocking`) for the User with `user-id`, excluding those granted (per `permissions-granting`)."+ [user-id database-id permissions-blocking permissions-granting]+ (t2/query (blocked-tables-select user-id [:= :blocked.db_id database-id] permissions-blocking permissions-granting)))++(defn blocked-tables-among+ "The `[db-name schema table-name group-name]` rows of the Tables with `table-ids` blocked (per+ `permissions-blocking`) for the User with `user-id`, excluding those granted (per `permissions-granting`)."+ [user-id table-ids permissions-blocking permissions-granting]+ (t2/query (blocked-tables-select user-id [:in :blocked.id table-ids] permissions-blocking permissions-granting)))diff --git a/enterprise/backend/src/metabase_enterprise/permission_debug/impl.clj b/enterprise/backend/src/metabase_enterprise/permission_debug/impl.cljindex 3276ec6dceb..7260f1c7220 100644--- a/enterprise/backend/src/metabase_enterprise/permission_debug/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/permission_debug/impl.clj@@ -12,6 +12,7 @@"(:require[clojure.set :as set]+ [metabase-enterprise.permission-debug.db :as permission-debug.db][metabase.api.common :as api][metabase.lib.core :as lib][metabase.models.interface :as mi]@@ -19,8 +20,7 @@[metabase.query-processor.preprocess :as qp.preprocess][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]- [metabase.util.match :as match]- [toucan2.core :as t2]))+ [metabase.util.match :as match]))(set! *warn-on-reflection* true)@@ -62,7 +62,7 @@Returns a map conforming to the DebuggerSchema defined in the API."{:arglists '([debug-info-map])}(fn [{:keys [action-type user-id]}]- (let [user-is-superuser? (t2/select-one-fn :is_superuser :model/User :id user-id)]+ (let [user-is-superuser? (permission-debug.db/user-superuser? user-id)](if user-is-superuser?::is-superuseraction-type))))@@ -181,38 +181,12 @@(condnative?;; native queries are blocked if _any_ table in the database is blocked (or limited for download perms)- (t2/query {:select [[:db.name :db_name] :blocked.schema [:blocked.name :table_name] [:pg.name :group_name]]- :from [[:metabase_table :blocked]]- :join [[(perms/select-tables-and-groups-granting-perm- {:user-id user-id- :is-superuser? false}- permissions-blocking) :perm_grant] [:= :blocked.id :perm_grant.id]- [:metabase_database :db] [:= :blocked.db_id :db.id]- [:permissions_group :pg] [:= :perm_grant.group_id :pg.id]]- :where [:and [:= :blocked.db_id (:database_id card)]- [:not- [:in :blocked.id (perms/visible-table-filter-select- :id- {:user-id user-id- :is-superuser? false}- permissions-granting)]]]})+ (permission-debug.db/blocked-tables-in-database user-id (:database_id card)+ permissions-blocking permissions-granting)(seq query-tables)- (t2/query {:select [[:db.name :db_name] :blocked.schema [:blocked.name :table_name] [:pg.name :group_name]]- :from [[:metabase_table :blocked]]- :join [[(perms/select-tables-and-groups-granting-perm- {:user-id user-id- :is-superuser? false}- permissions-blocking) :perm_grant] [:= :blocked.id :perm_grant.id]- [:metabase_database :db] [:= :blocked.db_id :db.id]- [:permissions_group :pg] [:= :perm_grant.group_id :pg.id]]- :where [:and [:in :blocked.id query-tables]- [:not- [:in :blocked.id (perms/visible-table-filter-select- :id- {:user-id user-id- :is-superuser? false}- permissions-granting)]]]})+ (permission-debug.db/blocked-tables-among user-id query-tables permissions-blocking permissions-granting)+:elsenil)(map (juxt (juxt :db_name :schema :table_name) :group_name))@@ -223,7 +197,7 @@(merge-permission-check(debug-permissions (assoc debug-info :action-type :card/read))(let [card-id (Integer/parseInt model-id)- card (t2/select-one :model/Card :id card-id)+ card (permission-debug.db/card card-id)blocked-by-group (check-table-permissions user-id card{:perms/view-data :blocked}{:perms/view-data :legacy-no-self-service})]@@ -243,7 +217,7 @@(merge-permission-check(debug-permissions (assoc debug-info :action-type :card/query))(let [card-id (Integer/parseInt model-id)- card (t2/select-one :model/Card :id card-id)+ card (permission-debug.db/card card-id)limited-by-group (check-table-permissions user-id card{:perms/download-results :ten-thousand-rows}{:perms/download-results :one-million-rows})diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/api.cljindex 935d148f627..d312f550611 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj@@ -3,6 +3,7 @@[clojure.string :as str][medley.core :as m][metabase-enterprise.remote-sync.core :as remote-sync.core]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.impl :as impl][metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object][metabase-enterprise.remote-sync.models.remote-sync-task :as remote-sync.task]@@ -269,8 +270,7 @@(let [collections (when (seq collections)(let [current-states (into {}(map (juxt :id :is_remote_synced))- (t2/select [:model/Collection :id :is_remote_synced]- :id [:in (keys collections)]))]+ (remote-sync.db/collection-sync-states (keys collections)))](not-empty(into {}(filter (fn [[id desired]]diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.cljindex e9fdf679760..ca4b9eab04c 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.remote-sync.core(:require[java-time.api :as t]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.guards :as guards][metabase-enterprise.remote-sync.settings :as settings][metabase-enterprise.remote-sync.source :as source]@@ -90,32 +91,17 @@(spec/batch-check-eligibility spec instances)(into {} (map (fn [inst] [(:id inst) false])) instances)))-(defn- subtree-where- "HoneySQL predicate matching `collections` and all of their descendants."- [collections]- (into [:or [:in :id (map :id collections)]]- (for [collection collections]- [:like :location (str (collections/location-path collection) "%")])))--(defn- contents-rso-where- "HoneySQL predicate matching the RemoteSyncObject rows of `collection-ids` and of their contents."- [collection-ids]- [:or- [:and [:= :model_type "Collection"] [:in :model_id collection-ids]]- [:in :model_collection_id collection-ids]])-(defn- record-removed-rsos!"Records a pending removal on the RemoteSyncObject rows of the given collections and their contents, sothe next export deletes them from the remote. Rows still in 'create' (never pushed) are dropped outright— the remote never received them, so there is nothing to delete there."[collection-ids]- (let [rows (t2/select [:model/RemoteSyncObject :id :status] {:where (contents-rso-where collection-ids)})+ (let [rows (remote-sync.db/content-rso-statuses collection-ids){created true tracked false} (group-by #(= "create" (:status %)) rows)](when (seq created)- (t2/delete! :model/RemoteSyncObject :id [:in (map :id created)]))+ (remote-sync.db/delete-rsos! (map :id created)))(when (seq tracked)- (t2/update! :model/RemoteSyncObject :id [:in (map :id tracked)]- {:status "removed" :status_changed_at (t/offset-date-time)}))))+ (remote-sync.db/set-rsos-status! (map :id tracked) "removed" (t/offset-date-time)))))(defn- restore-removed-rsos!"Clears any pending 'removed' status on the given collections' and contents' RemoteSyncObject rows when the@@ -126,12 +112,8 @@Restores to 'update' rather than 'synced': edits made while the collection was un-synced are not tracked,so the entity must be re-serialized for the remote to be guaranteed to match local."[collection-ids]- (when-let [ids (seq (t2/select-pks-set :model/RemoteSyncObject- {:where [:and- [:= :status "removed"]- (contents-rso-where collection-ids)]}))]- (t2/update! :model/RemoteSyncObject :id [:in ids]- {:status "update" :status_changed_at (t/offset-date-time)})))+ (when-let [ids (seq (remote-sync.db/removed-content-rso-ids collection-ids))]+ (remote-sync.db/set-rsos-status! ids "update" (t/offset-date-time))))(defn- collection-content-specs"Specs for entities tracked by living directly in a remote-synced collection (Card, Dashboard, Document,@@ -148,26 +130,23 @@stays a no-op)."[collection-ids](doseq [{:keys [model-key model-type archived-key] :as spec} (collection-content-specs)- :let [tracked (t2/select-fn-set :model_id :model/RemoteSyncObject :model_type model-type)- where (if archived-key- [:and [:in :collection_id collection-ids] [:= archived-key false]]- [:in :collection_id collection-ids])- entities (t2/select model-key {:where where})]+ :let [tracked (remote-sync.db/tracked-model-ids model-type)+ entities (remote-sync.db/instances-in-collections model-key collection-ids archived-key)]entity entities:when (not (contains? tracked (:id entity)))]- (t2/insert! :model/RemoteSyncObject- (merge {:model_type model-type- :model_id (:id entity)- :status "create"- :status_changed_at (t/offset-date-time)}- (spec/build-sync-object-fields spec entity)))))+ (remote-sync.db/insert-rso!+ (merge {:model_type model-type+ :model_id (:id entity)+ :status "create"+ :status_changed_at (t/offset-date-time)}+ (spec/build-sync-object-fields spec entity)))))(defn- collections-by-id"`{id collection}` for `ids`, carrying the fields the failure descriptions need. Nil and duplicate idsare tolerated so callers can pass raw `:collection_id`s straight from the entities they described."[ids](when-let [ids (not-empty (disj (set ids) nil))]- (t2/select-pk->fn identity [:model/Collection :id :name :location :personal_owner_id] :id [:in ids])))+ (remote-sync.db/collections-by-id ids)))(defn- top-level-ancestor-id"Id of the outermost collection containing `collection`."@@ -198,7 +177,7 @@[entities](into {}(for [[model-name group] (group-by :model entities)- row (t2/select [(keyword "model" model-name) :id :name] :id [:in (map :id group)])]+ row (remote-sync.db/instance-names (keyword "model" model-name) (map :id group))][[model-name (:id row)] (:name row)])))(defn- card-item-models@@ -213,7 +192,7 @@:metric "metric""card")]));; :card_schema is required alongside :type — selecting it runs Card's schema upgrades.- (t2/select [:model/Card :id :type :card_schema] :id [:in ids]))))+ (remote-sync.db/card-types ids))))(defn- describe-entities"`[{:model :id :name}]` for `entities`, which are `{:model \"Card\" :id 412}` maps, in the order given."@@ -351,33 +330,23 @@{:sync-on #{} :sync-off #{}}collection-states)(update :sync-on #(when-let [sync-on (seq %)]- (t2/select :model/Collection :id [:in sync-on])))+ (remote-sync.db/collections sync-on)))(update :sync-off #(when-let [sync-off (seq %)]- (t2/select :model/Collection :id [:in sync-off]))))]+ (remote-sync.db/collections sync-off))))](try(t2/with-transaction [_](when (seq sync-on)- (t2/query {:update (t2/table-name :model/Collection)- :set {:is_remote_synced true}- :where [:and- [:= :is_remote_synced false]- (subtree-where sync-on)]})- (when-let [ids (seq (t2/select-pks-set :model/Collection {:where (subtree-where sync-on)}))]+ (remote-sync.db/mark-subtree-remote-synced! sync-on)+ (when-let [ids (seq (remote-sync.db/subtree-collection-ids sync-on))];; Re-syncing before a recorded removal was pushed must not leave the contents marked for deletion.(restore-removed-rsos! ids);; ...and contents that were dropped outright (never-pushed 'create' rows) must be re-tracked, so;; the next export pushes them rather than silently omitting them.(track-untracked-contents! ids)))(when (seq sync-off)- (let [affected-collection-ids- (t2/select-pks-set :model/Collection- {:where [:and- [:= :is_remote_synced true]- (subtree-where sync-off)]})]+ (let [affected-collection-ids (remote-sync.db/remote-synced-subtree-collection-ids sync-off)](when (seq affected-collection-ids)- (t2/query {:update (t2/table-name :model/Collection)- :set {:is_remote_synced false}- :where [:in :id affected-collection-ids]})+ (remote-sync.db/unmark-collections-remote-synced! affected-collection-ids)(record-removed-rsos! affected-collection-ids))))(when-let [failures (not-empty (unsynced-dependency-failures sync-on))](throw (ex-info (tru "Uses content that is not remote synced.")diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/db.cljnew file mode 100644index 00000000000..148aae75981--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj@@ -0,0 +1,605 @@+(ns metabase-enterprise.remote-sync.db+ "Application database queries for the remote-sync module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself."+ (:require+ [metabase.collections.core :as collections]+ [toucan2.core :as t2]))++(defn eligible-children+ "The instances of `model-key` whose `fk` column equals `model-id`, additionally matching `conditions` (a map of+ column to value or Toucan 2 operator-vector value, or nil for none)."+ [model-key fk model-id conditions]+ (apply t2/select model-key fk model-id (mapcat identity conditions)))++(defn ids-where+ "The IDs of the instances of `model-key` matching `conditions` (a map of column to value or Toucan 2+ operator-vector value, or nil for every instance)."+ [model-key conditions]+ (apply t2/select-fn-set :id model-key (mapcat identity conditions)))++(defn count-where+ "The number of instances of `model-key` matching `conditions` (a map of column to value or Toucan 2+ operator-vector value, or nil for every instance)."+ [model-key conditions]+ (apply t2/count model-key (mapcat identity conditions)))++(defn- removal-condition-exprs+ "Turns a spec's removal-conditions map into `:where` fragments: an `:entity_id` entry whose value is an+ `[op value]` pair becomes `[op :entity_id value]`; any other entry with a vector value becomes `[:in key value]`;+ a scalar value becomes `[:= key value]`."+ [removal-conditions]+ (for [[k v] removal-conditions]+ (cond+ (and (= k :entity_id) (vector? v)) (let [[op value] v] [op :entity_id value])+ (vector? v) [:in k v]+ :else [:= k v])))++(defn- removal-exprs+ "The `:where` fragments (see [[removal-condition-exprs]]) selecting the `model-key` rows an import removes:+ scoped to `synced-collection-ids` (when `scope-key` is given), excluding `entity-ids`, and matching+ `removal-conditions`. Returns nil for a scoped model with no synced collections (removes nothing)."+ [{:keys [scope-key synced-collection-ids entity-ids removal-conditions]}]+ (when-not (and scope-key (empty? synced-collection-ids))+ (cond-> []+ scope-key (conj [:in scope-key synced-collection-ids])+ (seq entity-ids) (conj [:not-in :entity_id entity-ids])+ :always (into (removal-condition-exprs removal-conditions)))))++(defn delete-removed-instances!+ "Deletes the `model-key` rows an import removes (see [[removal-exprs]]); a no-op for a scoped model with no+ synced collections, and a delete of every row when nothing restricts it."+ [model-key removal-opts]+ (when-let [exprs (removal-exprs removal-opts)]+ (if (seq exprs)+ (t2/delete! model-key {:where (if (= 1 (count exprs)) (first exprs) (into [:and] exprs))})+ (t2/delete! model-key))))++(defn- unsynced-anti-join-expr+ "A `[:not [:exists ...]]` fragment keeping only rows with no RemoteSyncObject of `model-type` in 'synced'+ status — i.e. unsynced local work (an already-synced entity's removal is a normal reconcile, not data loss).+ `id-column` is the qualified id column of the model's own table."+ [model-type id-column]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [:remote_sync_object]+ :where [:and+ [:= :remote_sync_object.model_type model-type]+ [:= :remote_sync_object.model_id id-column]+ [:= :remote_sync_object.status "synced"]]}]])++(defn- unsynced-instance-expr+ [model-key model-type removal-opts]+ (let [id-column (keyword (str (name (t2/table-name model-key)) ".id"))]+ (into [:and (unsynced-anti-join-expr model-type id-column)] (removal-exprs removal-opts))))++(defn unsynced-instance-count+ "The number of `model-key` rows [[delete-removed-instances!]] would remove (see [[removal-exprs]]) that also+ have no RemoteSyncObject of `model-type` in synced status — unsynced local work an import would otherwise wipe+ out."+ [model-key model-type removal-opts]+ (t2/count model-key {:where (unsynced-instance-expr model-key model-type removal-opts)}))++(defn unsynced-instance-names+ "Up to `limit` names of the rows [[unsynced-instance-count]] counts."+ [model-key model-type removal-opts limit]+ (t2/select-fn-vec :name model-key {:where (unsynced-instance-expr model-key model-type removal-opts)+ :limit limit}))++(defn instance+ "The instance of `model` with `id`, or nil."+ [model id]+ (t2/select-one model :id id))++(defn instance-with-columns+ "The `columns` of the instance of `model` with `id`, or nil."+ [model columns id]+ (t2/select-one (into [model] columns) :id id))++(defn instance-names+ "The `:id` and `:name` of the instances of `model` with `ids`."+ [model ids]+ (t2/select [model :id :name] :id [:in ids]))++(defn instances-in-collections+ "The instances of `model` in the Collections with `collection-ids`, excluding those archived under the optional+ `archived-key` column."+ [model collection-ids archived-key]+ (t2/select model {:where [:and+ [:in :collection_id collection-ids]+ (when archived-key [:= archived-key false])]}))++(defn instances-with-columns-by-entity-ids+ "The `columns` of the instances of `model` with `entity-ids`."+ [model columns entity-ids]+ (t2/select (into [model] columns) :entity_id [:in entity-ids]))++(defn delete-instances!+ "Delete the instances of `model` with `ids`."+ [model ids]+ (t2/delete! model :id [:in ids]))++(defn- tracking-select-parts+ "The SELECT/FROM/JOIN joining a `model-key` instance (Field, Segment, or Measure) to its Table for sync tracking,+ plus the `alias` its own table is joined under (so callers can address its `:id` and `:entity_id` columns).+ Segment and Measure share alias \"s\" — both are looked up the same way by [[tracking-details-by-entity-ids]]."+ [model-key]+ (case model-key+ :model/Field {:alias "f"+ :select [:f.name :f.table_id [:t.collection_id :collection_id] [:t.name :table_name]]+ :from [[:metabase_field :f]]+ :join [[:metabase_table :t] [:= :f.table_id :t.id]]}+ :model/Segment {:alias "s"+ :select [:s.name :s.table_id [:t.collection_id :collection_id] [:t.name :table_name]]+ :from [[:segment :s]]+ :join [[:metabase_table :t] [:= :s.table_id :t.id]]}+ :model/Measure {:alias "s"+ :select [:s.name :s.table_id [:t.collection_id :collection_id] [:t.name :table_name]]+ :from [[:measure :s]]+ :join [[:metabase_table :t] [:= :s.table_id :t.id]]}))++(defn tracking-details-by-id+ "The name, table id, collection id, and table name of the `model-key` (Field, Segment, or Measure) instance with+ `model-id`, or nil."+ [model-key model-id]+ (let [{:keys [alias select from join]} (tracking-select-parts model-key)]+ (first (t2/query {:select select :from from :join join :where [:= (keyword alias "id") model-id]}))))++(defn tracking-details-by-entity-ids+ "The `:id`, name, table id, collection id, and table name of the `model-key` (Segment or Measure) instances with+ `entity-ids`."+ [model-key entity-ids]+ (let [{:keys [alias select from join]} (tracking-select-parts model-key)+ id-column (keyword alias "id")]+ (t2/query {:select (into [id-column] select)+ :from from+ :join join+ :where [:in (keyword alias "entity_id") entity-ids]})))++(defn entity-id+ "The entity ID of the instance of `model` with `id`."+ [model id]+ (t2/select-one-fn :entity_id model :id id))++(defn entity-ids-by-id+ "A map of ID to entity ID for the instances of `model` with `ids`."+ [model ids]+ (t2/select-pk->fn :entity_id model :id [:in ids]))++(defn existing-entity-ids+ "The subset of `entity-ids` that instances of `model` have."+ [model entity-ids]+ (t2/select-fn-set :entity_id model :entity_id [:in entity-ids]))++(defn ids-by-entity-ids+ "The IDs of the instances of `model` with `entity-ids`."+ [model entity-ids]+ (t2/select-pks-vec model :entity_id [:in entity-ids]))++(defn- path-expr+ "Matches the Tables (aliased `t` in a Database aliased `db`) at `paths`, and their Fields (aliased `f`) when+ `has-field?`."+ [paths has-field?]+ (into [:or]+ (for [path paths]+ (let [{:keys [db_name schema table_name field_name]} path]+ (cond-> [:and+ [:= :db.name db_name]+ (if schema [:= :t.schema schema] [:is :t.schema nil])+ [:= :t.name table_name]]+ (and has-field? field_name)+ (conj [:= :f.name field_name]))))))++(defn tables-at-paths+ "The `:id`, `:name`, and `:collection_id` rows of the Tables at `paths` (`{:db_name :schema :table_name}`)."+ [paths]+ (t2/query {:select [:t.id :t.name :t.collection_id]+ :from [[:metabase_table :t]]+ :join [[:metabase_database :db] [:= :db.id :t.db_id]]+ :where (path-expr paths false)}))++(defn fields-at-paths+ "The `:id`, `:name`, `:table_id`, `:collection_id`, and `:table_name` rows of the Fields at `paths`+ (`{:db_name :schema :table_name :field_name}`)."+ [paths]+ (t2/query {:select [:f.id :f.name :f.table_id [:t.collection_id :collection_id] [:t.name :table_name]]+ :from [[:metabase_field :f]]+ :join [[:metabase_table :t] [:= :t.id :f.table_id]+ [:metabase_database :db] [:= :db.id :t.db_id]]+ :where (path-expr paths true)}))++(defn card-types+ "The `:id`, `:type`, and `:card_schema` of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :type :card_schema] :id [:in card-ids]))++(defn field-user-settings-exist?+ "Whether the Field with `field-id` has FieldUserSettings."+ [field-id]+ (t2/exists? :model/FieldUserSettings :field_id field-id))++(defn snippets+ "The `:id`, `:name`, and `:collection_id` of every NativeQuerySnippet."+ []+ (t2/select [:model/NativeQuerySnippet :id :name :collection_id]))++(defn- subtree-expr+ "Matches `collections` and all of their descendants."+ [collections]+ (into [:or [:in :id (map :id collections)]]+ (for [collection collections]+ [:like :location (str (collections/location-path collection) "%")])))++(defn collections+ "The Collections with `collection-ids`."+ [collection-ids]+ (t2/select :model/Collection :id [:in collection-ids]))++(defn collections-by-id+ "A map of ID to the ID, name, location, and personal owner of the Collections with `collection-ids`."+ [collection-ids]+ (t2/select-pk->fn identity [:model/Collection :id :name :location :personal_owner_id] :id [:in collection-ids]))++(defn collection-sync-states+ "The `:id` and `:is_remote_synced` of the Collections with `collection-ids`."+ [collection-ids]+ (t2/select [:model/Collection :id :is_remote_synced] :id [:in collection-ids]))++(defn collection-name-and-id+ "The `:name` and `:collection_id` (its own ID) of the Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one [:model/Collection :name [:id :collection_id]] :id collection-id))++(defn library-collection+ "The Library Collection of `library-type`, or nil."+ [library-type]+ (t2/select-one :model/Collection :type library-type))++(defn snippet-collections+ "The `:id` and `:name` of the Collections of the snippets namespace."+ []+ (t2/select [:model/Collection :id :name] :namespace "snippets"))++(defn snippet-collection-ids+ "The IDs of the Collections of the snippets namespace."+ []+ (t2/select-pks-set :model/Collection :namespace "snippets"))++(defn collections-in-namespace+ "The `:id` and `:entity_id` of the Collections of `namespace-name`."+ [namespace-name]+ (t2/select [:model/Collection :id :entity_id] :namespace namespace-name))++(defn collection-ids-in-namespace+ "The IDs of the Collections of `namespace-name`."+ [namespace-name]+ (t2/select-pks-vec :model/Collection :namespace namespace-name))++(defn remote-synced-collection-ids+ "The IDs of the remote-synced Collections."+ []+ (t2/select-pks-vec :model/Collection :is_remote_synced true))++(defn unarchived-remote-synced-root-collection-ids+ "The IDs of the unarchived remote-synced root Collections."+ []+ (t2/select-fn-set :id :model/Collection+ {:where [:and+ [:= :is_remote_synced true]+ [:= :location "/"]+ [:not :archived]]}))++(defn unarchived-root-collection-ids-in-namespace+ "The IDs of the unarchived root Collections of `namespace-name`."+ [namespace-name]+ (t2/select-fn-set :id :model/Collection+ {:where [:and+ [:= :namespace namespace-name]+ [:= :location "/"]+ [:not :archived]]}))++(defn subtree-collection-ids+ "The IDs of `collections` and all of their descendants."+ [collections]+ (t2/select-pks-set :model/Collection {:where (subtree-expr collections)}))++(defn remote-synced-subtree-collection-ids+ "The IDs of the remote-synced Collections among `collections` and their descendants."+ [collections]+ (t2/select-pks-set :model/Collection+ {:where [:and+ [:= :is_remote_synced true]+ (subtree-expr collections)]}))++(defn mark-subtree-remote-synced!+ "Mark `collections` and all of their descendants as remote-synced."+ [collections]+ (t2/query {:update (t2/table-name :model/Collection)+ :set {:is_remote_synced true}+ :where [:and+ [:= :is_remote_synced false]+ (subtree-expr collections)]}))++(defn unmark-collections-remote-synced!+ "Mark the Collections with `collection-ids` as not remote-synced."+ [collection-ids]+ (t2/query {:update (t2/table-name :model/Collection)+ :set {:is_remote_synced false}+ :where [:in :id collection-ids]}))++(defn- contents-rso-expr+ "Matches the RemoteSyncObject rows of `collection-ids` and of their contents."+ [collection-ids]+ [:or+ [:and [:= :model_type "Collection"] [:in :model_id collection-ids]]+ [:in :model_collection_id collection-ids]])++(defn- rso-keys-expr+ "Matches the RemoteSyncObject rows of the `[{:model_type :model_id}]` `rows`."+ [rows]+ (into [:or] (map (fn [{:keys [model_type model_id]}]+ [:and [:= :model_type model_type] [:= :model_id model_id]]))+ rows))++(defn rso+ "The RemoteSyncObject of the entity `model-type` `model-id`, or nil."+ [model-type model-id]+ (t2/select-one :model/RemoteSyncObject :model_type model-type :model_id model-id))++(defn lock-rso+ "The RemoteSyncObject of the entity `model-type` `model-id`, locked for update, or nil."+ [model-type model-id]+ (t2/select-one :model/RemoteSyncObject+ {:where [:and [:= :model_type model-type] [:= :model_id model-id]]+ :for :update}))++(defn rso-by-file-path+ "The RemoteSyncObject at `file-path`, or nil."+ [file-path]+ (t2/select-one :model/RemoteSyncObject :file_path file-path))++(defn rso-exists?+ "Whether the entity `model-type` `model-id` has a RemoteSyncObject."+ [model-type model-id]+ (t2/exists? :model/RemoteSyncObject :model_type model-type :model_id model-id))++(defn rso-of-type-exists?+ "Whether any entity of `model-type` has a RemoteSyncObject."+ [model-type]+ (t2/exists? :model/RemoteSyncObject :model_type model-type))++(defn rso-count-of-type+ "The number of RemoteSyncObjects of `model-type`."+ [model-type]+ (t2/count :model/RemoteSyncObject :model_type model-type))++(defn rso-keys+ "The `:id`, `:model_type`, and `:model_id` of every RemoteSyncObject."+ []+ (t2/select [:model/RemoteSyncObject :id :model_type :model_id]))++(defn departed-rso-keys+ "The `:id`, `:model_type`, and `:model_id` of the RemoteSyncObjects pending removal or deletion."+ []+ (t2/select [:model/RemoteSyncObject :id :model_type :model_id] :status [:in ["removed" "delete"]]))++(defn all-rso-ids+ "The IDs of every RemoteSyncObject."+ []+ (t2/select-pks-set :model/RemoteSyncObject))++(defn unsynced-rsos+ "The RemoteSyncObjects whose status is not synced."+ []+ (t2/select :model/RemoteSyncObject {:where [:not= :status "synced"]}))++(defn dirty-rso-exists?+ "Whether a RemoteSyncObject of a model type other than `excluded-model-types` is not synced."+ [excluded-model-types]+ (t2/exists? :model/RemoteSyncObject+ {:where [:and+ [:not= :status "synced"]+ (when (seq excluded-model-types)+ [:not-in :model_type excluded-model-types])]}))++(defn dirty-rsos+ "The RemoteSyncObjects of model types other than `excluded-model-types` that are not synced."+ [excluded-model-types]+ (t2/select :model/RemoteSyncObject+ {:where [:and+ [:not= :status "synced"]+ (when (seq excluded-model-types)+ [:not-in :model_type excluded-model-types])]}))++(defn tracked-model-ids+ "The model IDs of the RemoteSyncObjects of `model-type`."+ [model-type]+ (t2/select-fn-set :model_id :model/RemoteSyncObject :model_type model-type))++(defn rsos-of-models+ "The RemoteSyncObjects of the entities of `model-type` with `model-ids`."+ [model-type model-ids]+ (t2/select :model/RemoteSyncObject :model_type model-type :model_id [:in model-ids]))++(defn active-child-rsos+ "The RemoteSyncObjects of `model-type` under the Table with `table-id` that are not pending removal or deletion."+ [model-type table-id]+ (t2/select :model/RemoteSyncObject+ :model_type model-type+ :model_table_id table-id+ :status [:not-in ["removed" "delete"]]))++(defn content-rso-statuses+ "The `:id` and `:status` of the RemoteSyncObjects of the Collections with `collection-ids` and their contents."+ [collection-ids]+ (t2/select [:model/RemoteSyncObject :id :status] {:where (contents-rso-expr collection-ids)}))++(defn removed-content-rso-ids+ "The IDs of the RemoteSyncObjects pending removal among those of the Collections with `collection-ids` and their+ contents."+ [collection-ids]+ (t2/select-pks-set :model/RemoteSyncObject+ {:where [:and+ [:= :status "removed"]+ (contents-rso-expr collection-ids)]}))++(defn insert-rso!+ "Insert the RemoteSyncObject `row`."+ [row]+ (t2/insert! :model/RemoteSyncObject row))++(defn insert-rsos!+ "Insert the RemoteSyncObject `rows`."+ [rows]+ (t2/insert! :model/RemoteSyncObject rows))++(defn update-rso!+ "Apply `changes` to the RemoteSyncObject with `rso-id`."+ [rso-id changes]+ (t2/update! :model/RemoteSyncObject rso-id changes))++(defn set-rsos-status!+ "Set the status of the RemoteSyncObjects with `rso-ids` to `status` as of `timestamp`."+ [rso-ids status timestamp]+ (t2/update! :model/RemoteSyncObject :id [:in rso-ids] {:status status :status_changed_at timestamp}))++(defn mark-all-rsos-synced!+ "Mark every RemoteSyncObject as synced as of `timestamp`."+ [timestamp]+ (t2/update! :model/RemoteSyncObject {:status "synced" :status_changed_at timestamp}))++(defn mark-rsos-synced!+ "Mark the RemoteSyncObjects with `rso-ids` as synced as of `timestamp`, writing the `:file_path` and+ `:content_hash` of those in `metadata-by-id` and keeping the existing values of the others."+ [rso-ids metadata-by-id timestamp]+ (t2/update! :model/RemoteSyncObject+ {:id [:in (vec rso-ids)]}+ (cond-> {:status "synced" :status_changed_at timestamp}+ (seq metadata-by-id)+ (assoc :file_path (into [:case]+ (concat+ (mapcat (fn [[id {:keys [file_path]}]]+ [[:= :id id] file_path])+ metadata-by-id)+ [:else :file_path]))+ :content_hash (into [:case]+ (concat+ (mapcat (fn [[id {:keys [content_hash]}]]+ [[:= :id id] content_hash])+ metadata-by-id)+ [:else :content_hash]))))))++(defn delete-rso!+ "Delete the RemoteSyncObject with `rso-id`."+ [rso-id]+ (t2/delete! :model/RemoteSyncObject rso-id))++(defn delete-rsos!+ "Delete the RemoteSyncObjects with `rso-ids`."+ [rso-ids]+ (t2/delete! :model/RemoteSyncObject :id [:in rso-ids]))++(defn delete-rso-of!+ "Delete the RemoteSyncObject of the entity `model-type` `model-id`."+ [model-type model-id]+ (t2/delete! :model/RemoteSyncObject :model_type model-type :model_id model-id))++(defn delete-rsos-of-type!+ "Delete the RemoteSyncObjects of `model-type`."+ [model-type]+ (t2/delete! :model/RemoteSyncObject :model_type model-type))++(defn delete-rsos-of-models!+ "Delete the RemoteSyncObjects of the entities of `model-type` with `model-ids`."+ [model-type model-ids]+ (t2/delete! :model/RemoteSyncObject :model_type model-type :model_id [:in model-ids]))++(defn delete-rsos-of-keys!+ "Delete the RemoteSyncObjects of the `[{:model_type :model_id}]` `rows`."+ [rows]+ (t2/delete! :model/RemoteSyncObject {:where (rso-keys-expr rows)}))++(defn delete-all-rsos!+ "Delete every RemoteSyncObject."+ []+ (t2/delete! :model/RemoteSyncObject))++(defn task+ "The RemoteSyncTask with `task-id`, or nil."+ [task-id]+ (t2/select-one :model/RemoteSyncTask task-id))++(defn lock-task+ "The RemoteSyncTask with `task-id`, locked for update, or nil."+ [task-id]+ (t2/select-one :model/RemoteSyncTask :id task-id {:for :update}))++(defn task-cancelled?+ "The cancelled flag of the RemoteSyncTask with `task-id`."+ [task-id]+ (t2/select-one-fn :cancelled :model/RemoteSyncTask :id task-id))++(defn current-task+ "The newest started, unfinished RemoteSyncTask that reported progress after `progress-cutoff`, or nil."+ [progress-cutoff]+ (t2/select-one :model/RemoteSyncTask+ {:where [:and+ [:<> :started_at nil]+ [:= :ended_at nil]+ [:< progress-cutoff :last_progress_report_at]]+ :limit 1+ :order-by [[:started_at :desc]+ [:id :desc]]}))++(defn most-recent-task+ "The newest started RemoteSyncTask, or nil."+ []+ (t2/select-one :model/RemoteSyncTask+ {:where [:and+ [:<> :started_at nil]]+ :limit 1+ :order-by [[:started_at :desc]+ [:id :desc]]}))++(defn last-successful-task+ "The newest finished RemoteSyncTask that was neither cancelled nor failed and recorded a version, or nil."+ []+ (t2/select-one :model/RemoteSyncTask+ {:where [:and+ [:<> nil :ended_at]+ [:= false :cancelled]+ [:= nil :error_message]+ [:<> nil :version]]+ :limit 1+ :order-by [[:started_at :desc]+ [:id :desc]]}))++(defn insert-task!+ "Insert `task` and return the new instance."+ [task]+ (t2/insert-returning-instance! :model/RemoteSyncTask task))++(defn update-task!+ "Apply `changes` to the RemoteSyncTask with `task-id`."+ [task-id changes]+ (t2/update! :model/RemoteSyncTask task-id changes))++(defn supersede-stale-tasks!+ "Cancel and end at `now` the started, unfinished RemoteSyncTasks that last reported progress before `cutoff`."+ [cutoff now]+ (t2/query {:update (t2/table-name :model/RemoteSyncTask)+ :set {:cancelled true+ :ended_at now+ :error_message "Superseded after staleness timeout"}+ :where [:and+ [:<> :started_at nil]+ [:= :ended_at nil]+ [:< :last_progress_report_at cutoff]]}))++(defn delete-tasks-started-before!+ "Delete the RemoteSyncTasks started before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/RemoteSyncTask {:where [:< :started_at cutoff]}))++(defn users-by-id+ "A map of User ID to User for `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity :model/User :id [:in user-ids]))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/events.cljindex c30efa17c19..6ceaab9c6bb 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj@@ -17,6 +17,7 @@- NativeQuerySnippet, snippets-namespace Collections (when Library is remote-synced)"(:require[java-time.api :as t]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.source :as source][metabase-enterprise.remote-sync.spec :as spec][metabase.collections.core :as collections]@@ -30,13 +31,13 @@[](let [timestamp (t/offset-date-time)rows (concat- (for [coll (t2/select [:model/Collection :id :name] :namespace "snippets")]+ (for [coll (remote-sync.db/snippet-collections)]{:model_type "Collection":model_id (:id coll):model_name (:name coll):status "create":status_changed_at timestamp})- (for [snippet (t2/select [:model/NativeQuerySnippet :id :name :collection_id])]+ (for [snippet (remote-sync.db/snippets)]{:model_type "NativeQuerySnippet":model_id (:id snippet):model_name (:name snippet)@@ -44,18 +45,15 @@:status "create":status_changed_at timestamp}))](when (seq rows)- (t2/insert! :model/RemoteSyncObject rows))))+ (remote-sync.db/insert-rsos! rows))))(defn disable-snippet-tracking!"Remove all snippet-related tracking entries."[]- (let [snippet-coll-ids (t2/select-pks-set :model/Collection :namespace "snippets")]- (t2/delete! :model/RemoteSyncObject- :model_type "NativeQuerySnippet")+ (let [snippet-coll-ids (remote-sync.db/snippet-collection-ids)]+ (remote-sync.db/delete-rsos-of-type! "NativeQuerySnippet")(when (seq snippet-coll-ids)- (t2/delete! :model/RemoteSyncObject- :model_type "Collection"- :model_id [:in snippet-coll-ids]))))+ (remote-sync.db/delete-rsos-of-models! "Collection" snippet-coll-ids))));;; ----------------------------------------- Helper Functions ---------------------------------------------------------@@ -86,36 +84,36 @@- hydrate-details-fn: Function that takes model-id and returns a map with :name, :collection_id,and optionally :display, :table_id, :table_name"[model-type model-id status hydrate-details-fn]- (let [existing (t2/select-one :model/RemoteSyncObject :model_type model-type :model_id model-id)]+ (let [existing (remote-sync.db/rso model-type model-id)](cond(not existing)(let [model-details (hydrate-details-fn model-id)]- (t2/insert! :model/RemoteSyncObject- {:model_type model-type- :model_id model-id- :model_name (:name model-details)- :model_collection_id (:collection_id model-details)- :model_display (some-> model-details :display name)- :model_table_id (:table_id model-details)- :model_table_name (:table_name model-details)- :status status- :status_changed_at (t/offset-date-time)}))+ (remote-sync.db/insert-rso!+ {:model_type model-type+ :model_id model-id+ :model_name (:name model-details)+ :model_collection_id (:collection_id model-details)+ :model_display (some-> model-details :display name)+ :model_table_id (:table_id model-details)+ :model_table_name (:table_name model-details)+ :status status+ :status_changed_at (t/offset-date-time)}))(and (= "create" (:status existing)) (contains? #{"removed" "delete"} status))- (t2/delete! :model/RemoteSyncObject (:id existing))+ (remote-sync.db/delete-rso! (:id existing))(= "delete" (:status existing))- (t2/update! :model/RemoteSyncObject (:id existing)- {:status status- :status_changed_at (t/offset-date-time)})+ (remote-sync.db/update-rso! (:id existing)+ {:status status+ :status_changed_at (t/offset-date-time)})(not (= "create" (:status existing)))(let [model-details (hydrate-details-fn model-id)]- (t2/update! :model/RemoteSyncObject (:id existing)- {:status (resolve-status model-type model-id status existing)- :status_changed_at (t/offset-date-time)- :model_name (:name model-details)- :model_collection_id (:collection_id model-details)- :model_display (some-> model-details :display name)- :model_table_id (:table_id model-details)- :model_table_name (:table_name model-details)})))))+ (remote-sync.db/update-rso! (:id existing)+ {:status (resolve-status model-type model-id status existing)+ :status_changed_at (t/offset-date-time)+ :model_name (:name model-details)+ :model_collection_id (:collection_id model-details)+ :model_display (some-> model-details :display name)+ :model_table_id (:table_id model-details)+ :model_table_name (:table_name model-details)})))));;; ----------------------------------------- Spec-based Event Handling ------------------------------------------------@@ -123,7 +121,7 @@"Re-checks `model-id`'s eligibility against current DB state. The eligibility that got us here was computedfrom an event payload, which a concurrent change may have invalidated in the meantime."[model-spec model-id]- (boolean (when-let [instance (t2/select-one (:model-key model-spec) :id model-id)]+ (boolean (when-let [instance (remote-sync.db/instance (:model-key model-spec) model-id)](spec/check-eligibility model-spec instance))))(defn- create-or-update-sync-object-from-spec!@@ -137,9 +135,7 @@[model-spec model-id status](t2/with-transaction [_conn](let [model-type (:model-type model-spec)- existing (t2/select-one :model/RemoteSyncObject- {:where [:and [:= :model_type model-type] [:= :model_id model-id]]- :for :update})]+ existing (remote-sync.db/lock-rso model-type model-id)](cond;; No row to lock, so a concurrent un-sync that hasn't inserted yet is invisible here (a phantom the;; row lock can't cover). Re-check eligibility so a stale tracked-status event does not start tracking@@ -152,15 +148,15 @@(not existing)(let [model-details (spec/hydrate-model-details model-spec model-id)fields (spec/build-sync-object-fields model-spec model-details)]- (t2/insert! :model/RemoteSyncObject- (merge {:model_type model-type- :model_id model-id- :status status- :status_changed_at (t/offset-date-time)}- fields)))+ (remote-sync.db/insert-rso!+ (merge {:model_type model-type+ :model_id model-id+ :status status+ :status_changed_at (t/offset-date-time)}+ fields)))(and (= "create" (:status existing)) (contains? #{"removed" "delete"} status))- (t2/delete! :model/RemoteSyncObject (:id existing))+ (remote-sync.db/delete-rso! (:id existing));; A pending removal must not be resurrected by a tracked-status write whose eligibility check was;; overtaken by a concurrent un-sync: that check ran against the event payload, well before this@@ -171,17 +167,17 @@nil(= "delete" (:status existing))- (t2/update! :model/RemoteSyncObject (:id existing)- {:status status- :status_changed_at (t/offset-date-time)})+ (remote-sync.db/update-rso! (:id existing)+ {:status status+ :status_changed_at (t/offset-date-time)})(not= "create" (:status existing))(let [model-details (spec/hydrate-model-details model-spec model-id)fields (spec/build-sync-object-fields model-spec model-details)]- (t2/update! :model/RemoteSyncObject (:id existing)- (merge {:status (resolve-status model-type model-id status existing)- :status_changed_at (t/offset-date-time)}- fields)))))))+ (remote-sync.db/update-rso! (:id existing)+ (merge {:status (resolve-status model-type model-id status existing)+ :status_changed_at (t/offset-date-time)}+ fields)))))))(defn- cascade-filter"Derives the filter conditions for querying eligible children from a child spec."@@ -200,14 +196,11 @@filter (cascade-filter child-spec)](if eligible?;; Eligible branch: query actual entities and create RSOs for eligible children- (doseq [child (apply t2/select (:model-key child-spec) (into [fk model-id] cat filter))]+ (doseq [child (remote-sync.db/eligible-children (:model-key child-spec) fk model-id filter)](when (spec/check-eligibility child-spec child)(create-or-update-sync-object-from-spec! child-spec (:id child) status)));; Ineligible branch: mark existing child RSOs as removed- (doseq [child-rso (t2/select :model/RemoteSyncObject- :model_type (:model-type child-spec)- :model_table_id model-id- :status [:not-in ["removed" "delete"]])]+ (doseq [child-rso (remote-sync.db/active-child-rsos (:model-type child-spec) model-id)](create-or-update-sync-object-from-spec! child-spec (:model_id child-rso) "removed"))))))(defn- handle-model-event-from-spec@@ -217,7 +210,7 @@(let [model-type (:model-type model-spec)model-id (:id object)eligible? (spec/check-eligibility model-spec object)- existing-entry (t2/select-one :model/RemoteSyncObject :model_type model-type :model_id model-id)+ existing-entry (remote-sync.db/rso model-type model-id)status (spec/determine-status model-spec topic object)](condeligible?@@ -266,13 +259,13 @@(defn- hydrate-collection-details"Hydrates details for a Collection."[id]- (t2/select-one [:model/Collection :name [:id :collection_id]] :id id))+ (remote-sync.db/collection-name-and-id id))(defn- handle-library-sync-status-change!"When the Library collection's is_remote_synced status changes, trigger snippet sync tracking.This ensures all snippets are tracked/untracked when Library sync is enabled/disabled."[is-now-synced?]- (let [snippets-already-tracked? (t2/exists? :model/RemoteSyncObject :model_type "NativeQuerySnippet")]+ (let [snippets-already-tracked? (remote-sync.db/rso-of-type-exists? "NativeQuerySnippet")](cond(and is-now-synced? (not snippets-already-tracked?))(do@@ -288,7 +281,7 @@(let [{:keys [object]} eventshould-sync? (spec/should-sync-collection? object)is-remote-synced? (collections/remote-synced-collection? object)- existing-entry (t2/select-one :model/RemoteSyncObject :model_type "Collection" :model_id (:id object))+ existing-entry (remote-sync.db/rso "Collection" (:id object))status (if (:archived object)"delete"(case topic@@ -321,13 +314,13 @@(let [field-id (:id object)eligible? (spec/check-eligibility field-spec object)](cond- (and eligible? (t2/exists? :model/FieldUserSettings :field_id field-id))+ (and eligible? (remote-sync.db/field-user-settings-exist? field-id))(create-or-update-remote-sync-object-entry!"FieldUserSettings" field-id "update"(fn [id] (spec/hydrate-model-details field-spec id)))(and (not eligible?)- (t2/exists? :model/RemoteSyncObject :model_type "FieldUserSettings" :model_id field-id))+ (remote-sync.db/rso-exists? "FieldUserSettings" field-id))(create-or-update-remote-sync-object-entry!"FieldUserSettings" field-id "removed"(fn [id] (spec/hydrate-model-details field-spec id))))))diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex b60b6ff50d5..ca1d117a877 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -4,6 +4,7 @@[diehard.core :as dh][java-time.api :as t][metabase-enterprise.data-apps.sync :as data-apps.sync]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.guards :as guards][metabase-enterprise.remote-sync.merge :as remote-sync.merge][metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object]@@ -72,17 +73,13 @@Collection are deleted before Collection itself)."[synced-collection-ids {:keys [by-entity-id]}](doseq [[model-key model-spec] (spec/specs-for-deletion)- :let [entity-ids (get by-entity-id (:model-type model-spec) [])- clauses (spec/removal-where-clauses model-spec synced-collection-ids entity-ids)]]- (cond- ;; Scoped model with no collections to scope to — nothing to delete- (nil? clauses) nil- ;; A predicate — delete matching rows- (seq clauses) (t2/delete! model-key {:where (if (= 1 (count clauses))- (first clauses)- (into [:and] clauses))})- ;; No predicate (global model, no imported ids or conditions) — delete all- :else (t2/delete! model-key))))+ :let [entity-ids (get by-entity-id (:model-type model-spec) [])]]+ (remote-sync.db/delete-removed-instances!+ model-key+ {:scope-key (get-in model-spec [:removal :scope-key])+ :synced-collection-ids synced-collection-ids+ :entity-ids entity-ids+ :removal-conditions (spec/removal-conditions model-spec)})))(defn- quoted"Wraps `s` in backticks so that leading and trailing whitespace is visible to the reader."@@ -226,13 +223,11 @@ns-coll-conflicts (spec/check-namespace-collection-conflictsimport-namespace-collections(:entity-ids import-ns-info))- library-conflict (when-let [local-library (t2/select-one :model/Collection :type collection/library-collection-type)]+ library-conflict (when-let [local-library (remote-sync.db/library-collection collection/library-collection-type)](when (and first-import?(contains? (get-in imported-data [:by-entity-id "Collection"] #{})collection/library-entity-id)- (not (t2/exists? :model/RemoteSyncObject- :model_type "Collection"- :model_id (:id local-library))))+ (not (remote-sync.db/rso-exists? "Collection" (:id local-library)))){:type :library-conflict:category "Library":message "Import contains Library but local instance has an unsynced Library collection"}))@@ -279,7 +274,7 @@opts {:where [:in :id (mapv :model_id model-rows)] :skip-archived true};; entity-id models: map local id -> entity_id so we can look up the repo pathid->eid (when (and model-key (= :entity-id (:identity spec)))- (t2/select-pk->fn :entity_id model-key :id [:in (mapv :model_id model-rows)]))]+ (remote-sync.db/entity-ids-by-id model-key (mapv :model_id model-rows)))](eduction (keep #(serialize model-type opts id->eid %))(serdes/extract-query model-type opts)))))(group-by :model_type rows))))@@ -301,8 +296,7 @@[rows repo-paths](serdes/with-cache(doseq [chunk (partition-all app-db-batch-size rows)]- (t2/insert! :model/RemoteSyncObject- (merge-content-metadata chunk (import-content-metadata chunk repo-paths))))))+ (remote-sync.db/insert-rsos! (merge-content-metadata chunk (import-content-metadata chunk repo-paths))))))(defn- branch-changed-since-scheduling?"Returns true if `pre-task-branch` was captured by the async-* function and the@@ -358,7 +352,7 @@;; Replace the RemoteSyncObject table, folding each entity's repo file_path (so later renames/deletes;; resolve the real file) and serialized-content hash (so a post-pull no-op edit stays synced) into the;; insert. Chunked so insert/IN params and memory stay bounded.- (t2/delete! :model/RemoteSyncObject)+ (remote-sync.db/delete-all-rsos!)(insert-with-metadata! (spec/sync-all-entities! sync-timestamp imported-data)(source.ingestable/cached-file-paths base-ingestable))(when finalize! (finalize!)))@@ -391,13 +385,6 @@(when-let [i (str/index-of path "/")](contains? serialization/legal-top-level-paths (subs path 0 i)))))-(defn- rso-where-for- "HoneySQL :where matching the RemoteSyncObject rows for the given `[{:model_type :model_id}]` maps."- [rows]- (into [:or] (map (fn [{:keys [model_type model_id]}]- [:and [:= :model_type model_type] [:= :model_id model_id]]))- rows))-(defn- pulled-change-count"Total number of entities applied by a pull, across entity-id- and path-identified models in `imported-data`."[imported-data]@@ -429,7 +416,7 @@deleted (into #{} (filter legal-yaml-path?) (:deleted changed));; N+1: one query per deleted path (bounded by deletions in a single pull; left un-batched because;; file_path values are long, making an IN clause bulky for marginal gain).- deleted-rsos (mapv (fn [p] (t2/select-one :model/RemoteSyncObject :file_path p)) deleted)+ deleted-rsos (mapv remote-sync.db/rso-by-file-path deleted)ingestable (when (seq add-mod)(source.p/->ingestable snapshot {:path-filters (mapv #(re-pattern (java.util.regex.Pattern/quote %)) add-mod)}))add-models (if ingestable@@ -478,19 +465,19 @@;; N+1: one entity_id query per delete candidate (bounded by deletions in a single;; pull; batching would need grouping by model-key into per-table IN queries).:let [model-key (:model-key (spec/spec-for-model-type model_type))- eid (when model-key (t2/select-one-fn :entity_id model-key :id model_id))]+ eid (when model-key (remote-sync.db/entity-id model-key model_id))]:when (not (loaded-eid? model_type eid))]{:model_type model_type :model_id model_id :model-key model-key})sync-rows (spec/sync-all-entities! sync-timestamp imported-data)](remote-sync.task/update-progress! task-id 0.8)(t2/with-transaction [_conn](doseq [[model-key ds] (group-by :model-key deletes)]- (t2/delete! model-key :id [:in (mapv :model_id ds)]))+ (remote-sync.db/delete-instances! model-key (mapv :model_id ds)))(when (seq deletes)- (t2/delete! :model/RemoteSyncObject {:where (rso-where-for deletes)}))+ (remote-sync.db/delete-rsos-of-keys! deletes))(when (seq sync-rows);; fold file_path + content_hash into the insert so the touched rows are written once (chunked)- (t2/delete! :model/RemoteSyncObject {:where (rso-where-for sync-rows)})+ (remote-sync.db/delete-rsos-of-keys! sync-rows)(insert-with-metadata! sync-rows (when ingestable (source.ingestable/cached-file-paths ingestable))))(when finalize! (finalize!)));; We skip the whole-appdb reindex the full load runs. Added/modified entities are already@@ -510,7 +497,7 @@"Returns the current non-synced RemoteSyncObject rows — the local changes that have not been pushed.Captured before a local-only merge so they can be restored afterwards (see [[import-merged!]])."[]- (t2/select :model/RemoteSyncObject {:where [:not= :status "synced"]}))+ (remote-sync.db/unsynced-rsos))(defn- restore-dirty-objects!"Re-applies captured dirty statuses after a merge load (which marks everything 'synced'). For each@@ -518,11 +505,9 @@(e.g. a pending local deletion, whose entity is absent from the merged set)."[dirty-objects timestamp](doseq [{:keys [model_type model_id status] :as row} dirty-objects]- (if-let [existing (t2/select-one :model/RemoteSyncObject :model_type model_type :model_id model_id)]- (t2/update! :model/RemoteSyncObject (:id existing)- {:status status :status_changed_at timestamp})- (t2/insert! :model/RemoteSyncObject- (-> row (dissoc :id) (assoc :status_changed_at timestamp))))))+ (if-let [existing (remote-sync.db/rso model_type model_id)]+ (remote-sync.db/update-rso! (:id existing) {:status status :status_changed_at timestamp})+ (remote-sync.db/insert-rso! (-> row (dissoc :id) (assoc :status_changed_at timestamp))))))(defn- import-merged!"Import in merge mode. Should only be called when you have a base-snapshot and its version differs from snaphot's version.@@ -778,7 +763,7 @@(let [pulled (apply + (vals summary))](load-snapshot! merged-snapshot task-id sync-timestamp:finalize! (fn []- (t2/update! :model/RemoteSyncObject {:status "synced" :status_changed_at sync-timestamp})+ (remote-sync.db/mark-all-rsos-synced! sync-timestamp)(remote-sync.task/set-version! task-id version)))(log/infof "Exported with merge: folded in %d remote change(s) (added %d, updated %d, removed %d); pushed %d"pulled (:added summary) (:updated summary) (:removed summary) (if empty? 0 pushed-count))@@ -833,7 +818,7 @@(filter (fn [{:keys [model_type model_id]}](and (not (and (= model_type model-type) (= model_id model-id)))(spec/spec-for-model-type model_type)- (not (t2/exists? :model/RemoteSyncObject :model_type model_type :model_id model_id)))))+ (not (remote-sync.db/rso-exists? model_type model_id)))))(export-closure model-type model-id)))(defn- ->sized-chunks@@ -1074,7 +1059,7 @@(defn- exportable-write-rows"WriteRows for a full export — every exportable id tagged with its RemoteSyncObject id (untracked deps get :id nil)."[]- (let [rso-id (u/index-by (juxt :model_type :model_id) :id (t2/select [:model/RemoteSyncObject :id :model_type :model_id]))]+ (let [rso-id (u/index-by (juxt :model_type :model_id) :id (remote-sync.db/rso-keys))](for [[model ids] (spec/exportable-entities)id ids]{:model_type model :model_id id :id (rso-id [model id])})))@@ -1084,8 +1069,7 @@`targets`), matching the incremental path; path/hybrid and still-exported rows are kept."[exported-rows](let [exported (into #{} (map #(select-keys % [:model_type :model_id])) exported-rows)]- (->> (t2/select [:model/RemoteSyncObject :id :model_type :model_id]- :status [:in ["removed" "delete"]])+ (->> (remote-sync.db/departed-rso-keys)(filter #(= :entity-id (:identity (spec/spec-for-model-type (:model_type %)))))(remove #(exported (select-keys % [:model_type :model_id])))(map :id))))@@ -1096,24 +1080,8 @@scope: the incremental export passes only its write set, a full export passes every RemoteSyncObject id."[ids synced sync-timestamp](let [by-id (u/index-by :id synced)]- (doseq [id-chunk (partition-all app-db-batch-size ids)- :let [hits (filter by-id id-chunk)]]- (t2/update! :model/RemoteSyncObject- {:id [:in (vec id-chunk)]}- (cond-> {:status "synced" :status_changed_at sync-timestamp}- (seq hits)- (assoc :file_path (into [:case]- (concat- (mapcat (fn [id]- [[:= :id id] (:file_path (by-id id))])- hits)- [:else :file_path]))- :content_hash (into [:case]- (concat- (mapcat (fn [id]- [[:= :id id] (:content_hash (by-id id))])- hits)- [:else :content_hash]))))))))+ (doseq [id-chunk (partition-all app-db-batch-size ids)]+ (remote-sync.db/mark-rsos-synced! id-chunk (select-keys by-id id-chunk) sync-timestamp))))(def ^:private export-progress-plan-done 0.33) ; phase 1 (plan) complete / serialize start(def ^:private export-progress-serialize 0.66) ; phase 2 (serialize) complete@@ -1147,8 +1115,8 @@(when-not (= version :remote-sync/empty-commit)(remote-sync.task/set-version! task-id version))(doseq [removed-ids (partition-all 500 (find-departed-entities export-rows))]- (t2/delete! :model/RemoteSyncObject :id [:in removed-ids]))- (mark-rows-synced! (t2/select-pks-set :model/RemoteSyncObject) synced sync-timestamp))+ (remote-sync.db/delete-rsos! removed-ids))+ (mark-rows-synced! (remote-sync.db/all-rso-ids) synced sync-timestamp))(if (= version :remote-sync/empty-commit)(do(log/info "Remote sync full export: re-serialized content matches remote; skipped empty commit")@@ -1180,7 +1148,7 @@(remote-sync.task/set-version! task-id version));; delete departed rows first, then update RSO metadata — same order as full-export!(doseq [removed-ids (partition-all 500 removed-ids)]- (t2/delete! :model/RemoteSyncObject :id [:in removed-ids]))+ (remote-sync.db/delete-rsos! removed-ids))(mark-rows-synced! (map :id synced) synced sync-timestamp))(if (= version :remote-sync/empty-commit)(do (log/info "Remote sync incremental export: nothing changed; skipped empty commit")@@ -1406,7 +1374,7 @@[result task-id & [branch]](let [proceed?(t2/with-transaction [_conn]- (let [task (t2/select-one :model/RemoteSyncTask :id task-id {:for :update})]+ (let [task (remote-sync.db/lock-task task-id)](cond(nil? task)(do (log/warnf "Task %s missing during result handling; skipping" task-id)@@ -1439,7 +1407,7 @@(e.g. `{:branch \"main\"}`, plus `:auto true` for system-triggered syncs); `user-id` is nil forsystem-triggered syncs."[topic task-id details user-id]- (let [task (t2/select-one :model/RemoteSyncTask task-id)]+ (let [task (remote-sync.db/task task-id)](events/publish-event! topic{:object task:details detailsdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_object.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_object.cljindex e8604fea5a0..c1f6ad9765d 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_object.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_object.clj@@ -6,6 +6,7 @@and for Field/Segment/Table models, parent table information."(:require[clojure.set :as set]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.spec :as spec][metabase.util :as u][methodical.core :as methodical]@@ -24,23 +25,13 @@Returns true if any remote-synced object has a status other than 'synced', false otherwise.Excludes transform model types when transform sync is disabled."[]- (let [excluded (spec/excluded-model-types)]- (if (empty? excluded)- (t2/exists? :model/RemoteSyncObject :status [:not= "synced"])- (t2/exists? :model/RemoteSyncObject- :status [:not= "synced"]- :model_type [:not-in excluded]))))+ (remote-sync.db/dirty-rso-exists? (spec/excluded-model-types)))(defn dirty-rows"Returns the raw RemoteSyncObject rows that are not yet synced (status != 'synced'),excluding disabled model types (e.g. transforms when transform sync is off)."[]- (let [excluded (spec/excluded-model-types)]- (if (empty? excluded)- (t2/select :model/RemoteSyncObject :status [:not= "synced"])- (t2/select :model/RemoteSyncObject- :status [:not= "synced"]- :model_type [:not-in excluded]))))+ (remote-sync.db/dirty-rsos (spec/excluded-model-types)))(defn dirty-objects"Gets all models in any collection that are dirty with their sync status.diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_task.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_task.cljindex c26a1b3deba..10b5b5a2247 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_task.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/models/remote_sync_task.clj@@ -2,6 +2,7 @@"Model for tracking remote sync tasks and their progress."(:require[java-time.api :as t]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase.models.interface :as mi][metabase.settings.core :as setting][metabase.util.malli :as mu]@@ -46,12 +47,11 @@[sync-task-type :- ::remote-sync-task-typeuser-id :- [:maybe pos-int?] &[additional-fields :- [:map]]]- (t2/insert-returning-instance! :model/RemoteSyncTask- (merge {:sync_task_type sync-task-type- :initiated_by user-id- :progress 0- :started_at (mi/now)}- additional-fields)))+ (remote-sync.db/insert-task! (merge {:sync_task_type sync-task-type+ :initiated_by user-id+ :progress 0+ :started_at (mi/now)}+ additional-fields)))(defn cancel-sync-task!"Marks a sync task as cancelled.@@ -63,10 +63,10 @@This signal will be checked in update-progress! to stop further processing. Note that the worker thread mustmanually check this flag rather than being interrupted, as interrupting Quartz threads can cause issues."[task-id]- (t2/update! :model/RemoteSyncTask task-id- {:cancelled true- :ended_at (mi/now)- :error_message "Task cancelled"}))+ (remote-sync.db/update-task! task-id+ {:cancelled true+ :ended_at (mi/now)+ :error_message "Task cancelled"}))(defn update-progress!"Updates the progress of a sync task.@@ -77,12 +77,12 @@Throws ExceptionInfo if the task has been marked as cancelled."[task-id progress]- (when (true? (t2/select-one-fn :cancelled :model/RemoteSyncTask :id task-id))+ (when (true? (remote-sync.db/task-cancelled? task-id))(throw (ex-info "Remote sync task has been cancelled" {:task-id task-id:cancelled? true})))- (t2/update! :model/RemoteSyncTask task-id- {:progress progress- :last_progress_report_at (mi/now)}))+ (remote-sync.db/update-task! task-id+ {:progress progress+ :last_progress_report_at (mi/now)}))(def ^:private default-progress-throttle-ms"Minimum ms between throttled (non-boundary) progress writes."@@ -124,8 +124,7 @@Returns the number of rows updated (should be 1 if successful)."[task-id version]- (t2/update! :model/RemoteSyncTask task-id- {:version version}))+ (remote-sync.db/update-task! task-id {:version version}))(defn complete-sync-task!"Marks a sync task as completed.@@ -137,10 +136,10 @@Returns the number of rows updated (should be 1 if successful)."([task-id] (complete-sync-task! task-id nil))([task-id outcome]- (t2/update! :model/RemoteSyncTask task-id- {:progress 1.0- :ended_at (mi/now)- :outcome outcome})))+ (remote-sync.db/update-task! task-id+ {:progress 1.0+ :ended_at (mi/now)+ :outcome outcome})))(defn fail-sync-task!"Marks a sync task as failed.@@ -149,9 +148,9 @@Returns the number of rows updated (should be 1 if successful)."[task-id error-msg]- (t2/update! :model/RemoteSyncTask task-id- {:ended_at (mi/now)- :error_message error-msg}))+ (remote-sync.db/update-task! task-id+ {:ended_at (mi/now)+ :error_message error-msg}))(defn current-task"Gets the current active sync task.@@ -159,16 +158,7 @@Returns the most recent RemoteSyncTask that is still running (started but not ended, and has reported progresswithin the time limit), or nil if no active task exists."[]- (t2/select-one :model/RemoteSyncTask- {:where [:and- [:<> :started_at nil]- [:= :ended_at nil]- [:<- (t/minus (t/offset-date-time) (t/millis (setting/get :remote-sync-task-time-limit-ms)))- :last_progress_report_at]]- :limit 1- :order-by [[:started_at :desc]- [:id :desc]]}))+ (remote-sync.db/current-task (t/minus (t/offset-date-time) (t/millis (setting/get :remote-sync-task-time-limit-ms)))))(defn supersede-stale-tasks!"Marks any genuinely stale task rows as cancelled and terminated.@@ -187,26 +177,14 @@[](let [cutoff (t/minus (t/offset-date-time)(t/millis (setting/get :remote-sync-task-time-limit-ms)))]- (t2/query {:update (t2/table-name :model/RemoteSyncTask)- :set {:cancelled true- :ended_at (mi/now)- :error_message "Superseded after staleness timeout"}- :where [:and- [:<> :started_at nil]- [:= :ended_at nil]- [:< :last_progress_report_at cutoff]]})))+ (remote-sync.db/supersede-stale-tasks! cutoff (mi/now))))(defn most-recent-task"Gets the most recently run task, including currently running tasks.Returns the most recent RemoteSyncTask (running or completed), or nil if no tasks exist."[]- (t2/select-one :model/RemoteSyncTask- {:where [:and- [:<> :started_at nil]]- :limit 1- :order-by [[:started_at :desc]- [:id :desc]]}))+ (remote-sync.db/most-recent-task))(defn last-version"Gets the version that any changes are built off of.@@ -214,15 +192,7 @@Returns the version string from the most recent successful task (either export or import), or nil if no successfultasks exist."[]- (:version (t2/select-one :model/RemoteSyncTask- {:where [:and- [:<> nil :ended_at]- [:= false :cancelled]- [:= nil :error_message]- [:<> nil :version]]- :limit 1- :order-by [[:started_at :desc]- [:id :desc]]})))+ (:version (remote-sync.db/last-successful-task)))(defn running?"Checks if a task is currently running.@@ -295,9 +265,9 @@Returns the number of rows updated (should be 1 if successful)."[task-id conflicts]- (t2/update! :model/RemoteSyncTask task-id- {:ended_at (mi/now)- :conflicts conflicts}))+ (remote-sync.db/update-task! task-id+ {:ended_at (mi/now)+ :conflicts conflicts}));;; ------------------------------------------- Hydration -------------------------------------------@@ -305,7 +275,7 @@[_model k tasks](mi/instances-with-hydrated-datatasks k- #(t2/select-pk->fn identity :model/User :id [:in (map :initiated_by tasks)])+ #(remote-sync.db/users-by-id (map :initiated_by tasks)):initiated_by))(methodical/defmethod t2/batched-hydrate [:model/RemoteSyncTask :status]diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/settings.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/settings.cljindex 7cd540ab6fe..be236083971 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/settings.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/settings.clj@@ -2,6 +2,7 @@(:require[clojure.string :as str][java-time.api :as t]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.guards :as guards][metabase-enterprise.remote-sync.source.git :as git][metabase.collections.models.collection :as collection]@@ -111,35 +112,27 @@spurious 'delete' entries when going from default false to explicitly false)."[enabled?](let [timestamp (t/offset-date-time)- existing-rso (t2/select-one :model/RemoteSyncObject- :model_type "Collection"- :model_id transforms-root-id)]+ existing-rso (remote-sync.db/rso "Collection" transforms-root-id)](cond;; When enabling, always create/update to 'create' statusenabled?(do(when existing-rso- (t2/delete! :model/RemoteSyncObject- :model_type "Collection"- :model_id transforms-root-id))- (t2/insert! :model/RemoteSyncObject- {:model_type "Collection"- :model_id transforms-root-id- :model_name "Transforms"- :status "create"- :status_changed_at timestamp}))+ (remote-sync.db/delete-rso-of! "Collection" transforms-root-id))+ (remote-sync.db/insert-rso! {:model_type "Collection"+ :model_id transforms-root-id+ :model_name "Transforms"+ :status "create"+ :status_changed_at timestamp}));; When disabling and there's an existing RSO, update to 'delete' statusexisting-rso(do- (t2/delete! :model/RemoteSyncObject- :model_type "Collection"- :model_id transforms-root-id)- (t2/insert! :model/RemoteSyncObject- {:model_type "Collection"- :model_id transforms-root-id- :model_name "Transforms"- :status "delete"- :status_changed_at timestamp}))+ (remote-sync.db/delete-rso-of! "Collection" transforms-root-id)+ (remote-sync.db/insert-rso! {:model_type "Collection"+ :model_id transforms-root-id+ :model_name "Transforms"+ :status "delete"+ :status_changed_at timestamp}));; When disabling and there's no existing RSO, do nothing;; (this avoids creating spurious 'delete' entries when going from default false to explicitly false):elsediff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.cljindex 5d1a82ee982..31c59c3c935 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj@@ -13,15 +13,14 @@(:require[clojure.set :as set][clojure.string :as str]- [clojure.walk :as walk]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.settings :as rs-settings][metabase-enterprise.transforms-python.core :as transforms-python][metabase.collections.core :as collections][metabase.collections.models.collection :as collection][metabase.models.serialization :as serdes][metabase.settings.core :as setting]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(set! *warn-on-reflection* true)@@ -55,7 +54,9 @@- :archived-key - Key to check for archived status (nil if model has no archived concept)- :tracking - RemoteSyncObject field configuration::select-fields - Fields to select for hydration- :hydrate-query - Optional custom query for joins (overrides select-fields)+ :hydrate-query? - When true, hydrate via the model's+ `metabase-enterprise.remote-sync.db` tracking-join query instead of+ :select-fields (Field, Segment, Measure):field-mappings - Map of RemoteSyncObject column -> source field or [field transform-fn]- :conditions - Optional map of conditions for filtering syncable entities.Only entities matching these conditions are eligible for sync@@ -208,12 +209,7 @@:types [:create :update :delete]}:eligibility {:type :parent-table}:archived-key nil ; fields don't have archived- :tracking {:hydrate-query {:select [:f.name :f.table_id- [:t.collection_id :collection_id]- [:t.name :table_name]]- :from [[:metabase_field :f]]- :join [[:metabase_table :t] [:= :f.table_id :t.id]]- :where [:= :f.id :?id]}+ :tracking {:hydrate-query? true:field-mappings {:model_name :name:model_collection_id :collection_id:model_table_id :table_id@@ -231,12 +227,7 @@:types [:create :update :delete]}:eligibility {:type :parent-table}:archived-key :archived- :tracking {:hydrate-query {:select [:s.name :s.table_id- [:t.collection_id :collection_id]- [:t.name :table_name]]- :from [[:segment :s]]- :join [[:metabase_table :t] [:= :s.table_id :t.id]]- :where [:= :s.id :?id]}+ :tracking {:hydrate-query? true:field-mappings {:model_name :name:model_collection_id :collection_id:model_table_id :table_id@@ -254,14 +245,7 @@:types [:create :update :delete]}:eligibility {:type :parent-table}:archived-key :archived- ;; Note: hydrate-query uses :s alias because query-entities-for-sync :hybrid- ;; hardcodes :s.id and :s.entity_id references- :tracking {:hydrate-query {:select [:s.name :s.table_id- [:t.collection_id :collection_id]- [:t.name :table_name]]- :from [[:measure :s]]- :join [[:metabase_table :t] [:= :s.table_id :t.id]]- :where [:= :s.id :?id]}+ :tracking {:hydrate-query? true:field-mappings {:model_name :name:model_collection_id :collection_id:model_table_id :table_id@@ -501,16 +485,13 @@:let [spec (spec-for-model-type model-type)model-key (:model-key spec)]:when (and spec model-key (#{:entity-id :hybrid} (:identity spec)))- :let [local-entity-ids (t2/select-fn-set :entity_id model-key :entity_id [:in entity-ids])+ :let [local-entity-ids (remote-sync.db/existing-entity-ids model-key entity-ids)tracked-entity-ids (when (seq local-entity-ids)- (let [pks (t2/select-pks-vec model-key- :entity_id [:in local-entity-ids])]- (t2/select-fn-set- (fn [rso]- (:entity_id (t2/select-one model-key :id (:model_id rso))))- :model/RemoteSyncObject- :model_type model-type- :model_id [:in pks])))+ (let [pks (remote-sync.db/ids-by-entity-ids model-key local-entity-ids)]+ (into #{}+ (map (fn [rso]+ (:entity_id (remote-sync.db/instance model-key (:model_id rso)))))+ (remote-sync.db/rsos-of-models model-type pks))))conflicting-entity-ids (set/difference local-entity-ids (or tracked-entity-ids #{}))conflicting-entity-ids (if (= model-type "Collection")(disj conflicting-entity-ids collection/library-entity-id)@@ -528,10 +509,8 @@(let [model-key (:model-key spec)model-type (:model-type spec)conditions (export-conditions spec)- local-count (if conditions- (apply t2/count model-key (into [] cat conditions))- (t2/count model-key))- synced-count (t2/count :model/RemoteSyncObject :model_type model-type)]+ local-count (remote-sync.db/count-where model-key conditions)+ synced-count (remote-sync.db/rso-count-of-type model-type)](and (pos? local-count)(> local-count synced-count))))specs-for-feature))@@ -578,16 +557,14 @@(keyword? setting-kw) (boolean (setting/get-value-of-type :boolean setting-kw)):else false)]:when (not setting-enabled?)- :let [local-ns-colls (t2/select [:model/Collection :id :entity_id] :namespace ns-name)+ :let [local-ns-colls (remote-sync.db/collections-in-namespace ns-name)import-eids (get import-ns-collection-entity-ids ns-name #{});; Only consider local collections that are NOT in the import (truly local-only);; and NOT tracked in RemoteSyncObjectunsynced-local (remove(fn [coll](or (contains? import-eids (:entity_id coll))- (t2/exists? :model/RemoteSyncObject- :model_type "Collection"- :model_id (:id coll))))+ (remote-sync.db/rso-exists? "Collection" (:id coll))))local-ns-colls)]:when (seq unsynced-local)]{:type (keyword (str (u/lower-case-en category) "-conflict"))@@ -595,49 +572,15 @@:message (format "Import contains %s but local instance has unsynced %s namespace collections"category category)}))))-(defn- removal-condition-clauses- "Converts a spec's removal-conditions map into HoneySQL where-fragments: an :entity_id entry whose value is- an [op value] pair becomes [op :entity_id value]; any other entry with a vector value becomes- [:in key value]; a scalar value becomes [:= key value]. (A scalar-only [:= key [...]] rendering would- silently produce a broken condition for vector values.)"- [removal-conds]- (for [[k v] removal-conds]- (cond- (and (= k :entity_id) (vector? v)) (let [[op value] v] [op :entity_id value])- (vector? v) [:in k v]- :else [:= k v])))--(defn removal-where-clauses- "The AND-clauses selecting the rows an import reconcile removes for one entity-id `spec`: rows scoped to- `synced-collection-ids` (when the spec has a `:scope-key`), minus the imported `entity-ids`, honoring the- spec's removal conditions.-- Returns nil for a scoped model with no synced collections (removes nothing); an empty vector means no- predicate (a global, unconditioned delete)."+(defn- removal-opts+ "The `metabase-enterprise.remote-sync.db` removal-opts (`:scope-key`, `:synced-collection-ids`, `:entity-ids`,+ `:removal-conditions`) for removing the entity-id `spec`'s rows not in the import, scoped to+ `synced-collection-ids` when the spec has a `:scope-key`, minus the imported `entity-ids`."[spec synced-collection-ids entity-ids]- (let [scope-key (get-in spec [:removal :scope-key])]- (when-not (and scope-key (empty? synced-collection-ids))- (cond-> []- scope-key (conj [:in scope-key synced-collection-ids])- (seq entity-ids) (conj [:not-in :entity_id entity-ids])- :always (into (removal-condition-clauses (removal-conditions spec)))))))--(defn- model-id-column- "The qualified id column of a model's own table (e.g. :report_card.id), for correlating a subquery."- [model-key]- (keyword (str (name (t2/table-name model-key)) ".id")))--(defn- unsynced-anti-join- "A [:not [:exists ...]] HoneySQL fragment keeping only rows with no RemoteSyncObject in 'synced' status —- i.e. unsynced local work (an already-synced entity's removal is a normal reconcile, not data loss).- `id-col` is the qualified id column of the model's own table (see [[model-id-column]])."- [model-type id-col]- [:not [:exists ^:allow-subquery {:select [1]- :from [:remote_sync_object]- :where [:and- [:= :remote_sync_object.model_type model-type]- [:= :remote_sync_object.model_id id-col]- [:= :remote_sync_object.status "synced"]]}]])+ {:scope-key (get-in spec [:removal :scope-key])+ :synced-collection-ids synced-collection-ids+ :entity-ids entity-ids+ :removal-conditions (removal-conditions spec)})(defn check-deletion-conflicts"Detects local entities of all-or-nothing models (specs with :all-on-setting-disable) that an import@@ -655,12 +598,10 @@:when setting-kw:let [model-type (:model-type spec)imported-ids (get by-entity-id model-type #{})- ;; These models are unscoped (no :scope-key), so removal-where-clauses just yields the- ;; not-in-import + removal-condition clauses; the anti-join keeps the unsynced ones.- where (-> [:and]- (into (removal-where-clauses spec nil imported-ids))- (conj (unsynced-anti-join model-type (model-id-column model-key))))- n-unsynced (t2/count model-key {:where where})]+ ;; These models are unscoped (no :scope-key), so the removal-opts just carry the+ ;; not-in-import + removal-condition restrictions; unsynced-instance-count adds the anti-join.+ n-unsynced (remote-sync.db/unsynced-instance-count+ model-key model-type (removal-opts spec nil imported-ids))]:when (pos? n-unsynced):let [category (setting->category setting-kw)]]{:type (keyword (str (u/lower-case-en category) "-conflict"))@@ -706,11 +647,11 @@[](into []cat- [(t2/select-pks-vec :model/Collection :is_remote_synced true)+ [(remote-sync.db/remote-synced-collection-ids)(when (rs-settings/remote-sync-transforms)- (t2/select-pks-vec :model/Collection :namespace (name collections/transforms-ns)))+ (remote-sync.db/collection-ids-in-namespace (name collections/transforms-ns)))(when (rs-settings/library-is-remote-synced?)- (t2/select-pks-vec :model/Collection :namespace "snippets"))]))+ (remote-sync.db/collection-ids-in-namespace "snippets"))]))(def ^:private max-conflict-names"Cap on how many entity names a collection deletion conflict carries, so the payload stays bounded when@@ -738,20 +679,18 @@(not= :model/Collection model-key)):let [model-type (:model-type spec)imported-ids (get by-entity-id model-type #{})- ;; Same base predicate remove-unsynced! deletes by, plus an anti-join keeping only the+ ;; Same base restriction remove-unsynced! deletes by, plus an anti-join keeping only the;; unsynced rows the import would delete. Done in SQL so we never materialize a whole;; collection's worth of rows just to count/sample them.- where (-> [:and]- (into (removal-where-clauses spec synced-collection-ids imported-ids))- (conj (unsynced-anti-join model-type (model-id-column model-key))))- n (t2/count model-key {:where where})]+ opts (removal-opts spec synced-collection-ids imported-ids)+ n (remote-sync.db/unsynced-instance-count model-key model-type opts)]:when (pos? n)]{:type (keyword (str (u/lower-case-en model-type) "-deletion-conflict")):category model-type:model model-type:count n;; A bounded sample of names for the UI; :count above is the true total.- :names (t2/select-fn-vec :name model-key {:where where :limit max-conflict-names})+ :names (remote-sync.db/unsynced-instance-names model-key model-type opts max-conflict-names):message (format "Import would delete %d unsynced local %s %s"n model-type (if (= 1 n) "entity" "entities"))})))))@@ -816,7 +755,7 @@(defmethod check-eligibility-by-type :parent-table[{:keys [parent-model]} {:keys [table_id]}](when table_id- (when-let [table (t2/select-one parent-model :id table_id)]+ (when-let [table (remote-sync.db/instance parent-model table_id)](check-eligibility (spec-for-model-key parent-model) table))))(defmethod check-eligibility-by-type :setting@@ -883,16 +822,12 @@"Hydrates model details for RemoteSyncObject based on spec.Returns a map with the fields needed to populate the sync object."[{:keys [model-key tracking]} model-id]- (if-let [query (:hydrate-query tracking)]- ;; Use custom query for joins (Field, Segment)- (first (t2/query (update query :where- (fn [where-clause]- (walk/postwalk- #(if (= % :?id) model-id %)- where-clause)))))+ (if (:hydrate-query? tracking)+ ;; Use the tracking-join query for models needing a Table join (Field, Segment, Measure)+ (remote-sync.db/tracking-details-by-id model-key model-id);; Simple select using select-fields(when-let [fields (:select-fields tracking)]- (t2/select-one (into [model-key] fields) :id model-id))))+ (remote-sync.db/instance-with-columns model-key fields model-id))))(defn build-sync-object-fields"Builds the fields map for RemoteSyncObject from hydrated model details.@@ -1058,7 +993,7 @@(when (seq entity-ids)(let [;; Get select fields from spec, with :id always includedselect-fields (into [:id] (or (:select-fields tracking) [:name :collection_id]))- entities (t2/select (into [model-key] select-fields) :entity_id [:in entity-ids])]+ entities (remote-sync.db/instances-with-columns-by-entity-ids model-key select-fields entity-ids)](map (fn [entity](let [;; Apply field mappingsfield-mappings (:field-mappings tracking)@@ -1081,49 +1016,27 @@(defmethod query-entities-for-sync :hybrid;; Hybrid models like Segment need a join query for table info- [{:keys [model-type tracking]} entity-ids timestamp]+ [{:keys [model-type model-key tracking]} entity-ids timestamp](when (seq entity-ids)- (when-let [query-template (:hydrate-query tracking)]- ;; Use custom hydrate query adapted for batch lookup- ;; Keep the existing from/join structure, just modify select and where- ;; The query template uses alias :s for the main model (segment)- (let [base-query (-> query-template- (update :select (fn [cols] (vec (concat [:s.id] cols))))- (assoc :where [:in :s.entity_id entity-ids]))]- (->> (t2/query base-query)- (map (fn [entity]- (let [field-mappings (:field-mappings tracking)- mapped-fields (into {}- (for [[sync-field source-spec] field-mappings]- [sync-field (get entity source-spec)]))]- (merge {:model_type model-type- :model_id (:id entity)- :status "synced"- :status_changed_at timestamp}- mapped-fields)))))))))--(defn- build-path-where-clause- "Builds an :or where clause for path-based lookups."- [paths has-field?]- (into [:or]- (for [path paths]- (let [{:keys [db_name schema table_name field_name]} path]- (cond-> [:and- [:= :db.name db_name]- (if schema [:= :t.schema schema] [:is :t.schema nil])- [:= :t.name table_name]]- (and has-field? field_name)- (conj [:= :f.name field_name]))))))+ (when (:hydrate-query? tracking)+ (->> (remote-sync.db/tracking-details-by-entity-ids model-key entity-ids)+ (map (fn [entity]+ (let [field-mappings (:field-mappings tracking)+ mapped-fields (into {}+ (for [[sync-field source-spec] field-mappings]+ [sync-field (get entity source-spec)]))]+ (merge {:model_type model-type+ :model_id (:id entity)+ :status "synced"+ :status_changed_at timestamp}+ mapped-fields))))))))(defmethod query-entities-for-sync :path[{:keys [model-type model-key]} paths timestamp](when (seq paths)(case model-key:model/Table- (->> (t2/query {:select [:t.id :t.name :t.collection_id]- :from [[:metabase_table :t]]- :join [[:metabase_database :db] [:= :db.id :t.db_id]]- :where (build-path-where-clause paths false)})+ (->> (remote-sync.db/tables-at-paths paths)(map (fn [{:keys [id name collection_id]}]{:model_type model-type:model_id id@@ -1136,11 +1049,7 @@:status_changed_at timestamp}))):model/Field- (->> (t2/query {:select [:f.id :f.name :f.table_id [:t.collection_id :collection_id] [:t.name :table_name]]- :from [[:metabase_field :f]]- :join [[:metabase_table :t] [:= :t.id :f.table_id]- [:metabase_database :db] [:= :db.id :t.db_id]]- :where (build-path-where-clause paths true)})+ (->> (remote-sync.db/fields-at-paths paths)(map (fn [{:keys [id name table_id table_name collection_id]}]{:model_type model-type:model_id id@@ -1190,42 +1099,26 @@(case (or export-scope :derived):root-collections;; Excludes archived collections - their files are handled by the removal logic- (concat- (t2/select-fn-set (juxt (constantly "Collection") :id)- :model/Collection- {:where [:and- [:= :is_remote_synced true]- [:= :location "/"]- [:not :archived]]})- (when (rs-settings/remote-sync-transforms)- (t2/select-fn-set (juxt (constantly "Collection") :id)- :model/Collection- {:where [:and- [:= :namespace (name collections/transforms-ns)]- [:= :location "/"]- [:not :archived]]}))- (when (rs-settings/library-is-remote-synced?)- (t2/select-fn-set (juxt (constantly "Collection") :id)- :model/Collection- {:where [:and- [:= :namespace "snippets"]- [:= :location "/"]- [:not :archived]]})))+ (let [collection-keys (fn [ids] (into #{} (map (fn [id] ["Collection" id])) ids))]+ (concat+ (collection-keys (remote-sync.db/unarchived-remote-synced-root-collection-ids))+ (when (rs-settings/remote-sync-transforms)+ (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace (name collections/transforms-ns))))+ (when (rs-settings/library-is-remote-synced?)+ (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace "snippets"))))):derivednil))(defmethod query-export-roots :setting[{:keys [export-scope model-key model-type] :as spec}](when (spec-enabled? spec)- (let [conditions (export-conditions spec)]+ (let [conditions (export-conditions spec)+ model-keys (fn [ids] (into #{} (map (fn [id] [model-type id])) ids))](case export-scope:root-only- (apply t2/select-fn-set (juxt (constantly model-type) :id) model-key- :collection_id nil- (into [] cat conditions))+ (model-keys (remote-sync.db/ids-where model-key (assoc conditions :collection_id nil))):all- (apply t2/select-fn-set (juxt (constantly model-type) :id) model-key- (into [] cat conditions))+ (model-keys (remote-sync.db/ids-where model-key conditions))nil))))(defmethod query-export-roots :published-table [_] nil)@@ -1236,9 +1129,9 @@(when (spec-enabled? spec)(case export-scope:all- (if archived-key- (t2/select-fn-set (juxt (constantly model-type) :id) model-key archived-key false)- (t2/select-fn-set (juxt (constantly model-type) :id) model-key))+ (into #{}+ (map (fn [id] [model-type id]))+ (remote-sync.db/ids-where model-key (when archived-key {archived-key false})))nil)))(defmethod query-export-roots :default [_] nil)diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/task/table_cleanup.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/task/table_cleanup.cljindex 84919f09af7..bbf5207e09e 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/task/table_cleanup.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/task/table_cleanup.clj@@ -5,9 +5,9 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(org.quartz DisallowConcurrentExecution)))@@ -30,7 +30,7 @@[](log/infof "Attempting to delete remote_sync_task records older than %d days." retention-days)(let [cutoff-date (t/minus (t/offset-date-time) (t/days retention-days))- deleted-count (t2/delete! :model/RemoteSyncTask {:where [:< :started_at cutoff-date]})]+ deleted-count (remote-sync.db/delete-tasks-started-before! cutoff-date)](log/infof "Deleted %d remote_sync_task records. Cleanup successful." deleted-count)deleted-count))diff --git a/enterprise/backend/src/metabase_enterprise/replacement/api.clj b/enterprise/backend/src/metabase_enterprise/replacement/api.cljindex 1affa1cab52..f69bd8bb9c4 100644--- a/enterprise/backend/src/metabase_enterprise/replacement/api.clj+++ b/enterprise/backend/src/metabase_enterprise/replacement/api.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.replacement.api"`/api/ee/replacement/` routes"(:require+ [metabase-enterprise.replacement.db :as replacement.db][metabase-enterprise.replacement.execute :as replacement.execute][metabase-enterprise.replacement.models.replacement-run :as replacement-run][metabase-enterprise.replacement.runner :as replacement.runner]@@ -12,8 +13,7 @@[metabase.api.routes.common :refer [+auth]][metabase.transforms.core :as transforms][metabase.transforms.schema :as transforms.schema]- [ring.util.response :as response]- [toucan2.core :as t2]))+ [ring.util.response :as response]))(set! *warn-on-reflection* true)@@ -103,7 +103,7 @@[:transform_tag_ids {:optional true} [:maybe [:sequential pos-int?]]]]](api/check-superuser)(let [user-id api/*current-user-id*- card (api/check-404 (t2/select-one :model/Card :id card_id))+ card (api/check-404 (replacement.db/card card_id))transform (transforms/create-transform!{:name transform_name:source {:type :query@@ -140,22 +140,20 @@[_route-params{:keys [is-active]} :- [:map [:is-active {:optional true} [:maybe :boolean]]]](api/check-superuser)- (t2/select :model/ReplacementRun- (cond-> {:order-by [[:start_time :desc]]}- (some? is-active) (assoc :where [:= :is_active is-active]))))+ (replacement.db/runs is-active))(api.macros/defendpoint :get "/runs/:id" :- ::replacement.schema/run"Get the status of a source replacement run."[{:keys [id]} :- [:map [:id ::replacement.schema/run-id]]](api/check-superuser)- (or (t2/select-one :model/ReplacementRun :id id)+ (or (replacement.db/run id)(throw (ex-info "Run not found" {:status-code 404}))))(api.macros/defendpoint :post "/runs/:id/cancel" :- [:map [:success boolean?]]"Cancel a running source replacement."[{:keys [id]} :- [:map [:id ::replacement.schema/run-id]]](api/check-superuser)- (let [run (t2/select-one :model/ReplacementRun :id id)]+ (let [run (replacement.db/run id)](when-not run(throw (ex-info "Run not found" {:status-code 404})))(when-not (:is_active run)diff --git a/enterprise/backend/src/metabase_enterprise/replacement/db.clj b/enterprise/backend/src/metabase_enterprise/replacement/db.cljnew file mode 100644index 00000000000..fe49d29d30e--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/replacement/db.clj@@ -0,0 +1,200 @@+(ns metabase-enterprise.replacement.db+ "Application database queries for the replacement module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn run+ "The ReplacementRun with `run-id`, or nil."+ [run-id]+ (t2/select-one :model/ReplacementRun :id run-id))++(defn runs+ "The ReplacementRuns, newest first, restricted to the `is-active` flag when given."+ [is-active]+ (t2/select :model/ReplacementRun+ (cond-> {:order-by [[:start_time :desc]]}+ (some? is-active) (assoc :where [:= :is_active is-active]))))++(defn active-run+ "The active ReplacementRun, or nil."+ []+ (t2/select-one :model/ReplacementRun :is_active true))++(defn run-active-flag+ "The `:is_active` row of the ReplacementRun with `run-id`, or nil."+ [run-id]+ (t2/select-one [:model/ReplacementRun :is_active] :id run-id))++(defn insert-run!+ "Insert `run` and return the new instance."+ [run]+ (t2/insert-returning-instance! :model/ReplacementRun run))++(defn update-run!+ "Apply `changes` to the ReplacementRun with `run-id`."+ [run-id changes]+ (t2/update! :model/ReplacementRun :id run-id changes))++(defn update-active-run!+ "Apply `changes` to the ReplacementRun with `run-id` if it is active."+ [run-id changes]+ (t2/update! :model/ReplacementRun :id run-id :is_active true changes))++(defn time-out-active-runs-older-than!+ "Mark the active ReplacementRuns started more than `age` `unit`s ago as timed out."+ [age unit]+ (t2/update! :model/ReplacementRun+ :is_active true+ :start_time [:< (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]+ {:status :timeout+ :is_active nil+ :end_time :%now+ :message "Timed out by metabase"}))++(defn cards-with-ids+ "The Cards with `ids`."+ [ids]+ (t2/select :model/Card :id [:in ids]))++(defn tables-with-ids+ "The Tables with `ids`."+ [ids]+ (t2/select :model/Table :id [:in ids]))++(defn dashboards-with-ids+ "The Dashboards with `ids`."+ [ids]+ (t2/select :model/Dashboard :id [:in ids]))++(defn transforms-with-ids+ "The Transforms with `ids`."+ [ids]+ (t2/select :model/Transform :id [:in ids]))++(defn segments-with-ids+ "The Segments with `ids`."+ [ids]+ (t2/select :model/Segment :id [:in ids]))++(defn measures-with-ids+ "The Measures with `ids`."+ [ids]+ (t2/select :model/Measure :id [:in ids]))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn cards-by-id+ "A map of Card ID to Card for `card-ids`."+ [card-ids]+ (t2/select-pk->fn identity :model/Card :id [:in card-ids]))++(defn card-database-id+ "The Database ID of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :database_id :model/Card :id card-id))++(defn card-with-table-exists?+ "Whether one of the Cards with `card-ids` is on the Table with `table-id`."+ [card-ids table-id]+ (t2/exists? :model/Card :id [:in card-ids] :table_id table-id))++(defn update-card!+ "Apply `changes` to the Card with `card-id`."+ [card-id changes]+ (t2/update! :model/Card card-id changes))++(defn transform+ "The Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/Transform :id transform-id))++(defn update-transform!+ "Apply `changes` to the Transform with `transform-id`."+ [transform-id changes]+ (t2/update! :model/Transform transform-id changes))++(defn segment+ "The Segment with `segment-id`, or nil."+ [segment-id]+ (t2/select-one :model/Segment :id segment-id))++(defn update-segment!+ "Apply `changes` to the Segment with `segment-id`."+ [segment-id changes]+ (t2/update! :model/Segment segment-id changes))++(defn measure+ "The Measure with `measure-id`, or nil."+ [measure-id]+ (t2/select-one :model/Measure :id measure-id))++(defn update-measure!+ "Apply `changes` to the Measure with `measure-id`."+ [measure-id changes]+ (t2/update! :model/Measure measure-id changes))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn update-dashboard!+ "Apply `changes` to the Dashboard with `dashboard-id`."+ [dashboard-id changes]+ (t2/update! :model/Dashboard dashboard-id changes))++(defn dashboard-cards+ "The DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id))++(defn update-dashboard-card!+ "Apply `changes` to the DashboardCard with `dashcard-id`."+ [dashcard-id changes]+ (t2/update! :model/DashboardCard dashcard-id changes))++(defn table-database-id+ "The Database ID of the Table with `table-id`."+ [table-id]+ (t2/select-one-fn :db_id :model/Table :id table-id))++(defn active-fields-of-table+ "The active Fields of the Table with `table-id`."+ [table-id]+ (t2/select :model/Field :table_id table-id :active true))++(defn active-field-ids-of-table+ "The IDs of the active Fields of the Table with `table-id`."+ [table-id]+ (t2/select-pks-set :model/Field :table_id table-id :active true))++(defn active-fk-to-fields-exists?+ "Whether an active Field points at one of the Fields with `field-ids`."+ [field-ids]+ (t2/exists? :model/Field :fk_target_field_id [:in field-ids] :active true))++(defn update-field!+ "Apply `changes` to the Field with `field-id`."+ [field-id changes]+ (t2/update! :model/Field field-id changes))++(defn sandbox-exists-for-table?+ "Whether a Sandbox is defined on the Table with `table-id`."+ [table-id]+ (t2/exists? :model/Sandbox :table_id table-id))++(defn sandbox-card-ids+ "The IDs of the Cards Sandboxes are built on."+ []+ (t2/select-fn-set :card_id :model/Sandbox :card_id [:not= nil]))++(defn persisted-info-for-card+ "The PersistedInfo of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/PersistedInfo :card_id card-id))diff --git a/enterprise/backend/src/metabase_enterprise/replacement/field_refs.clj b/enterprise/backend/src/metabase_enterprise/replacement/field_refs.cljindex e12454bd590..ab183a99c9e 100644--- a/enterprise/backend/src/metabase_enterprise/replacement/field_refs.clj+++ b/enterprise/backend/src/metabase_enterprise/replacement/field_refs.clj@@ -1,12 +1,12 @@(ns metabase-enterprise.replacement.field-refs(:require+ [metabase-enterprise.replacement.db :as replacement.db][metabase-enterprise.replacement.util :as replacement.util][metabase-enterprise.replacement.walk :as replacement.walk][metabase.lib.core :as lib][metabase.lib.util :as lib.util][metabase.models.visualization-settings :as vs]- [metabase.source-swap.core :as source-swap]- [toucan2.core :as t2]))+ [metabase.source-swap.core :as source-swap]))(set! *warn-on-reflection* true)@@ -33,7 +33,7 @@[parameters](let [card-ids (replacement.walk/parameter-source-card-ids parameters)card-id->card (when (seq card-ids)- (t2/select-pk->fn identity :model/Card :id [:in card-ids]))]+ (replacement.db/cards-by-id card-ids))](if (seq card-ids)(replacement.walk/walk-parameter-source-card-refs parameters #(upgrade-source-card-ref %1 %2 card-id->card))parameters)))@@ -71,7 +71,7 @@(assoc :result_metadata (:result_metadata card):verified-result-metadata? true))](when (seq changes)- (t2/update! :model/Card (:id card) changes))))+ (replacement.db/update-card! (:id card) changes))))(defn- transform-upgrade-field-refs!"Upgrade field refs in `:source` for a transform."@@ -82,7 +82,7 @@(let [query (:query source)query' (source-swap/upgrade-field-refs-in-query query)](when (not= query query')- (t2/update! :model/Transform (:id transform) {:source (assoc source :query query')}))))))+ (replacement.db/update-transform! (:id transform) {:source (assoc source :query query')}))))))(defn- segment-upgrade-field-refs!"Upgrade field refs in `:definition` for a segment."@@ -91,7 +91,7 @@(let [query (:definition segment)query' (source-swap/upgrade-field-refs-in-query query)](when (not= query query')- (t2/update! :model/Segment (:id segment) {:definition query'})))))+ (replacement.db/update-segment! (:id segment) {:definition query'})))))(defn- measure-upgrade-field-refs!"Upgrade field refs in `:definition` for a measure."@@ -100,7 +100,7 @@(let [query (:definition measure)query' (source-swap/upgrade-field-refs-in-query query)](when (not= query query')- (t2/update! :model/Measure (:id measure) {:definition query'})))))+ (replacement.db/update-measure! (:id measure) {:definition query'})))))(defn- upgrade-parameter-target"Upgrade field refs in a parameter target."@@ -128,12 +128,12 @@(not= viz-settings viz-settings')(assoc :visualization_settings viz-settings'))](when (seq changes)- (t2/update! :model/DashboardCard (:id dashcard) changes))))+ (replacement.db/update-dashboard-card! (:id dashcard) changes))))(defn dashboard-upgrade-field-refs!"Upgrade field refs in `:parameters` for the `dashboard`, `:parameter_mappings` and `:visualization_settings` for all dashcards in the `dashboard`."[dashboard]- (let [dashcards (t2/select :model/DashboardCard :dashboard_id (:id dashboard))+ (let [dashcards (replacement.db/dashboard-cards (:id dashboard))parameters (or (:parameters dashboard) [])all-card-ids (into (replacement.walk/parameter-source-card-ids parameters)(mapcat (fn [dashcard]@@ -142,14 +142,14 @@(replacement.walk/viz-settings-click-behavior-card-ids (-> dashcard :visualization_settings vs/db->norm)))))dashcards)card-id->card (if (seq all-card-ids)- (t2/select-pk->fn identity :model/Card :id [:in all-card-ids])+ (replacement.db/cards-by-id all-card-ids){})parameters' (replacement.walk/walk-parameter-source-card-refs parameters #(upgrade-source-card-ref %1 %2 card-id->card))changes (cond-> {}(not= parameters parameters')(assoc :parameters parameters'))](when (seq changes)- (t2/update! :model/Dashboard (:id dashboard) changes))+ (replacement.db/update-dashboard! (:id dashboard) changes))(doseq [dashcard dashcards](dashcard-upgrade-field-refs! dashcard card-id->card))))@@ -160,11 +160,11 @@`entity` is an optional pre-fetched entity from bulk-load-metadata-for-entities!."([[entity-type entity-id :as entity-ref]](upgrade-field-refs! entity-ref (case entity-type- :card (t2/select-one :model/Card :id entity-id)- :transform (t2/select-one :model/Transform :id entity-id)- :segment (t2/select-one :model/Segment :id entity-id)- :measure (t2/select-one :model/Measure :id entity-id)- :dashboard (t2/select-one :model/Dashboard :id entity-id)+ :card (replacement.db/card entity-id)+ :transform (replacement.db/transform entity-id)+ :segment (replacement.db/segment entity-id)+ :measure (replacement.db/measure entity-id)+ :dashboard (replacement.db/dashboard entity-id)nil)))([[entity-type _entity-id] entity](case entity-typediff --git a/enterprise/backend/src/metabase_enterprise/replacement/models/replacement_run.clj b/enterprise/backend/src/metabase_enterprise/replacement/models/replacement_run.cljindex 82ab5312f05..b46790e1a26 100644--- a/enterprise/backend/src/metabase_enterprise/replacement/models/replacement_run.clj+++ b/enterprise/backend/src/metabase_enterprise/replacement/models/replacement_run.clj@@ -1,9 +1,8 @@(ns metabase-enterprise.replacement.models.replacement-run(:require+ [metabase-enterprise.replacement.db :as replacement.db][metabase-enterprise.replacement.protocols :as replacement.protocols]- [metabase.app-db.core :as mdb][metabase.models.interface :as mi]- [metabase.util.honey-sql-2 :as h2x][metabase.util.log :as log][methodical.core :as methodical][toucan2.core :as t2]))@@ -22,80 +21,63 @@(defn create-run!"Insert a new pending run. It becomes active when [[start-run!]] is called."[source-type source-id target-type target-id user-id]- (t2/insert-returning-instance! :model/ReplacementRun- {:source_entity_type source-type- :source_entity_id source-id- :target_entity_type target-type- :target_entity_id target-id- :user_id user-id- :status :pending- :is_active nil- :progress 0.0}))+ (replacement.db/insert-run! {:source_entity_type source-type+ :source_entity_id source-id+ :target_entity_type target-type+ :target_entity_id target-id+ :user_id user-id+ :status :pending+ :is_active nil+ :progress 0.0}))(defn start-run!"Mark the active run as started."[run-id]- (t2/update! :model/ReplacementRun- :id run-id- {:status :started- :is_active true}))+ (replacement.db/update-run! run-id+ {:status :started+ :is_active true}))(defn update-progress!"Update progress on the active run."[run-id progress]- (t2/update! :model/ReplacementRun- :id run-id- :is_active true- {:progress progress}))+ (replacement.db/update-active-run! run-id {:progress progress}))(defn succeed-run!"Mark the active run as succeeded."[run-id]- (t2/update! :model/ReplacementRun- :id run-id- :is_active true- {:status :succeeded- :progress 1.0- :is_active nil- :end_time :%now}))+ (replacement.db/update-active-run! run-id+ {:status :succeeded+ :progress 1.0+ :is_active nil+ :end_time :%now}))(defn fail-run!"Mark the active run as failed."[run-id message]- (t2/update! :model/ReplacementRun- :id run-id- :is_active true- {:status :failed- :is_active nil- :end_time :%now- :message message}))+ (replacement.db/update-active-run! run-id+ {:status :failed+ :is_active nil+ :end_time :%now+ :message message}))(defn cancel-run!"Mark the active run as canceled."[run-id]- (t2/update! :model/ReplacementRun- :id run-id- :is_active true- {:status :canceled- :is_active nil- :end_time :%now- :message "Canceled by user"}))+ (replacement.db/update-active-run! run-id+ {:status :canceled+ :is_active nil+ :end_time :%now+ :message "Canceled by user"}))(defn timeout-old-runs!"Time out all active runs older than the specified age."[age unit]- (t2/update! :model/ReplacementRun- :is_active true- :start_time [:< (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]- {:status :timeout- :is_active nil- :end_time :%now- :message "Timed out by metabase"}))+ (replacement.db/time-out-active-runs-older-than! age unit))(defn active-run"Return the single active run, or nil."[]- (t2/select-one :model/ReplacementRun :is_active true))+ (replacement.db/active-run))(def ^:private ^:const progress-batch-size"Write progress to DB every N items (and always on the final item)."@@ -135,7 +117,7 @@(deliver on-complete :run/cancelled))(throw (ex-info "Run canceled" {:run-id run-id})))))))(canceled? [_]- (not (:is_active (t2/select-one [:model/ReplacementRun :is_active] :id run-id))))+ (not (:is_active (replacement.db/run-active-flag run-id))))(start-run! [_](start-run! run-id))(succeed-run! [_]diff --git a/enterprise/backend/src/metabase_enterprise/replacement/runner.clj b/enterprise/backend/src/metabase_enterprise/replacement/runner.cljindex 28b08f29db3..005b0cbb5b5 100644--- a/enterprise/backend/src/metabase_enterprise/replacement/runner.clj+++ b/enterprise/backend/src/metabase_enterprise/replacement/runner.clj@@ -2,6 +2,7 @@(:require[clojure.string :as str][medley.core :as m]+ [metabase-enterprise.replacement.db :as replacement.db][metabase-enterprise.replacement.field-refs :as replacement.field-refs][metabase-enterprise.replacement.protocols :as replacement.protocols][metabase-enterprise.replacement.source-swap :as replacement.source-swap]@@ -15,8 +16,7 @@[metabase.transforms.core :as transforms][metabase.util :as u][metabase.util.log :as log]- [metabase.warehouse-schema.models.field-user-settings :as field-user-settings]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.models.field-user-settings :as field-user-settings]))(set! *warn-on-reflection* true)@@ -47,14 +47,13 @@(when (seq ids)(into {}(map (juxt (fn [o] [m (:id o)]) identity))- (t2/select (case m- :card :model/Card- :table :model/Table- :dashboard :model/Dashboard- :transform :model/Transform- :segment :model/Segment- :measure :model/Measure)- {:where [:in :id ids]})))))]+ (case m+ :card (replacement.db/cards-with-ids ids)+ :table (replacement.db/tables-with-ids ids)+ :dashboard (replacement.db/dashboards-with-ids ids)+ :transform (replacement.db/transforms-with-ids ids)+ :segment (replacement.db/segments-with-ids ids)+ :measure (replacement.db/measures-with-ids ids))))))](let [cards (id->instances :card)tables (id->instances :table)dashboards (id->instances :dashboard)@@ -111,8 +110,8 @@(count all-transitive-dependents))) ;; phase 2: swap(let [db-id (case (first old-source)- :card (t2/select-one-fn :database_id :model/Card :id (second old-source))- :table (t2/select-one-fn :db_id :model/Table :id (second old-source)))+ :card (replacement.db/card-database-id (second old-source))+ :table (replacement.db/table-database-id (second old-source)))batch-size 500];; phase 1: Upgrade field refs for ALL transitive dependents(doseq [batch (partition-all batch-size all-transitive-dependents)]@@ -173,15 +172,15 @@"Copy user-edited metadata from a model's result_metadata onto the Fields of theoutput table. Writes to both Field and FieldUserSettings so overrides survive sync."[card-id table-id]- (let [card (t2/select-one :model/Card :id card-id)+ (let [card (replacement.db/card card-id)result-metadata (:result_metadata card)- fields (t2/select :model/Field :table_id table-id :active true)+ fields (replacement.db/active-fields-of-table table-id)field-by-name (m/index-by :name fields)](doseq [col-meta result-metadata:let [field (field-by-name (source-swap.util/column-match-key col-meta))overrides (u/select-keys-when col-meta :non-nil metadata-override-keys)]:when (and field (seq overrides))]- (t2/update! :model/Field (:id field) overrides)+ (replacement.db/update-field! (:id field) overrides)(field-user-settings/upsert-user-settings field overrides))))(defn run-swap-model-with-transform!@@ -194,7 +193,7 @@([card-id transform-id](run-swap-model-with-transform! card-id transform-id noop-progress))([card-id transform-id progress & {:keys [user-id]}]- (let [transform (or (t2/select-one :model/Transform :id transform-id)+ (let [transform (or (replacement.db/transform transform-id)(throw (ex-info "Transform not found" {:transform-id transform-id})))];; phase 1: execute the transform(transforms/execute! transform (cond-> {:run-method :manual}@@ -206,7 +205,7 @@(copy-model-metadata-overrides! card-id (:id table))(run-swap-source! [:card card-id] [:table (:id table)] progress));; phase 3: unpersist the model if it was persisted- (when-let [persisted-info (t2/select-one :model/PersistedInfo :card_id card-id)]+ (when-let [persisted-info (replacement.db/persisted-info-for-card card-id)](model-persistence/mark-for-pruning! {:id (:id persisted-info)} "off"));; phase 4: convert the model to a saved question- (t2/update! :model/Card card-id {:type :question}))))+ (replacement.db/update-card! card-id {:type :question}))))diff --git a/enterprise/backend/src/metabase_enterprise/replacement/source_check.clj b/enterprise/backend/src/metabase_enterprise/replacement/source_check.cljindex ec3ea78b42c..185464bbc30 100644--- a/enterprise/backend/src/metabase_enterprise/replacement/source_check.clj+++ b/enterprise/backend/src/metabase_enterprise/replacement/source_check.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.replacement.source-check(:require+ [metabase-enterprise.replacement.db :as replacement.db][metabase-enterprise.replacement.schema :as replacement.schema][metabase-enterprise.replacement.usages :as replacement.usages][metabase.lib-be.core :as lib-be]@@ -8,8 +9,7 @@[metabase.source-swap.core :as source-swap][metabase.source-swap.schema :as source-swap.schema][metabase.util :as u]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -17,17 +17,17 @@"Returns true if any sandbox (GTAP) policy references `table-id`, either directlyvia `sandbox.table_id` or indirectly via a scoping card whose `table_id` matches."[table-id :- ::lib.schema.id/table]- (or (t2/exists? :model/Sandbox :table_id table-id)- (let [sandbox-card-ids (t2/select-fn-set :card_id :model/Sandbox :card_id [:not= nil])]+ (or (replacement.db/sandbox-exists-for-table? table-id)+ (let [sandbox-card-ids (replacement.db/sandbox-card-ids)](boolean(when (seq sandbox-card-ids)- (t2/exists? :model/Card :id [:in sandbox-card-ids] :table_id table-id))))))+ (replacement.db/card-with-table-exists? sandbox-card-ids table-id))))))(mu/defn- has-incoming-fks? :- :boolean"Returns true if any active field has a FK pointing to a field in `table-id`."[table-id :- ::lib.schema.id/table]- (if-let [field-ids (not-empty (t2/select-pks-set :model/Field :table_id table-id :active true))]- (t2/exists? :model/Field :fk_target_field_id [:in field-ids] :active true)+ (if-let [field-ids (not-empty (replacement.db/active-field-ids-of-table table-id))]+ (replacement.db/active-fk-to-fields-exists? field-ids)false))(mu/defn- format-column :- ::replacement.schema/column@@ -44,8 +44,8 @@[entity-type :- ::replacement.schema/source-entity-typeentity-id :- ::replacement.schema/source-entity-id](case entity-type- :card (t2/select-one-fn :database_id :model/Card :id entity-id)- :table (t2/select-one-fn :db_id :model/Table :id entity-id)))+ :card (replacement.db/card-database-id entity-id)+ :table (replacement.db/table-database-id entity-id)))(mu/defn- format-column-mappings :- [:sequential ::replacement.schema/column-mapping]"Format column mappings by applying format-column to source and target columns."diff --git a/enterprise/backend/src/metabase_enterprise/replacement/source_swap.clj b/enterprise/backend/src/metabase_enterprise/replacement/source_swap.cljindex eadfd0f7fca..90906469119 100644--- a/enterprise/backend/src/metabase_enterprise/replacement/source_swap.clj+++ b/enterprise/backend/src/metabase_enterprise/replacement/source_swap.clj@@ -12,6 +12,7 @@(the table was already upgraded and the query references are the same), so this is rarely an issue."(:require[metabase-enterprise.dependencies.models.dependency :as models.dependency]+ [metabase-enterprise.replacement.db :as replacement.db][metabase-enterprise.replacement.util :as replacement.util][metabase-enterprise.replacement.walk :as replacement.walk][metabase.api.common :as api]@@ -19,8 +20,7 @@[metabase.lib.core :as lib][metabase.models.visualization-settings :as vs][metabase.queries.models.query :as queries.query]- [metabase.source-swap.core :as source-swap]- [toucan2.core :as t2]))+ [metabase.source-swap.core :as source-swap]))(set! *warn-on-reflection* true)@@ -34,7 +34,7 @@(assoc :source (assoc (:source transform) :query query')))](models.dependency/swap-dependency! :transform (:id transform) old-source new-source)(when (seq changes)- (t2/update! :model/Transform (:id transform) changes)+ (replacement.db/update-transform! (:id transform) changes)(events/publish-event! :event/transform-update{:object (merge transform changes) :user-id api/*current-user-id*}))))))@@ -78,7 +78,7 @@:verified-result-metadata? true))](models.dependency/swap-dependency! :card (:id card) old-source new-source)(when (seq changes)- (t2/update! :model/Card (:id card) changes)+ (replacement.db/update-card! (:id card) changes)(events/publish-event! :event/card-update{:object (merge card changes):user-id api/*current-user-id*@@ -98,7 +98,7 @@(assoc :table_id table-id'))](models.dependency/swap-dependency! :segment (:id segment) old-source new-source)(when (seq changes)- (t2/update! :model/Segment (:id segment) changes)+ (replacement.db/update-segment! (:id segment) changes)(events/publish-event! :event/segment-update{:object (merge segment changes) :user-id api/*current-user-id*})))))@@ -116,7 +116,7 @@(assoc :table_id table-id'))](models.dependency/swap-dependency! :measure (:id measure) old-source new-source)(when (seq changes)- (t2/update! :model/Measure (:id measure) changes)+ (replacement.db/update-measure! (:id measure) changes)(events/publish-event! :event/measure-update{:object (merge measure changes) :user-id api/*current-user-id*})))))@@ -146,11 +146,11 @@(not= viz-settings viz-settings')(assoc :visualization_settings viz-settings'))](when (seq changes)- (t2/update! :model/DashboardCard (:id dashcard) changes))))+ (replacement.db/update-dashboard-card! (:id dashcard) changes))))(defn- dashboard-swap-source![dashboard old-source new-source]- (let [dashcards (t2/select :model/DashboardCard :dashboard_id (:id dashboard))+ (let [dashcards (replacement.db/dashboard-cards (:id dashboard))all-card-ids (into #{}(mapcat (fn [dashcard](concat@@ -160,7 +160,7 @@(-> dashcard :visualization_settings vs/db->norm)))))dashcards)card-id->card (if (seq all-card-ids)- (t2/select-pk->fn identity :model/Card :id [:in all-card-ids])+ (replacement.db/cards-by-id all-card-ids){})any-dashcard-changed? (reduce (fn [changed? dashcard](or@@ -172,10 +172,10 @@parameters' (swap-parameter-source-card-id parameters old-source new-source)params-changed? (not= parameters parameters')](when params-changed?- (t2/update! :model/Dashboard (:id dashboard) {:parameters parameters'}))+ (replacement.db/update-dashboard! (:id dashboard) {:parameters parameters'}))(when (or any-dashcard-changed? params-changed?)(events/publish-event!- :event/dashboard-update {:object (t2/select-one :model/Dashboard :id (:id dashboard))+ :event/dashboard-update {:object (replacement.db/dashboard (:id dashboard)):user-id api/*current-user-id*}))))(defn swap-source!@@ -186,11 +186,11 @@([[entity-type entity-id :as entity-ref] old-source new-source](swap-source! entity-ref(case entity-type- :card (t2/select-one :model/Card :id entity-id)- :transform (t2/select-one :model/Transform :id entity-id)- :segment (t2/select-one :model/Segment :id entity-id)- :measure (t2/select-one :model/Measure :id entity-id)- :dashboard (t2/select-one :model/Dashboard :id entity-id)+ :card (replacement.db/card entity-id)+ :transform (replacement.db/transform entity-id)+ :segment (replacement.db/segment entity-id)+ :measure (replacement.db/measure entity-id)+ :dashboard (replacement.db/dashboard entity-id)nil)old-source new-source))([[entity-type _entity-id] entity old-source new-source]diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/column_filter.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/column_filter.cljindex 98ad5dee443..68083a3b84a 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/column_filter.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/column_filter.clj@@ -22,13 +22,13 @@failed extractions, sandboxed users will see zero columns until an admin fixes the sourcecard — which is what we want, given the alternative is leaking every column."(:require+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase.lib.core :as lib][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.util :as u][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(mu/defn find-sandbox-source-cards :- [:map-of ms/PositiveInt :map]"Return `{table-id => sandbox-source-card}` for the `table-ids` that have a Card-backed sandbox for the current user.@@ -38,8 +38,7 @@(let [sandboxes (filter (comp table-ids :table_id) (perms/sandboxes-for-user))card-ids (into #{} (keep :card_id) sandboxes)](if (seq card-ids)- (let [cards-by-id (t2/select-pk->fn identity [:model/Card :id :dataset_query :result_metadata :card_schema]- :id [:in card-ids])]+ (let [cards-by-id (sandbox.db/cards-by-id card-ids)](into {}(keep (fn [{:keys [table_id card_id]}](when-let [card (get cards-by-id card_id)]diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.cljindex d6ddf1769b4..d6bbf0006e2 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/gtap.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.sandbox.api.gtap"`/api/mt/gtap` endpoints, for CRUD operations and the like on GTAPs (Group Table Access Policies)."(:require+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase-enterprise.sandbox.models.sandbox :as sandbox][metabase-enterprise.sandbox.schema :as sandbox.schema][metabase.api.common :as api]@@ -10,8 +11,7 @@[metabase.premium-features.core :as premium-features][metabase.util :as u][metabase.util.i18n :refer [tru]]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST API@@ -28,8 +28,8 @@[:group_id {:optional true} [:maybe ms/PositiveInt]][:table_id {:optional true} [:maybe ms/PositiveInt]]]](if (and group_id table_id)- (t2/select-one :model/Sandbox :group_id group_id :table_id table_id)- (t2/select :model/Sandbox {:order-by [[:id :asc]]})))+ (sandbox.db/sandbox-for-group-and-table group_id table_id)+ (sandbox.db/sandboxes)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -39,7 +39,7 @@"Fetch GTAP by `id`"[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (api/check-404 (t2/select-one :model/Sandbox :id id)))+ (api/check-404 (sandbox.db/sandbox id)));; TODO - not sure what other endpoints we might need, e.g. for fetching the list above but for a given group or Table@@ -56,9 +56,7 @@[:card_id {:optional true} [:maybe ms/PositiveInt]][:group_id ms/PositiveInt][:attribute_remappings {:optional true} ::sandbox.schema/attribute-remappings]]]- (first (t2/insert-returning-instances!- :model/Sandbox- (select-keys body [:table_id :card_id :group_id :attribute_remappings]))))+ (sandbox.db/insert-sandbox! (select-keys body [:table_id :card_id :group_id :attribute_remappings])));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -74,14 +72,14 @@body :- [:map[:card_id {:optional true} [:maybe ms/PositiveInt]][:attribute_remappings {:optional true} ::sandbox.schema/attribute-remappings]]]- (api/check-404 (t2/select-one :model/Sandbox :id id))+ (api/check-404 (sandbox.db/sandbox id));; Only update `card_id` and/or `attribute_remappings` if the values are present in the body of the request.;; This allows existing values to be "cleared" by being set to nil(when (some #(contains? body %) [:card_id :attribute_remappings])- (t2/update! :model/Sandbox id- (u/select-keys-when body- :present #{:card_id :attribute_remappings})))- (t2/select-one :model/Sandbox :id id))+ (sandbox.db/update-sandbox! id+ (u/select-keys-when body+ :present #{:card_id :attribute_remappings})))+ (sandbox.db/sandbox id));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -96,10 +94,7 @@[:table_id ms/PositiveInt][:card_id {:optional true} [:maybe ms/PositiveInt]]]](when card_id- (let [db (t2/select-one :model/Database- :id ^:allow-subquery {:select [:t.db_id]- :from [[(t2/table-name :model/Table) :t]]- :where [:= :t.id table_id]})]+ (let [db (sandbox.db/database-of-table table_id)](when (not (driver.u/supports? (:engine db) :saved-question-sandboxing db))(throw (ex-info (tru "Sandboxing with a saved question is not enabled for this database."){:status-code 400@@ -115,8 +110,8 @@"Delete a GTAP entry."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (api/check-404 (t2/select-one :model/Sandbox :id id))- (t2/delete! :model/Sandbox :id id)+ (api/check-404 (sandbox.db/sandbox id))+ (sandbox.db/delete-sandbox! id)api/generic-204-no-content)(defn- +check-sandboxes-enableddiff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.cljindex 60a1d03cc54..12c2c9b5df1 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/metric.clj@@ -3,10 +3,10 @@Overrides `metabase.permissions.metric/sandbox-restricted-fields` to restrictdimensions from sandboxed tables to only fields in the sandbox source card."(:require+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features :refer [defenterprise]]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(defn- source-card-allowed-field-ids"Extract the set of allowed field IDs from a sandbox source card's result_metadata.@@ -23,9 +23,7 @@name->fid (when (seq col-names)(into {}(map (juxt :name :id))- (t2/select [:model/Field :id :name]- :table_id table-id- :name [:in col-names])))]+ (sandbox.db/fields-of-table-named table-id col-names)))](not-empty (set (vals name->fid))))))))(defenterprise sandbox-restricted-fields@@ -49,8 +47,7 @@cards-by-id (when (seq card-ids)(into {}(map (juxt :id identity))- (t2/select [:model/Card :id :result_metadata :card_schema]- :id [:in card-ids])))]+ (sandbox.db/cards-result-metadata card-ids)))](not-empty(into {}(keep (fn [{:keys [table_id card_id]}]diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/table.cljindex e4e9cf423be..211347c2b52 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/table.clj@@ -2,6 +2,7 @@(:require[metabase-enterprise.sandbox.api.column-filter :as col-filter][metabase-enterprise.sandbox.api.util :as sandbox.api.util]+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.permissions.core :as perms]@@ -9,8 +10,7 @@[metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [metabase.warehouse-schema.table :as schema.table]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.table :as schema.table]))(mu/defn only-sandboxed-perms? :- :boolean"Returns true if the user has sandboxed permissions for the given table. If a sandbox policy exists, it overrides@@ -29,7 +29,7 @@`include-hidden-fields?` and `include-editable-data-model?` can be either booleans or boolean strings.":feature :sandboxes[id opts]- (let [table (api/check-404 (t2/select-one :model/Table :id id))+ (let [table (api/check-404 (sandbox.db/table id))thunk (fn [] (schema.table/fetch-query-metadata* table opts))](if (only-sandboxed-perms? table)(filter-fields-for-sandboxingdiff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/user.cljindex 08966ef65a8..74de24b5e18 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/user.clj@@ -1,13 +1,13 @@(ns metabase-enterprise.sandbox.api.user"Endpoint(s)for setting user attributes."(:require+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.tenants.core :as tenants][metabase.util.i18n :refer [deferred-tru]][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(def ^:private UserAttributes(mu/with-api-error-message@@ -30,8 +30,8 @@_query-params{:keys [login_attributes]} :- [:map[:login_attributes {:optional true} [:maybe UserAttributes]]]]- (api/check-404 (t2/select-one :model/User :id id :type :personal))- (pos? (t2/update! :model/User id {:login_attributes login_attributes})))+ (api/check-404 (sandbox.db/personal-user id))+ (pos? (sandbox.db/set-user-login-attributes! id login_attributes)))(def ^:private max-login-attributes 5000)@@ -48,16 +48,7 @@(mapcat keys)(distinct)(take max-login-attributes))- (t2/select-fn-reducible (comp (partial apply merge)- (juxt :jwt_attributes :login_attributes))- [:model/User :login_attributes :jwt_attributes]- {:where [:or- [:and- [:not= :jwt_attributes nil]- [:not= :jwt_attributes "{}"]]- [:and- [:not= :login_attributes nil]- [:not= :login_attributes "{}"]]]})))+ (sandbox.db/user-attributes-reducible)))(def ^{:arglists '([request respond raise])} routes"`/api/mt/user` routes."diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj b/enterprise/backend/src/metabase_enterprise/sandbox/api/util.cljindex a67fae6aae5..309ab3e6864 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/api/util.clj@@ -3,6 +3,7 @@(:require[clojure.set :as set][medley.core :as m]+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase.api.common :refer [*current-user-id* *is-superuser?*]][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]]@@ -46,19 +47,10 @@[user-id](when user-id(let [user-group-ids (user/group-ids user-id)- sandboxes-with-group-ids (t2/hydrate- (t2/select :model/Sandbox- {:select [[:pgm.group_id :group_id]- [:s.*]]- :from [[:permissions_group_membership :pgm]]- :left-join [[:sandboxes :s] [:= :s.group_id :pgm.group_id]]- :where [:and- [:= :pgm.user_id user-id]]})- :table)+ sandboxes-with-group-ids (t2/hydrate (sandbox.db/user-sandboxes-with-group-ids user-id) :table)impersonations-with-group-ids (when (seq user-group-ids)- (t2/select :model/ConnectionImpersonation- :group_id [:in user-group-ids]))+ (sandbox.db/impersonations-for-groups user-group-ids))group-id->impersonations (->> impersonations-with-group-ids(group-by :group_id))group-id->sandboxes (->> sandboxes-with-group-idsdiff --git a/enterprise/backend/src/metabase_enterprise/sandbox/db.clj b/enterprise/backend/src/metabase_enterprise/sandbox/db.cljnew file mode 100644index 00000000000..ef42ea87ba3--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/sandbox/db.clj@@ -0,0 +1,167 @@+(ns metabase-enterprise.sandbox.db+ "Application database queries for the sandbox module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions."+ (:require+ [toucan2.core :as t2]))++(defn sandbox+ "The Sandbox with `sandbox-id`, or nil."+ [sandbox-id]+ (t2/select-one :model/Sandbox :id sandbox-id))++(defn sandboxes+ "Every Sandbox, in ID order."+ []+ (t2/select :model/Sandbox {:order-by [[:id :asc]]}))++(defn sandbox-for-group-and-table+ "The Sandbox of the group with `group-id` on the Table with `table-id`, or nil."+ [group-id table-id]+ (t2/select-one :model/Sandbox :group_id group-id :table_id table-id))++(defn sandboxes-for-groups-and-table+ "The Sandboxes of the groups with `group-ids` on the Table with `table-id`."+ [group-ids table-id]+ (t2/select :model/Sandbox :group_id [:in group-ids] :table_id table-id))++(defn sandboxes-using-card+ "The `:id` and `:table_id` of the Sandboxes built on the Card with `card-id`."+ [card-id]+ (t2/select [:model/Sandbox :id :table_id] :card_id card-id))++(defn user-sandboxes-with-group-ids+ "The Sandboxes of the groups of the User with `user-id`, each with the `:group_id` of the membership."+ [user-id]+ (t2/select :model/Sandbox+ {:select [[:pgm.group_id :group_id]+ [:s.*]]+ :from [[:permissions_group_membership :pgm]]+ :left-join [[:sandboxes :s] [:= :s.group_id :pgm.group_id]]+ :where [:and+ [:= :pgm.user_id user-id]]}))++(defn sandboxes-with-table-info+ "The group, Table, Database, and schema of the Sandboxes of the optional `group-id` or `group-ids` in the optional+ Database `db-id`, excluding the Database `excluded-db-id` when given."+ [group-id group-ids db-id excluded-db-id]+ (t2/select :model/Sandbox+ {:select [:s.group_id :s.table_id :t.db_id :t.schema]+ :from [[:sandboxes :s]]+ :join [[:metabase_table :t] [:= :s.table_id :t.id]]+ :where [:and+ (when group-id [:= :s.group_id group-id])+ (when group-ids [:in :s.group_id group-ids])+ (when db-id [:= :t.db_id db-id])+ (when excluded-db-id [:not [:= :t.db_id excluded-db-id]])]}))++(defn insert-sandbox!+ "Insert `sandbox` and return the new instance."+ [sandbox]+ (first (t2/insert-returning-instances! :model/Sandbox sandbox)))++(defn update-sandbox!+ "Apply `changes` to the Sandbox with `sandbox-id`."+ [sandbox-id changes]+ (t2/update! :model/Sandbox sandbox-id changes))++(defn delete-sandbox!+ "Delete the Sandbox with `sandbox-id`."+ [sandbox-id]+ (t2/delete! :model/Sandbox :id sandbox-id))++(defn delete-sandboxes!+ "Delete the Sandboxes with `sandbox-ids`."+ [sandbox-ids]+ (t2/delete! :model/Sandbox :id [:in sandbox-ids]))++(defn impersonations-for-groups+ "The ConnectionImpersonations of the groups with `group-ids`."+ [group-ids]+ (t2/select :model/ConnectionImpersonation :group_id [:in group-ids]))++(defn user-group-ids+ "The IDs of the groups of the User with `user-id`."+ [user-id]+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))++(defn personal-user+ "The personal User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User :id user-id :type :personal))++(defn set-user-login-attributes!+ "Set the login attributes of the User with `user-id`, returning the number of rows updated."+ [user-id login-attributes]+ (t2/update! :model/User user-id {:login_attributes login-attributes}))++(defn user-attributes-reducible+ "Reducible merged JWT and login attribute maps of the Users that have any."+ []+ (t2/select-fn-reducible (comp (partial apply merge)+ (juxt :jwt_attributes :login_attributes))+ [:model/User :login_attributes :jwt_attributes]+ {:where [:or+ [:and+ [:not= :jwt_attributes nil]+ [:not= :jwt_attributes "{}"]]+ [:and+ [:not= :login_attributes nil]+ [:not= :login_attributes "{}"]]]}))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn tables-of-database+ "The `:id`, `:db_id`, and `:schema` of the Tables of the Database with `db-id`, restricted to `schema` when+ `schema-only?`."+ [db-id schema-only? schema]+ (t2/select [:model/Table :id :db_id :schema]+ {:where [:and+ [:= :db_id db-id]+ (when schema-only?+ [:= :schema schema])]}))++(defn database-of-table+ "The Database of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Database+ :id ^:allow-subquery {:select [:t.db_id]+ :from [[(t2/table-name :model/Table) :t]]+ :where [:= :t.id table-id]}))++(defn fields-of-table-named+ "The `:id` and `:name` of the Fields of the Table with `table-id` named one of `field-names`."+ [table-id field-names]+ (t2/select [:model/Field :id :name] :table_id table-id :name [:in field-names]))++(defn cards-by-id+ "A map of Card ID to the query, result metadata, and schema of the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn identity [:model/Card :id :dataset_query :result_metadata :card_schema] :id [:in card-ids]))++(defn cards-result-metadata+ "The `:id`, `:result_metadata`, and `:card_schema` of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :result_metadata :card_schema] :id [:in card-ids]))++(defn card-result-metadata+ "The result metadata of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :result_metadata :model/Card :id card-id))++(defn sandboxing-cards+ "The `:id`, `:dataset_query`, `:database_id`, and `:card_schema` of the Cards Sandboxes are built on."+ []+ (t2/select :model/Card+ {:select [:c.id :c.dataset_query :c.database_id :c.card_schema]+ :from [[(t2/table-name :model/Card) :c]]+ :where [:exists ^:allow-subquery {:select [[[:inline 1]]]+ :from [[(t2/table-name :model/Sandbox) :s]]+ :where [:= :s.card_id :c.id]}]}))++(defn set-card-result-metadata!+ "Set the result metadata of the Card with `card-id`."+ [card-id result-metadata]+ (t2/update! :model/Card card-id {:result_metadata result-metadata}))diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.cljindex 5886018150e..b76f6a7e05d 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/params/field_values.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.sandbox.models.params.field-values(:require[metabase-enterprise.sandbox.api.table :as table]+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase-enterprise.sandbox.query-processor.middleware.sandboxing :as sandboxing][metabase.api.common :as api][metabase.premium-features.core :refer [defenterprise]]@@ -22,11 +23,9 @@called from a background sync), since sandboxes are scoped to a user's group memberships."[table-id](when api/*current-user-id*- (let [group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id api/*current-user-id*)+ (let [group-ids (sandbox.db/user-group-ids api/*current-user-id*)sandboxes (when (seq group-ids)- (t2/select :model/Sandbox- :group_id [:in group-ids]- :table_id table-id))]+ (sandbox.db/sandboxes-for-groups-and-table group-ids table-id))](when sandboxes(sandboxing/assert-one-sandbox-per-table sandboxes);; there should be only one gtap per table and we only need one table herediff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.cljindex ad4013e39be..4ec307fdd4e 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/permissions/delete_sandboxes.clj@@ -1,10 +1,10 @@(ns metabase-enterprise.sandbox.models.permissions.delete-sandboxes(:require+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase.app-db.core :as app-db][metabase.premium-features.core :refer [defenterprise]][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(defn- should-delete-sandbox?"Given the changes map and a candidate sandbox, determine if this sandbox should be deleted.@@ -63,7 +63,7 @@candidate-sandboxes)](when (seq ids-to-delete)(log/debugf "Deleting %d unneeded GTAPs: %s" (count ids-to-delete) (pr-str ids-to-delete))- (t2/delete! :model/Sandbox :id [:in ids-to-delete])))))+ (sandbox.db/delete-sandboxes! ids-to-delete)))))(catch Throwable e(throw (ex-info (tru "Error deleting Sandboxes: {0}" (ex-message e)){:changes changes}diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.cljindex 4dd2b89988a..e0a813659be 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/models/sandbox.clj@@ -7,6 +7,7 @@system."(:require[medley.core :as m]+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase-enterprise.sandbox.schema :as sandbox.schema][metabase.api.common :as api][metabase.audit-app.core :as audit]@@ -88,11 +89,7 @@;; If perms were set at the database or schema-level before, we might need to add granular values for all tables;; in the database or schema, so they show correctly in the UI.tables (when (or (keyword? db-perm) (keyword? schema-perm))- (t2/select [:model/Table :id :db_id :schema]- {:where [:and- [:= :db_id db-id]- (when (keyword? schema-perm)- [:= :schema schema])]}))+ (sandbox.db/tables-of-database db-id (keyword? schema-perm) schema));; Remove the overarching database or schema permission so that we can add the granular table-level permissionsgraph (cond(and tables (keyword? db-perm))@@ -119,15 +116,7 @@"Augments a provided permissions graph with active sandboxing policies.":feature :sandboxes[graph & {:keys [group-ids group-id db-id audit?]}]- (let [sandboxes (t2/select :model/Sandbox- {:select [:s.group_id :s.table_id :t.db_id :t.schema]- :from [[:sandboxes :s]]- :join [[:metabase_table :t] [:= :s.table_id :t.id]]- :where [:and- (when group-id [:= :s.group_id group-id])- (when group-ids [:in :s.group_id group-ids])- (when db-id [:= :t.db_id db-id])- (when-not audit? [:not [:= :t.db_id audit/audit-db-id]])]})]+ (let [sandboxes (sandbox.db/sandboxes-with-table-info group-id group-ids db-id (when-not audit? audit/audit-db-id))];; Incorporate each sandbox policy into the permissions graph.(reduce (fn [acc {:keys [group_id table_id db_id schema]}](merge-sandbox-into-graph acc group_id table_id db_id schema [:view-data] :sandboxed))@@ -142,7 +131,7 @@;; not all sandboxes have Cards(when card-id;; not all Cards have saved result metadata- (when-let [result-metadata (not-empty (t2/select-one-fn :result_metadata :model/Card :id card-id))]+ (when-let [result-metadata (not-empty (sandbox.db/card-result-metadata card-id))](check-columns-match-table table-id result-metadata))))([table-id :- ::lib.schema.id/table result-metadata-columns]@@ -155,12 +144,7 @@(defn- sandboxing-card-ids"Every Card a sandbox is built out of: the Cards sandboxes name directly, plus every Card those read at any depth."[]- (let [cards (t2/select :model/Card- {:select [:c.id :c.dataset_query :c.database_id :c.card_schema]- :from [[(t2/table-name :model/Card) :c]]- :where [:exists ^:allow-subquery {:select [[[:inline 1]]]- :from [[(t2/table-name :model/Sandbox) :s]]- :where [:= :s.card_id :c.id]}]})]+ (let [cards (sandbox.db/sandboxing-cards)](into (into #{} (map :id) cards)(mapcat (fn [{:keys [dataset_query database_id]}](when (seq dataset_query)@@ -181,8 +165,8 @@"Throws if `new-result-metadata` would stop matching the Tables the sandboxes built out of this Card sandbox: theCard cannot add fields or change types vs. the original Table."[card-id new-result-metadata]- (when-let [gtaps-using-this-card (not-empty (t2/select [:model/Sandbox :id :table_id] :card_id card-id))]- (let [original-result-metadata (t2/select-one-fn :result_metadata :model/Card :id card-id)]+ (when-let [gtaps-using-this-card (not-empty (sandbox.db/sandboxes-using-card card-id))]+ (let [original-result-metadata (sandbox.db/card-result-metadata card-id)](when-not (= original-result-metadata new-result-metadata)(doseq [{table-id :table_id} gtaps-using-this-card](try@@ -223,15 +207,13 @@;; This allows existing values to be "cleared" by being set to nil(do(when (some #(contains? sandbox %) [:card_id :attribute_remappings])- (t2/update! :model/Sandbox- id- (u/select-keys-when sandbox :present #{:card_id :attribute_remappings})))- (let [updated-sandbox (t2/select-one :model/Sandbox :id id)]+ (sandbox.db/update-sandbox! id (u/select-keys-when sandbox :present #{:card_id :attribute_remappings})))+ (let [updated-sandbox (sandbox.db/sandbox id)](events/publish-event! :event/sandbox-update{:object updated-sandbox:user-id api/*current-user-id*})updated-sandbox))- (let [inserted-sandbox (first (t2/insert-returning-instances! :model/Sandbox sandbox))]+ (let [inserted-sandbox (sandbox.db/insert-sandbox! sandbox)](events/publish-event! :event/sandbox-create{:object inserted-sandbox:user-id api/*current-user-id*})diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.cljindex 1f5f1a55536..5aa0506d6f0 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/query_processor/middleware/sandboxing.clj@@ -6,6 +6,7 @@[better-cond.core :as b][medley.core :as m][metabase-enterprise.sandbox.api.util :as sandbox.api.util]+ [metabase-enterprise.sandbox.db :as sandbox.db][metabase-enterprise.sandbox.models.sandbox :as sandbox][metabase.api.common :as api :refer [*current-user* *current-user-id*]];; allowed (for now) since sandboxing needs to manipulate legacy metadata@@ -32,10 +33,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.match :as match]- ;; caches inferred result_metadata onto the sandbox Card row; a write the metadata provider can't do- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2]))+ [metabase.util.match :as match]))(set! *warn-on-reflection* true)@@ -217,7 +215,7 @@(log/infof "Saving results metadata for Sandbox Card %d" card-id);; TODO (Cam 9/9/25) -- we should switch to saving Lib-style metadata in the app DB instead of legacy;; style in the near future- (t2/update! :model/Card card-id {:result_metadata cols}))+ (sandbox.db/set-card-result-metadata! card-id cols))(lib/update-query-stage query 0 assoc :lib/stage-metadata (lib/->normalized-stage-metadata cols))))))query))diff --git a/enterprise/backend/src/metabase_enterprise/scim/api.clj b/enterprise/backend/src/metabase_enterprise/scim/api.cljindex 6563738a466..ac4ac5f9664 100644--- a/enterprise/backend/src/metabase_enterprise/scim/api.clj+++ b/enterprise/backend/src/metabase_enterprise/scim/api.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.scim.api"/api/ee/scim/ endpoints"(:require+ [metabase-enterprise.scim.db :as scim.db][metabase.api-keys.core :as api-key][metabase.api.common :as api][metabase.api.macros :as api.macros]@@ -19,15 +20,15 @@"Generates a new SCIM API key and deletes any that already exist."[user-id](t2/with-transaction [_conn]- (t2/delete! :model/ApiKey :scope :scim)+ (scim.db/delete-scim-api-keys!)(let [unhashed-key (api-key/generate-key)](->- (t2/insert-returning-instance! :model/ApiKey {:user_id nil- :scope :scim- :name (scim-api-key-name)- ::api-key/unhashed-key unhashed-key- :creator_id user-id- :updated_by_id user-id})+ (scim.db/insert-api-key! {:user_id nil+ :scope :scim+ :name (scim-api-key-name)+ ::api-key/unhashed-key unhashed-key+ :creator_id user-id+ :updated_by_id user-id})(assoc :unmasked_key (u.secret/expose unhashed-key))))));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API@@ -42,7 +43,7 @@to that after it is created."[](api/check-superuser)- (api/check-404 (t2/select-one :model/ApiKey :scope :scim)))+ (api/check-404 (scim.db/scim-api-key)));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;diff --git a/enterprise/backend/src/metabase_enterprise/scim/auth.clj b/enterprise/backend/src/metabase_enterprise/scim/auth.cljindex 7da0960b240..cdb311c1f66 100644--- a/enterprise/backend/src/metabase_enterprise/scim/auth.clj+++ b/enterprise/backend/src/metabase_enterprise/scim/auth.clj@@ -1,17 +1,17 @@(ns metabase-enterprise.scim.auth(:require+ [metabase-enterprise.scim.db :as scim.db][metabase-enterprise.scim.settings :as scim.settings][metabase.api.open-api :as open-api][metabase.server.middleware.session :as mw.session]- [metabase.util.password :as u.password]- [toucan2.core :as t2]))+ [metabase.util.password :as u.password]))(defn- validate-scim-api-key"Checks whether the API key provided as a Bearer token in the request matches an API keyin the database with the SCIM scope."[api-key](boolean- (let [expected-api-key (-> (t2/select-one :model/ApiKey :scope :scim) :key)]+ (let [expected-api-key (-> (scim.db/scim-api-key) :key)](if (and api-key expected-api-key)(u.password/verify-password api-key "" expected-api-key)(mw.session/do-useless-hash)))))diff --git a/enterprise/backend/src/metabase_enterprise/scim/db.clj b/enterprise/backend/src/metabase_enterprise/scim/db.cljnew file mode 100644index 00000000000..086e8116858--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/scim/db.clj@@ -0,0 +1,145 @@+(ns metabase-enterprise.scim.db+ "Application database queries for the scim module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for transactions."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(def ^:private user-columns+ "Required columns when fetching users for SCIM."+ [:model/User :id :first_name :last_name :email :locale :is_active :entity_id])++(def ^:private group-columns+ "Required columns when fetching groups for SCIM."+ [:model/PermissionsGroup :id :name :entity_id])++(defn scim-api-key+ "The SCIM ApiKey, or nil."+ []+ (t2/select-one :model/ApiKey :scope :scim))++(defn delete-scim-api-keys!+ "Delete every SCIM ApiKey."+ []+ (t2/delete! :model/ApiKey :scope :scim))++(defn insert-api-key!+ "Insert `api-key` and return the new instance."+ [api-key]+ (t2/insert-returning-instance! :model/ApiKey api-key))++(defn- personal-user-expr+ [email]+ [:and [:= :type "personal"]+ (when email [:= :%lower.email (u/lower-case-en email)])])++(defn scim-user-by-entity-id+ "The SCIM columns of the personal User with `entity-id`, or nil."+ [entity-id]+ (t2/select-one user-columns :entity_id entity-id {:where [:= :type "personal"]}))++(defn scim-user-by-email+ "The SCIM columns of the User with `email`, or nil."+ [email]+ (t2/select-one user-columns :email (u/lower-case-en email)))++(defn scim-users+ "The SCIM columns of the personal Users, narrowed to the optional `email` (case-insensitive), paged by `limit`+ and `offset` in ID order."+ [email limit offset]+ (t2/select user-columns+ {:where (personal-user-expr email)+ :limit limit+ :offset offset+ :order-by [[:id :asc]]}))++(defn scim-user-count+ "The number of personal Users, narrowed to the optional `email` (case-insensitive)."+ [email]+ (t2/count :model/User {:where (personal-user-expr email)}))++(defn user-email-exists?+ "Whether a User with `email` (case-insensitive) exists."+ [email]+ (t2/exists? :model/User :%lower.email (u/lower-case-en email)))++(defn user-ids-by-entity-ids+ "The IDs of the Users with `entity-ids`."+ [entity-ids]+ (t2/select-fn-set :id :model/User {:where [:in :entity_id entity-ids]}))++(defn insert-user!+ "Insert the User `row`."+ [row]+ (t2/insert! :model/User row))++(defn update-user!+ "Apply `changes` to the User with `user-id`."+ [user-id changes]+ (t2/update! :model/User user-id changes))++(defn user-group-memberships+ "Rows of User ID, group name, and group entity ID for the memberships of the Users with `user-ids`, excluding the+ groups with `excluded-group-ids`."+ [user-ids excluded-group-ids]+ (t2/select [:model/PermissionsGroupMembership :pgm.user_id :pg.name :pg.entity_id]+ {:from [[:permissions_group_membership :pgm]]+ :join [[:permissions_group :pg] [:= :pg.id :group_id]]+ :where (into [:and [:in :user_id user-ids]]+ (map (fn [group-id] [:not= :pg.id group-id]))+ excluded-group-ids)}))++(defn- manageable-group-expr+ [excluded-group-ids group-name]+ (into [:and (when group-name [:= :name group-name])]+ (map (fn [group-id] [:not= :id group-id]))+ excluded-group-ids))++(defn scim-group-by-entity-id+ "The SCIM columns of the PermissionsGroup with `entity-id` other than `excluded-group-ids`, or nil."+ [entity-id excluded-group-ids]+ (t2/select-one group-columns :entity_id entity-id {:where (manageable-group-expr excluded-group-ids nil)}))++(defn scim-groups+ "The SCIM columns of the PermissionsGroups other than `excluded-group-ids`, narrowed to the optional `group-name`,+ paged by `limit` and `offset` in ID order."+ [excluded-group-ids group-name limit offset]+ (t2/select group-columns+ {:where (manageable-group-expr excluded-group-ids group-name)+ :limit limit+ :offset offset+ :order-by [[:id :asc]]}))++(defn scim-group-count+ "The number of PermissionsGroups other than `excluded-group-ids`, narrowed to the optional `group-name`."+ [excluded-group-ids group-name]+ (t2/count :model/PermissionsGroup {:where (manageable-group-expr excluded-group-ids group-name)}))++(defn group-name-exists?+ "Whether a PermissionsGroup with `group-name` (case-insensitive) exists."+ [group-name]+ (t2/exists? :model/PermissionsGroup :%lower.name (u/lower-case-en group-name)))++(defn insert-group!+ "Insert `group` and return the new instance."+ [group]+ (first (t2/insert-returning-instances! :model/PermissionsGroup group)))++(defn update-group!+ "Apply `changes` to the PermissionsGroup with `group-id`."+ [group-id changes]+ (t2/update! :model/PermissionsGroup group-id changes))++(defn delete-group!+ "Delete the PermissionsGroup with `group-id`."+ [group-id]+ (t2/delete! :model/PermissionsGroup group-id))++(defn group-members+ "Rows of group ID, member email, and member entity ID for the memberships of the PermissionsGroups with+ `group-ids`."+ [group-ids]+ (t2/select [:model/PermissionsGroupMembership :pgm.group_id :u.email :u.entity_id]+ {:from [[:permissions_group_membership :pgm]]+ :join [[:core_user :u] [:= :u.id :pgm.user_id]]+ :where [:in :pgm.group_id group-ids]}))diff --git a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj b/enterprise/backend/src/metabase_enterprise/scim/v2/api.cljindex f26d5c21a60..cfd5fc37228 100644--- a/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj+++ b/enterprise/backend/src/metabase_enterprise/scim/v2/api.clj@@ -4,6 +4,7 @@`v2` in the API path represents the fact that we implement SCIM 2.0."(:require+ [metabase-enterprise.scim.db :as scim.db][metabase-enterprise.scim.settings :as scim.settings][metabase.analytics-interface.core :as analytics][metabase.api.macros :as api.macros]@@ -143,22 +144,14 @@;;; | User operations |;;; +----------------------------------------------------------------------------------------------------------------+-(def ^:private user-cols- "Required columns when fetching users for SCIM."- [:id :first_name :last_name :email :locale :is_active :entity_id])-(mi/define-batched-hydration-method add-scim-user-group-memberships:scim_user_group_memberships"Add to each `user` a list of :user_group_memberships where each item is a map with 2 keys [:name :entity_id]."[users](when (seq users)- (let [user-id->memberships (group-by :user_id (t2/select [:model/PermissionsGroupMembership :pgm.user_id :pg.name :pg.entity_id]- {:from [[:permissions_group_membership :pgm]]- :join [[:permissions_group :pg] [:= :pg.id :group_id]]- :where [:and- [:in :user_id (map u/the-id users)]- [:not= :pg.id (:id (perms/all-users-group))]- [:not= :pg.id (:id (perms/admin-group))]]}))+ (let [user-id->memberships (group-by :user_id (scim.db/user-group-memberships (map u/the-id users)+ [(:id (perms/all-users-group))+ (:id (perms/admin-group))]))membership->group (fn [membership] (select-keys membership [:name :entity_id]))](for [user users](assoc user :user_group_memberships (->> (user-id->memberships (u/the-id user))@@ -204,16 +197,15 @@(mu/defn ^:private get-user-by-entity-id"Fetches a user by entity ID, or throws a 404"[entity-id]- (or (t2/select-one (cons :model/User user-cols)- :entity_id entity-id- {:where [:= :type "personal"]})+ (or (scim.db/scim-user-by-entity-id entity-id)(throw-scim-error 404 "User not found")))-(defn- ^:private user-filter-clause+(defn- ^:private user-filter-email+ "The lower-cased email a `userName eq` `filter-parameter` selects."[filter-parameter](let [[_ match] (re-matches #"^userName eq \"(.*)\"$" filter-parameter)](if match- [:= :%lower.email (u/lower-case-en match)]+ (u/lower-case-en match)(throw-scim-error 400 (format "Unsupported filter parameter: %s" filter-parameter)))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -232,18 +224,13 @@;; SCIM start-index is 1-indexed, so we need to decrement it hereoffset (if start-index (dec start-index) default-pagination-offset)filter-param (when filter-param (codec/url-decode filter-param))- where-clause [:and [:= :type "personal"]- (when filter-param (user-filter-clause filter-param))]- users (t2/select (cons :model/User user-cols)- {:where where-clause- :limit limit- :offset offset- :order-by [[:id :asc]]})+ lower-email (when filter-param (user-filter-email filter-param))+ users (scim.db/scim-users lower-email limit offset)hydrated-users (t2/hydrate users :scim_user_group_memberships)results-count (count hydrated-users)items-per-page (if (< results-count limit) results-count limit)result {:schemas [list-schema-uri]- :totalResults (t2/count :model/User {:where where-clause})+ :totalResults (scim.db/scim-user-count lower-email):startIndex (inc offset):itemsPerPage items-per-page:Resources (map mb-user->scim hydrated-users)}]@@ -274,12 +261,11 @@(with-prometheus-counters(let [mb-user (scim-user->mb scim-user)email (:email mb-user)]- (when (t2/exists? :model/User :%lower.email (u/lower-case-en email))+ (when (scim.db/user-email-exists? email)(throw-scim-error 409 "Email address is already in use"))(let [new-user (t2/with-transaction [_]- (t2/insert! :model/User mb-user)- (-> (t2/select-one (cons :model/User user-cols)- :email (u/lower-case-en email))+ (scim.db/insert-user! mb-user)+ (-> (scim.db/scim-user-by-email email)mb-user->scim))](scim-response new-user 201)))))@@ -301,9 +287,8 @@(throw-scim-error 400 "You may not update the email of an existing user.")(try(t2/with-transaction [_conn]- (t2/update! :model/User (u/the-id current-user) updates)- (let [user (-> (t2/select-one (cons :model/User user-cols)- :entity_id id)+ (scim.db/update-user! (u/the-id current-user) updates)+ (let [user (-> (scim.db/scim-user-by-entity-id id)mb-user->scim)](scim-response user)))(catch Exception e@@ -360,7 +345,7 @@(= (u/lower-case-en op) "replace") (patch->user-updates path value)))){}(:Operations patch-ops))]- (t2/update! :model/User (u/the-id user) updates)+ (scim.db/update-user! (u/the-id user) updates)(-> (get-user-by-entity-id id)mb-user->scimscim-response)))))@@ -369,19 +354,12 @@;;; | Group operations |;;; +----------------------------------------------------------------------------------------------------------------+-(def ^:private group-cols- "Required columns when fetching groups for SCIM."- [:name :id :entity_id])-(mi/define-batched-hydration-method add-scim-group-members:scim_group_members"Add to each `group` a list of :members where each item is a map with 2 keys [:email :entity_id]."[groups](when (seq groups)- (let [group-id->members (group-by :group_id (t2/select [:model/PermissionsGroupMembership :pgm.group_id :u.email :u.entity_id]- {:from [[:permissions_group_membership :pgm]]- :join [[:core_user :u] [:= :u.id :pgm.user_id]]- :where [:in :pgm.group_id (map u/the-id groups)]}))+ (let [group-id->members (group-by :group_id (scim.db/group-members (map u/the-id groups)))group->member (fn [member] (select-keys member [:email :entity_id]))](for [group groups](assoc group :members (->> (group-id->members (u/the-id group))@@ -392,12 +370,7 @@"Fetches a group by entity ID, or throws a 404. Cannot fetch the Administrators or All Users groups, as these arestatic and cannot be managed via SCIM."[entity-id]- (or (t2/select-one (cons :model/PermissionsGroup group-cols)- :entity_id entity-id- {:where- [:and- [:not= :id (:id (perms/all-users-group))]- [:not= :id (:id (perms/admin-group))]]})+ (or (scim.db/scim-group-by-entity-id entity-id [(:id (perms/all-users-group)) (:id (perms/admin-group))])(throw-scim-error 404 "Group not found")))(mu/defn ^:private mb-group->scim :- SCIMGroup@@ -414,11 +387,12 @@:displayName (:name group):meta {:resourceType "Group"}})-(defn- group-filter-clause+(defn- group-filter-name+ "The group name a `displayName eq` `filter-parameter` selects."[filter-parameter](let [[_ match] (re-matches #"^displayName eq \"(.*)\"$" filter-parameter)](if match- [:= :name match]+ match(throw (ex-info "Unsupported filter parameter" {:filter filter-parameter:status-code 400})))))@@ -439,19 +413,13 @@;; SCIM start-index is 1-indexed, so we need to decrement it hereoffset (if start-index (dec start-index) default-pagination-offset)filter-param (when filter-param (codec/url-decode filter-param))- where-clause [:and- [:not= :id (:id perms/all-users-group)]- [:not= :id (:id perms/admin-group)]- (when filter-param (group-filter-clause filter-param))]- groups (t2/select (cons :model/PermissionsGroup group-cols)- {:where where-clause- :limit limit- :offset offset- :order-by [[:id :asc]]})+ excluded-ids [(:id perms/all-users-group) (:id perms/admin-group)]+ group-name (when filter-param (group-filter-name filter-param))+ groups (scim.db/scim-groups excluded-ids group-name limit offset)results-count (count groups)items-per-page (if (< results-count limit) results-count limit)result {:schemas [list-schema-uri]- :totalResults (t2/count :model/PermissionsGroup {:where where-clause})+ :totalResults (scim.db/scim-group-count excluded-ids group-name):startIndex (inc offset):itemsPerPage items-per-page:Resources (map mb-group->scim groups)}]@@ -474,7 +442,7 @@"Updates the membership of `group-id` to be the set of users in the collection `user-entity-ids`. Clearsany existing members."[group-id user-entity-ids]- (let [user-ids (t2/select-fn-set :id :model/User {:where [:in :entity_id user-entity-ids]})]+ (let [user-ids (scim.db/user-ids-by-entity-ids user-entity-ids)](when-let [memberships (not-empty (map(fn [user-id] {:group group-id :user user-id})user-ids))]@@ -493,10 +461,10 @@(with-prometheus-counters(let [group-name (:displayName scim-group)entity-ids (map :value (:members scim-group))]- (when (t2/exists? :model/PermissionsGroup :%lower.name (u/lower-case-en group-name))+ (when (scim.db/group-name-exists? group-name)(throw-scim-error 409 "A group with that name already exists"))(t2/with-transaction [_conn]- (let [new-group (first (t2/insert-returning-instances! :model/PermissionsGroup {:name group-name}))]+ (let [new-group (scim.db/insert-group! {:name group-name})](when (seq entity-ids)(update-group-membership (:id new-group) entity-ids))(-> new-group@@ -519,7 +487,7 @@entity-ids (map :value (:members scim-group))](t2/with-transaction [_conn](let [group (get-group-by-entity-id id)]- (t2/update! :model/PermissionsGroup (u/the-id group) {:name group-name})+ (scim.db/update-group! (u/the-id group) {:name group-name})(when (seq entity-ids)(update-group-membership (u/the-id group) entity-ids))(-> (get-group-by-entity-id id)@@ -537,5 +505,5 @@[:id ms/NonBlankString]]](with-prometheus-counters(let [group (get-group-by-entity-id id)]- (t2/delete! :model/PermissionsGroup (u/the-id group))+ (scim.db/delete-group! (u/the-id group))(scim-response nil 204))))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/api.clj b/enterprise/backend/src/metabase_enterprise/security_center/api.cljindex ab5b5f2d817..2c23d0cf765 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/api.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/api.clj@@ -2,6 +2,7 @@"API endpoints for Security Center advisories."(:require[clojure.set :as set]+ [metabase-enterprise.security-center.db :as security-center.db][metabase-enterprise.security-center.models.security-advisory :as security-advisory][metabase-enterprise.security-center.notification :as notification][metabase-enterprise.security-center.schema :as security-center.schema]@@ -69,8 +70,7 @@"List all security advisories with match status."[](api/check-superuser)- (let [advisories (t2/hydrate (t2/select :model/SecurityAdvisory {:order-by [[:published_at :desc]]})- :acknowledged_by_user)]+ (let [advisories (t2/hydrate (security-center.db/advisories-newest-first) :acknowledged_by_user)]{:last_checked_at (settings/security-center-last-synced-at):advisories (mapv advisory-response advisories)}))@@ -84,7 +84,7 @@"Acknowledge a security advisory. Stops repeat notifications."[{:keys [advisory-id]} :- [:map [:advisory-id ms/NonBlankString]]](api/check-superuser)- (let [advisory (t2/select-one :model/SecurityAdvisory :advisory_id advisory-id)]+ (let [advisory (security-center.db/advisory-by-advisory-id advisory-id)](api/check-404 advisory)(acknowledge-response (security-advisory/acknowledge! advisory api/*current-user-id*))))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/db.clj b/enterprise/backend/src/metabase_enterprise/security_center/db.cljnew file mode 100644index 00000000000..2e65ee16425--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/security_center/db.clj@@ -0,0 +1,50 @@+(ns metabase-enterprise.security-center.db+ "Application database queries for the security-center module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [toucan2.core :as t2]))++(defn advisory+ "The SecurityAdvisory with `id`, or nil."+ [id]+ (t2/select-one :model/SecurityAdvisory :id id))++(defn advisory-by-advisory-id+ "The SecurityAdvisory with the external `advisory-id`, or nil."+ [advisory-id]+ (t2/select-one :model/SecurityAdvisory :advisory_id advisory-id))++(defn advisories-newest-first+ "Every SecurityAdvisory, newest first."+ []+ (t2/select :model/SecurityAdvisory {:order-by [[:published_at :desc]]}))++(defn advisories-reducible+ "Reducible SecurityAdvisories."+ []+ (t2/reducible-select :model/SecurityAdvisory))++(defn advisories-with-statuses-reducible+ "Reducible severity and acknowledgement time of the SecurityAdvisories whose match status is one of `statuses`."+ [statuses]+ (t2/reducible-select [:model/SecurityAdvisory :severity :acknowledged_at] :match_status [:in statuses]))++(defn unacknowledged-advisories-with-statuses+ "The unacknowledged SecurityAdvisories whose match status is one of `statuses`."+ [statuses]+ (t2/select :model/SecurityAdvisory :acknowledged_at nil :match_status [:in statuses]))++(defn unacknowledged-advisories-by-advisory-ids+ "The unacknowledged SecurityAdvisories with the external `advisory-ids`."+ [advisory-ids]+ (t2/select :model/SecurityAdvisory :advisory_id [:in advisory-ids] :acknowledged_at nil))++(defn update-advisory!+ "Apply `changes` to the SecurityAdvisory with `id`."+ [id changes]+ (t2/update! :model/SecurityAdvisory id changes))++(defn user-summaries-by-id+ "A map of ID to the ID, names, and email of the Users with `user-ids`."+ [user-ids]+ (t2/select-fn->fn :id identity [:model/User :id :first_name :last_name :email] :id [:in user-ids]))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/matching.clj b/enterprise/backend/src/metabase_enterprise/security_center/matching.cljindex 3b22f353672..c65f973244d 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/matching.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/matching.clj@@ -2,6 +2,7 @@"Advisory matching engine. Evaluates HoneySQL queries against the appdband combines with version checks to determine match status."(:require+ [metabase-enterprise.security-center.db :as security-center.db][metabase-enterprise.security-center.schema :as schema][metabase.app-db.core :as mdb][metabase.config.core :as config]@@ -10,8 +11,7 @@[metabase.util.connection :as u.connection][metabase.util.log :as log][metabase.util.malli :as mu]- [next.jdbc.result-set :as rs]- [toucan2.core :as t2])+ [next.jdbc.result-set :as rs])(:import(org.semver4j Semver)))@@ -148,11 +148,11 @@reactivated? (and (#{:active :error} match-status)currently-unaffected(some? (:acknowledged_at advisory)))]- (t2/update! :model/SecurityAdvisory (:id advisory)- (cond-> {:match_status match-status- :last_evaluated_at (mi/now)}- reactivated? (assoc :acknowledged_at nil- :acknowledged_by nil))))))))+ (security-center.db/update-advisory! (:id advisory)+ (cond-> {:match_status match-status+ :last_evaluated_at (mi/now)}+ reactivated? (assoc :acknowledged_at nil+ :acknowledged_by nil))))))))(defn evaluate-all-advisories!"Re-evaluate every advisory, including acknowledged ones — an acked@@ -160,12 +160,12 @@[](let [instance-version (parse-version (:tag config/mb-version-info))](->>- (t2/reducible-select :model/SecurityAdvisory)+ (security-center.db/advisories-reducible)(run! (fn [advisory](try(evaluate-advisory! advisory instance-version)(catch Exception e(log/warnf "Error evaluating advisory %s: %s" (:advisory_id advisory) (ex-message e))- (t2/update! :model/SecurityAdvisory (:id advisory)- {:match_status :error- :last_evaluated_at (mi/now)}))))))))+ (security-center.db/update-advisory! (:id advisory)+ {:match_status :error+ :last_evaluated_at (mi/now)}))))))))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/metrics.clj b/enterprise/backend/src/metabase_enterprise/security_center/metrics.cljindex e9693bec146..3acdd99e496 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/metrics.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/metrics.clj@@ -3,11 +3,11 @@vulnerability counts. Exposed so operators can alert when advisories stopsyncing or when vulnerabilities are present."(:require+ [metabase-enterprise.security-center.db :as security-center.db][metabase-enterprise.security-center.settings :as settings][metabase.analytics-interface.core :as analytics][metabase.analytics.core :as analytics.core]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.time.temporal Temporal ChronoField)))@@ -41,8 +41,7 @@"Return a map of [severity acknowledged?] → count for advisories whosematch_status places them in the vulnerable bucket."[]- (->> (t2/reducible-select [:model/SecurityAdvisory :severity :acknowledged_at]- :match_status [:in vulnerable-statuses])+ (->> (security-center.db/advisories-with-statuses-reducible vulnerable-statuses)(reduce (fn [acc {:keys [severity acknowledged_at]}](update acc (label-of severity (some? acknowledged_at)) (fnil inc 0))){})))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.clj b/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.cljindex 6ca549e33b2..3d92b7ceae4 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/models/security_advisory.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.security-center.models.security-advisory(:require+ [metabase-enterprise.security-center.db :as security-center.db][metabase.analytics.core :as analytics][metabase.events.core :as events][metabase.models.interface :as mi]@@ -28,9 +29,8 @@[_model k advisories](let [user-ids (keep :acknowledged_by advisories)id->user (when (seq user-ids)- (t2/select-fn->fn :id #(select-keys % [:id :common_name :email])- [:model/User :id :first_name :last_name :email]- :id [:in (set user-ids)]))]+ (update-vals (security-center.db/user-summaries-by-id (set user-ids))+ #(select-keys % [:id :common_name :email])))](mi/instances-with-hydrated-dataadvisories k(constantly id->user)@@ -44,21 +44,21 @@(when (:acknowledged_at advisory)(throw (ex-info "Advisory already acknowledged" {:status-code 409})))(let [now (mi/now)]- (t2/update! :model/SecurityAdvisory (:id advisory)- {:acknowledged_by user-id- :acknowledged_at now})+ (security-center.db/update-advisory! (:id advisory)+ {:acknowledged_by user-id+ :acknowledged_at now})(events/publish-event! :event/security-advisory-acknowledge{:object advisory:user-id user-id})(analytics/track-event! :snowplow/simple_event{:event "security_advisory_acknowledged":event_detail (name (:severity advisory))})- (-> (t2/select-one :model/SecurityAdvisory :id (:id advisory))+ (-> (security-center.db/advisory (:id advisory))(t2/hydrate :acknowledged_by_user))))(defn acknowledge-many!"Acknowledge multiple security advisories by their advisory_id strings. Skips already-acknowledgedadvisories. Returns a sequence of updated advisories with `:acknowledged_by` hydrated."[advisory-ids user-id]- (let [advisories (t2/select :model/SecurityAdvisory :advisory_id [:in (set advisory-ids)] :acknowledged_at nil)]+ (let [advisories (security-center.db/unacknowledged-advisories-by-advisory-ids (set advisory-ids))](mapv #(acknowledge! % user-id) advisories)))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/notification.clj b/enterprise/backend/src/metabase_enterprise/security_center/notification.cljindex 221525fb88b..3f3776a6066 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/notification.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/notification.clj@@ -10,6 +10,7 @@as a recipient when set, but only if `security-center-email-recipients`targets the admin group (i.e. \"Send to all instance admins\" is on)."(:require+ [metabase-enterprise.security-center.db :as security-center.db][metabase-enterprise.security-center.settings :as settings][metabase.analytics.core :as analytics][metabase.channel.settings :as channel.settings]@@ -168,8 +169,7 @@(try(notification/send-notification! notif :notification/sync? true)(track-notification-sent! notif triggered-from "success")- (t2/update! :model/SecurityAdvisory (:id advisory)- {:last_notified_at (mi/now)})+ (security-center.db/update-advisory! (:id advisory) {:last_notified_at (mi/now)})(catch Exception e(track-notification-sent! notif triggered-from "failure")(throw e))))))diff --git a/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.clj b/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.cljindex 1a029f65baf..4b308359903 100644--- a/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.clj+++ b/enterprise/backend/src/metabase_enterprise/security_center/task/sync_advisories.clj@@ -7,6 +7,7 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase-enterprise.security-center.db :as security-center.db][metabase-enterprise.security-center.fetch :as fetch][metabase-enterprise.security-center.matching :as matching][metabase-enterprise.security-center.metrics :as metrics]@@ -14,8 +15,7 @@[metabase-enterprise.security-center.settings :as settings][metabase.premium-features.core :as premium-features][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(org.quartz DisallowConcurrentExecution)))@@ -39,9 +39,7 @@(defn- unacknowledged-active-advisories"Return all unacknowledged advisories with match_status in (:active :error)."[]- (t2/select :model/SecurityAdvisory- :acknowledged_at nil- :match_status [:in ["active" "error"]]))+ (security-center.db/unacknowledged-advisories-with-statuses ["active" "error"]))(defn send-repeat-notifications!"Check all unacknowledged active/error advisories and send repeat notificationsdiff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db.cljnew file mode 100644index 00000000000..4753f157c7e--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db.clj@@ -0,0 +1,98 @@+(ns metabase-enterprise.semantic-search.db+ "Application database queries for the semantic-search module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.search.scoring :as search.scoring]+ [toucan2.core :as t2]))++(defn library-root-collections+ "The ID and type of the top-level Collections whose type is one of `types`."+ [types]+ (t2/select [:model/Collection :id :type] :type [:in types] :location "/"))++(defn descendant-collection-ids+ "The IDs of the Collections under the top-level Collection with `root-id`."+ [root-id]+ (t2/select-pks-set :model/Collection :location [:like (str "/" root-id "/%")]))++(defn curated-tables-reducible+ "Reducible ID, published flag, data layer, and data authority of the active Tables that are published or+ authoritative."+ []+ (t2/reducible-select [:model/Table :id :is_published :data_layer :data_authority]+ {:where [:and+ [:= :active true]+ [:or [:= :is_published true]+ [:= :data_authority ^:allow-raw-sql [:inline "authoritative"]]]]}))++(defn official-collection-ids+ "The IDs of the official Collections."+ []+ (t2/select-pks-set :model/Collection :authority_level :official))++(defn unarchived-dashboard-ids-in-collections-reducible+ "Reducible `:id` rows of the unarchived Dashboards in the Collections with `collection-ids`."+ [collection-ids]+ (t2/reducible-select [:model/Dashboard :id]+ {:where [:and [:= :archived false]+ [:in :collection_id collection-ids]]}))++(defn collection-owners-and-locations+ "The ID, owner, and location of the Collections with `collection-ids`."+ [collection-ids]+ (t2/select [:model/Collection :id :personal_owner_id :location] :id [:in collection-ids]))++(defn personal-collection-owners+ "The ID and owner of the personal Collections among `collection-ids`."+ [collection-ids]+ (t2/select [:model/Collection :id :personal_owner_id]+ :id [:in collection-ids]+ :personal_owner_id [:not= nil]))++(defn collection-locations+ "The ID and location of the raw collection rows with `collection-ids`."+ [collection-ids]+ (t2/select [:collection :id :location] :id [:in collection-ids]))++(defn instances+ "The instances of `model` with `ids`."+ [model ids]+ (t2/select model :id [:in ids]))++(defn- search-doc-select+ [{:keys [id model]}]+ ^:allow-subquery+ {:select [[^:allow-raw-sql [:inline (str id)]] [^:allow-raw-sql [:inline model]]]})++(defn- search-index-select+ "A `search_index` CTE selecting the `:id` and `:model` of each of `search-results` (each `{:id :model}`)."+ [search-results]+ {:with [[[:search_index ^:allow-subquery {:columns [:model_id :model]}]+ ;; We could use :values here, except MySQL uses a slightly different syntax and I can't seem to get+ ;; honeysql to generate a valid WITH ... VALUES statement for MySQL, so fallback to UNION + SELECT+ ;; which works with all supported appdbs. https://dev.mysql.com/doc/refman/8.4/en/values.html+ ^:allow-subquery+ {:union (map search-doc-select search-results)}]]+ :select [[[:cast :search_index.model_id (if (= :mysql (mdb/db-type)) :unsigned :int)] :id]+ [:search_index.model :model]]+ :from [:search_index]})++(defn appdb-scored-rows+ "The `:id`/`:model` rows of `search-results` (each `{:id :model}`) augmented with the SELECT expressions of+ `scorers` (a map of scorer key to SELECT expression, see+ `metabase-enterprise.semantic-search.scoring/appdb-scorers`) evaluated under `search-ctx`, joining bookmark+ tables when `:bookmarked` is among `scorers`."+ [search-results search-ctx scorers]+ (t2/query (cond-> (search.scoring/with-scores search-ctx scorers (search-index-select search-results))+ (:bookmarked scorers) (search.scoring/join-bookmarks (:current-user-id search-ctx)))))++(defn insert-token-tracking!+ "Insert the SemanticSearchTokenTracking `row`."+ [row]+ (t2/insert! :model/SemanticSearchTokenTracking row))++(defn delete-token-tracking-created-before!+ "Delete the SemanticSearchTokenTracking rows created before `cutoff`."+ [cutoff]+ (t2/delete! :model/SemanticSearchTokenTracking {:where [:< :created_at cutoff]}))diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.cljindex 8f1b0957ae1..31640cc0434 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/db/migration/impl.clj@@ -2,6 +2,7 @@(:require[clojure.string :as str][honey.sql :as sql]+ [metabase-enterprise.semantic-search.db :as semantic-search.db][metabase-enterprise.semantic-search.index :as semantic.index][metabase-enterprise.semantic-search.index-metadata :as semantic.index-metadata][metabase-enterprise.semantic-search.util :as semantic.util]@@ -11,8 +12,7 @@[metabase.util :as u][metabase.util.log :as log][next.jdbc :as jdbc]- [next.jdbc.result-set :as jdbc.rs]- [toucan2.core :as t2]))+ [next.jdbc.result-set :as jdbc.rs]))(def schema-version"Version to compare the [[metabase-enterprise.semantic-search.db.migration/db-version]] with. If this is higher,@@ -211,11 +211,8 @@;; Catch covers test setups that exercise pgvector before the appdb schema is up;;; production semantic-search init always runs after appdb migration.(try- (u/for-map [{root-id :id root-type :type} (t2/select [:model/Collection :id :type]- :type [:in library-types]- :location "/")- coll-id (cons root-id (t2/select-pks-set :model/Collection- :location [:like (str "/" root-id "/%")]))]+ (u/for-map [{root-id :id root-type :type} (semantic-search.db/library-root-collections library-types)+ coll-id (cons root-id (semantic-search.db/descendant-collection-ids root-id))][coll-id root-type])(catch Exception e(log/warnf "Skipping Library forest backfill — appdb lookup failed: %s" (ex-message e))@@ -276,11 +273,7 @@(= :authoritative data_authority) (update :authoritative conj id)(and is_published (= :final data_layer)) (update :published conj id)))){:authoritative [] :published []}- (t2/reducible-select [:model/Table :id :is_published :data_layer :data_authority]- {:where [:and- [:= :active true]- [:or [:= :is_published true]- [:= :data_authority ^:allow-raw-sql [:inline "authoritative"]]]]}))+ (semantic-search.db/curated-tables-reducible))(catch Exception e(when-not config/is-test?(throw e))@@ -294,13 +287,11 @@Throws outside tests if the appdb lookup fails."[](try- (let [official-coll-ids (t2/select-pks-set :model/Collection :authority_level :official)]+ (let [official-coll-ids (semantic-search.db/official-collection-ids)](if (empty? official-coll-ids)[](into [] (map (comp str :id))- (t2/reducible-select [:model/Dashboard :id]- {:where [:and [:= :archived false]- [:in :collection_id (vec official-coll-ids)]]}))))+ (semantic-search.db/unarchived-dashboard-ids-in-collections-reducible (vec official-coll-ids)))))(catch Exception e(when-not config/is-test?(throw e))diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/index.cljindex 51c698ccb5d..b51d783a2ef 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/index.clj@@ -8,6 +8,7 @@[honey.sql :as sql][honey.sql.helpers :as sql.helpers][java-time.api :as t]+ [metabase-enterprise.semantic-search.db :as semantic-search.db];; TODO: extract schema code to go under db.migration[metabase-enterprise.semantic-search.embedding :as embedding][metabase-enterprise.semantic-search.scoring :as scoring]@@ -134,8 +135,7 @@Uses at most 2 queries regardless of the number of collection-ids."[collection-ids](when-let [collection-ids (not-empty (set (remove nil? collection-ids)))]- (let [colls (t2/select [:model/Collection :id :personal_owner_id :location]- :id [:in collection-ids])+ (let [colls (semantic-search.db/collection-owners-and-locations collection-ids){personal truenon-personal false} (group-by (comp some? :personal_owner_id) colls)direct (into {} (map (juxt :id :personal_owner_id)) personal)@@ -147,9 +147,7 @@root-id->owner (into direct(map (juxt :id :personal_owner_id))(when (seq unknown-roots)- (t2/select [:model/Collection :id :personal_owner_id]- :id [:in unknown-roots]- :personal_owner_id [:not= nil])))]+ (semantic-search.db/personal-collection-owners unknown-roots)))](into direct(keep (fn [[coll-id root-id]](when-let [owner (get root-id->owner root-id)]@@ -997,7 +995,7 @@fast-filtered (filterv #(coll-readable? (:collection_id %)) fast-docs)slow-t2-instances (vec(for [[t2-model docs] (group-by doc->t2-model slow-docs)- t2-instance (t2/select t2-model :id [:in (map :id docs)])]+ t2-instance (semantic-search.db/instances t2-model (map :id docs))]t2-instance))doc->t2 (comp (u/index-by (juxt :id t2/model) slow-t2-instances)(juxt :id doc->t2-model))@@ -1018,8 +1016,7 @@[docs collection-id](let [collection-ids (keep :collection_id docs)collections-map (when (seq collection-ids)- (->> (t2/select [:collection :id :location]- :id [:in collection-ids])+ (->> (semantic-search.db/collection-locations collection-ids)(into {} (map (juxt :id identity)))))](filterv (fn [doc](let [doc-collection-id (:collection_id doc)]diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/models/token_tracking.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/models/token_tracking.cljindex c4d063f8066..46b228f86c4 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/models/token_tracking.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/models/token_tracking.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.semantic-search.models.token-tracking(:require+ [metabase-enterprise.semantic-search.db :as semantic-search.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -14,6 +15,6 @@(defn record-tokens"Record semantic search token usage."[model request-type total-tokens]- (t2/insert! :model/SemanticSearchTokenTracking {:model_name model- :request_type request-type- :total_tokens total-tokens}))+ (semantic-search.db/insert-token-tracking! {:model_name model+ :request_type request-type+ :total_tokens total-tokens}))diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.cljindex 2db050fb5a6..0a1325c5a51 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/scoring.clj@@ -5,17 +5,16 @@[honey.sql :as sql][honey.sql.helpers :as sql.helpers][medley.core :as m]+ [metabase-enterprise.semantic-search.db :as semantic-search.db][metabase-enterprise.semantic-search.db.datasource :as semantic.db.datasource][metabase.activity-feed.core :as activity-feed]- [metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.premium-features.core :as premium-features][metabase.search.config :as search.config][metabase.search.scoring :as search.scoring][metabase.util :as u][next.jdbc :as jdbc]- [next.jdbc.result-set :as jdbc.rs]- [toucan2.core :as t2]))+ [next.jdbc.result-set :as jdbc.rs]));;;; index-based scorers: these scorers only rely on columns in the search index in the pgvector db@@ -156,26 +155,6 @@;; appdb-based scorers: these scorers rely on tables in the appdb;;-(defn- search-doc->select- [{:keys [id model]}]- ^:allow-subquery- {:select [[^:allow-raw-sql [:inline (str id)]] [^:allow-raw-sql [:inline model]]]})--(defn- search-index-query- [search-results]- {:with [[[:search_index ^:allow-subquery {:columns [:model_id :model]}]- ;; We could use :values here, except MySQL uses a slightly different syntax and I can't seem to get- ;; honeysql to generate a valid WITH ... VALUES statement for MySQL, so fallback to UNION + SELECT- ;; which works with all supported appdbs. https://dev.mysql.com/doc/refman/8.4/en/values.html- ^:allow-subquery- {:union (map search-doc->select search-results)}]]- :select [[[:cast :search_index.model_id (if (= :mysql (mdb/db-type))- :unsigned- :int)]- :id]- [:search_index.model :model]]- :from [:search_index]})-(defn- update-with-appdb-score[weights scorers grouped-appdb-results search-result](let [id-model-key ((juxt :id :model) search-result)@@ -225,16 +204,11 @@combined `:score`."[search-ctx appdb-scorers weights search-results];; search-results-to-score are the search-results that have models that are relevant to the appdb-scorers.- (let [{:keys [current-user-id]} search-ctx- search-results-to-score (filter (comp appdb-scorer-models :model) search-results)- maybe-join-bookmarks #(cond-> % (:bookmarked appdb-scorers) (search.scoring/join-bookmarks current-user-id))]+ (let [search-results-to-score (filter (comp appdb-scorer-models :model) search-results)](if-not (and (seq search-results-to-score)(seq appdb-scorers))search-results- (->> (search-index-query search-results-to-score)- (search.scoring/with-scores search-ctx appdb-scorers)- maybe-join-bookmarks- t2/query+ (->> (semantic-search.db/appdb-scored-rows search-results-to-score search-ctx appdb-scorers)(update-with-appdb-scores weights (keys appdb-scorers) search-results)(sort-by :score >)vec))))diff --git a/enterprise/backend/src/metabase_enterprise/semantic_search/task/usage_trimmer.clj b/enterprise/backend/src/metabase_enterprise/semantic_search/task/usage_trimmer.cljindex 9a8d4a7e9df..b86688c1529 100644--- a/enterprise/backend/src/metabase_enterprise/semantic_search/task/usage_trimmer.clj+++ b/enterprise/backend/src/metabase_enterprise/semantic_search/task/usage_trimmer.clj@@ -3,10 +3,10 @@[clojurewerkz.quartzite.jobs :as jobs][clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers]+ [metabase-enterprise.semantic-search.db :as semantic-search.db][metabase-enterprise.semantic-search.util :as semantic.u][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.sql Timestamp)(org.quartz DisallowConcurrentExecution)))@@ -23,7 +23,7 @@(when (semantic.u/semantic-search-available?)(log/info "Attempting to delete old semantic search usage data.")(let [t (Timestamp/valueOf (.minusMonths (java.time.LocalDateTime/now) storage-months))]- (t2/delete! :model/SemanticSearchTokenTracking {:where [:< :created_at t]}))+ (semantic-search.db/delete-token-tracking-created-before! t))(log/info "Semantic search old data cleanup successful.")))(task/defjob ^{DisallowConcurrentExecution truediff --git a/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj b/enterprise/backend/src/metabase_enterprise/serialization/cmd.cljindex 87c20ad9d60..255e2490433 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/cmd.clj@@ -2,6 +2,7 @@(:require[clojure.java.io :as io][clojure.string :as str]+ [metabase-enterprise.serialization.db :as serialization.db][metabase-enterprise.serialization.v2.extract :as v2.extract][metabase-enterprise.serialization.v2.ingest :as v2.ingest][metabase-enterprise.serialization.v2.load :as v2.load]@@ -17,8 +18,7 @@[metabase.util :as u][metabase.util.i18n :refer [trs]][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(clojure.lang ExceptionInfo)))@@ -97,7 +97,7 @@(log/infof "Exporting Metabase to %s" path)(mdb/setup-db! :create-sample-content? false)(check-premium-token!)- (t2/select :model/User) ;; TODO -- why??? [editor's note: this comment originally from Cam]+ (serialization.db/all-users) ;; TODO -- why??? [editor's note: this comment originally from Cam](let [f (io/file path)](.mkdirs f)(when-not (.canWrite f)diff --git a/enterprise/backend/src/metabase_enterprise/serialization/db.clj b/enterprise/backend/src/metabase_enterprise/serialization/db.cljnew file mode 100644index 00000000000..a04e5ab0d45--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/serialization/db.clj@@ -0,0 +1,46 @@+(ns metabase-enterprise.serialization.db+ "Application database queries for the serialization module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model-level helpers."+ (:require+ [toucan2.core :as t2]))++(defn all-users+ "Every User."+ []+ (t2/select :model/User))++(defn collection-id-row+ "The `:collection_id` row of the instance of `model` with `id`, or nil."+ [model id]+ (t2/select-one [model :collection_id] :id id))++(defn existing-ids+ "The subset of `ids` for which an instance of `model` exists."+ [model ids]+ (t2/select-pks-set model {:where [:in :id ids]}))++(defn instance-exists?+ "Whether an instance of `model` whose primary key is `id` exists."+ [model id]+ (t2/exists? model (first (t2/primary-keys model)) id))++(defn root-collections-for-user+ "The top-level non-analytics Collections that are not personal or belong to the User with `user-id`."+ [user-id]+ (t2/select :model/Collection {:where [:and [:= :location "/"]+ [:or [:= :personal_owner_id nil]+ [:= :personal_owner_id user-id]]+ [:or [:= :namespace nil]+ [:!= :namespace "analytics"]]]}))++(defn analytics-root-collections+ "The Collections in the analytics namespace."+ []+ (t2/select :model/Collection {:where [:= :namespace "analytics"]}))++(defn card-ids-in-collections+ "The subset of `card-ids` living in the Collections with `collection-ids`."+ [card-ids collection-ids]+ (t2/select-pks-set :model/Card {:where [:and+ [:in :id card-ids]+ [:in :collection_id collection-ids]]}))diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.cljindex 3c1e10295ac..f621223f09e 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj@@ -10,6 +10,7 @@check driven by [[metabase.models.serialization/serialization-dependencies]]."(:require[medley.core :as m]+ [metabase-enterprise.serialization.db :as serialization.db][metabase-enterprise.serialization.v2.models :as serdes.models][metabase.models.serialization :as serdes][metabase.util :as u]@@ -24,7 +25,7 @@"[no collection]"))(defn- entity-label [{:keys [model id]}]- (let [entity (t2/select-one [model :collection_id] :id id)]+ (let [entity (serialization.db/collection-id-row model id)](format "%s %d (from collection %s)" (name model) id (collection-label (:collection_id entity)))))(defn- resize-batch@@ -72,7 +73,7 @@(into #{}(comp (distinct)(partition-all serdes/query-batch-size)- (mapcat #(t2/select-pks-set (keyword "model" model) {:where [:in :id %]})))+ (mapcat #(serialization.db/existing-ids (keyword "model" model) %)))ids))(def ^:private structural-content-modelsdiff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.cljindex bfa5a548d87..914e26e8b16 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/extract.clj@@ -4,13 +4,13 @@See the detailed descriptions of the (de)serialization processes in [[metabase.models.serialization]]."(:require[clojure.set :as set]+ [metabase-enterprise.serialization.db :as serialization.db][metabase-enterprise.serialization.v2.dependency-validation :as dependency-validation][metabase-enterprise.serialization.v2.models :as serdes.models][metabase.collections.models.collection :as collection][metabase.models.serialization :as serdes][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -60,11 +60,7 @@Does not export ee-only analytics collections."[user-id]- (let [roots (t2/select :model/Collection {:where [:and [:= :location "/"]- [:or [:= :personal_owner_id nil]- [:= :personal_owner_id user-id]]- [:or [:= :namespace nil]- [:!= :namespace "analytics"]]]})]+ (let [roots (serialization.db/root-collections-for-user user-id)];; start with the special "nil" root collection ID(-> #{nil}(into (map :id) roots)@@ -90,7 +86,7 @@[model-name resolved-id](throw (missing-target-error model-name "entity ID" id)))(let [model (keyword "model" model-name)]- (when-not (t2/exists? model (first (t2/primary-keys model)) id)+ (when-not (serialization.db/instance-exists? model id)(throw (missing-target-error model-name "ID" id)))target)))@@ -98,7 +94,7 @@"Returns a set of collection IDs that are in the 'analytics' namespace (internal analytics collections).These collections are intentionally excluded from serialization."[]- (let [analytics-roots (t2/select :model/Collection {:where [:= :namespace "analytics"]})]+ (let [analytics-roots (serialization.db/analytics-root-collections)](into (set (map :id analytics-roots))(mapcat collection/descendant-ids)analytics-roots)))@@ -113,9 +109,7 @@(into #{}(comp (partition-all serdes/query-batch-size)(mapcat (fn [batch]- (t2/select-pks-set :model/Card {:where [:and- [:in :id (vec batch)]- [:in :collection_id (vec analytics-colls)]]}))))+ (serialization.db/card-ids-in-collections (vec batch) (vec analytics-colls)))))card-ids)#{})))diff --git a/enterprise/backend/src/metabase_enterprise/snippet_collections/db.clj b/enterprise/backend/src/metabase_enterprise/snippet_collections/db.cljnew file mode 100644index 00000000000..86eb0541f38--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/snippet_collections/db.clj@@ -0,0 +1,12 @@+(ns metabase-enterprise.snippet-collections.db+ "Application database queries for the snippet-collections module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn snippet-with-collection-id+ "The `:collection_id` of the NativeQuerySnippet with `id`, or nil if no such NativeQuerySnippet exists. Unlike a+ bare column lookup, this distinguishes a missing snippet (nil) from one filed under the root collection+ (`{:collection_id nil}`)."+ [id]+ (t2/select-one [:model/NativeQuerySnippet :collection_id] :id id))diff --git a/enterprise/backend/src/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions.clj b/enterprise/backend/src/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions.cljindex e2eb2b78f3b..bfe72945bee 100644--- a/enterprise/backend/src/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions.clj@@ -1,14 +1,14 @@(ns metabase-enterprise.snippet-collections.models.native-query-snippet.permissions"EE implementation of NativeQuerySnippet permissions."(:require+ [metabase-enterprise.snippet-collections.db :as snippet-collections.db][metabase.models.interface :as mi][metabase.native-query-snippets.core :as snippets][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.remote-sync.core :as remote-sync][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(mu/defn- has-parent-collection-perms?[snippet :- [:map [:collection_id [:maybe ms/PositiveInt]]]@@ -23,8 +23,8 @@(not (perms/sandboxed-user?))(snippets/has-any-native-permissions?)(has-parent-collection-perms? snippet :read)))- ([model id]- (can-read? (t2/select-one [model :collection_id] :id id))))+ ([_model id]+ (can-read? (snippet-collections.db/snippet-with-collection-id id))))(defenterprise can-write?"Can the current User edit this `snippet`?"@@ -35,8 +35,8 @@(snippets/has-any-native-permissions?)(has-parent-collection-perms? snippet :write)(remote-sync/model-editable? :model/NativeQuerySnippet snippet)))- ([model id]- (can-write? (t2/select-one [model :collection_id] :id id))))+ ([_model id]+ (can-write? (snippet-collections.db/snippet-with-collection-id id))))(defenterprise can-create?"Can the current User save a new Snippet with the values in `m`?"diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj b/enterprise/backend/src/metabase_enterprise/sso/api/sso.cljindex bb1bfae6aaa..4281f0be535 100644--- a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj@@ -5,6 +5,7 @@we can have a uniform interface both via the API and code"(:require[metabase-enterprise.sso.api.interface :as sso.i]+ [metabase-enterprise.sso.db :as sso.db][metabase-enterprise.sso.integrations.jwt :as jwt][metabase-enterprise.sso.integrations.oidc :as oidc-integration][metabase-enterprise.sso.integrations.saml]@@ -18,8 +19,7 @@[metabase.util.malli :as mu][metabase.util.malli.schema :as ms][saml20-clj.core :as saml]- [stencil.core :as stencil]- [toucan2.core :as t2]))+ [stencil.core :as stencil]))(set! *warn-on-reflection* true)@@ -103,14 +103,11 @@(let [metabase-session-key (get-in cookies [request/metabase-session-cookie :value])metabase-session-key-hashed (session/hash-session-key metabase-session-key){:keys [email sso_source]}- (t2/query-one {:select [:u.email :u.sso_source]- :from [[:core_user :u]]- :join [[:core_session :session] [:= :u.id :session.user_id]]- :where [:= :key_hashed metabase-session-key-hashed]})]+ (sso.db/session-user-email-and-source metabase-session-key-hashed)];; If a user doesn't have SLO setup on their IdP,;; they will never hit "/handle_slo" so we must delete the session here:(when-not (sso-settings/saml-slo-enabled)- (t2/delete! :model/Session :key_hashed metabase-session-key-hashed))+ (sso.db/delete-session! metabase-session-key-hashed)){:saml-logout-url(when (and (sso-settings/saml-slo-enabled)(= sso_source "saml"))diff --git a/enterprise/backend/src/metabase_enterprise/sso/db.clj b/enterprise/backend/src/metabase_enterprise/sso/db.cljnew file mode 100644index 00000000000..dcb03e7eca5--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/sso/db.clj@@ -0,0 +1,43 @@+(ns metabase-enterprise.sso.db+ "Application database queries for the sso module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself."+ (:require+ [toucan2.core :as t2]))++(defn session-user-email-and-source+ "The email and SSO source of the User owning the Session with `session-key-hashed`, or nil."+ [session-key-hashed]+ (t2/query-one {:select [:u.email :u.sso_source]+ :from [[:core_user :u]]+ :join [[:core_session :session] [:= :u.id :session.user_id]]+ :where [:= :key_hashed session-key-hashed]}))++(defn delete-session!+ "Delete the Session with `session-key-hashed`."+ [session-key-hashed]+ (t2/delete! :model/Session :key_hashed session-key-hashed))++(defn group-ids-by-name+ "The IDs of the PermissionsGroups named one of `group-names`."+ [group-names]+ (t2/select-pks-set :model/PermissionsGroup :name [:in group-names]))++(defn insert-relay-state!+ "Insert the SsoRelayState `row`."+ [row]+ (t2/insert! :model/SsoRelayState row))++(defn unexpired-relay-state+ "The SsoRelayState with `hashed-key` expiring after `now`, or nil."+ [hashed-key now]+ (t2/select-one :model/SsoRelayState :id hashed-key :expires_at [:> now]))++(defn delete-relay-state!+ "Delete the SsoRelayState with `hashed-key`."+ [hashed-key]+ (t2/delete! :model/SsoRelayState :id hashed-key))++(defn delete-relay-states-expired-at!+ "Delete the SsoRelayStates expired at or before `now`, returning the number deleted."+ [now]+ (t2/delete! :model/SsoRelayState :expires_at [:<= now]))diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.cljindex ed1946f764f..3ad5013796a 100644--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/saml.clj@@ -32,6 +32,7 @@[clojure.string :as str][java-time.api :as t][metabase-enterprise.sso.api.interface :as sso.i]+ [metabase-enterprise.sso.db :as sso.db][metabase-enterprise.sso.integrations.saml-utils :as saml-utils][metabase-enterprise.sso.integrations.sso-utils :as sso-utils][metabase-enterprise.sso.integrations.token-utils :as token-utils]@@ -50,8 +51,7 @@[metabase.util.i18n :refer [trs tru]][metabase.util.log :as log][ring.util.response :as response]- [saml20-clj.core :as saml]- [toucan2.core :as t2]))+ [saml20-clj.core :as saml]))(set! *warn-on-reflection* true)@@ -242,7 +242,7 @@:response-validators [:signature :require-authenticated :issuer]})](if-let [metabase-session-key (and (saml/logout-success? response) (get-in cookies [request/metabase-session-cookie :value]))](do- (t2/delete! :model/Session :key_hashed (session/hash-session-key metabase-session-key))+ (sso.db/delete-session! (session/hash-session-key metabase-session-key))(request/clear-session-cookie (response/redirect (system/site-url)))){:status 500 :body "SAML logout failed."}))(log/warn "SAML SLO is not enabled, not continuing Single Log Out flow.")))diff --git a/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.clj b/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.cljindex 85800660680..b12547ba1d9 100644--- a/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/models/relay_state.clj@@ -9,6 +9,7 @@[buddy.core.hash :as buddy-hash][clojure.string :as str][java-time.api :as t]+ [metabase-enterprise.sso.db :as sso.db][metabase.util.random :as random][methodical.core :as methodical][toucan2.core :as t2])@@ -61,12 +62,11 @@- `:origin` - postMessage target origin (embedding popup only)- `:embedding?` - whether this is a modular-embedding popup login"[{:keys [id continue-url origin embedding?]}]- (t2/insert! :model/SsoRelayState- {:id (hash-key id)- :continue_url continue-url- :origin origin- :embedding (boolean embedding?)- :expires_at (t/plus (t/offset-date-time) (t/seconds ttl-seconds))})+ (sso.db/insert-relay-state! {:id (hash-key id)+ :continue_url continue-url+ :origin origin+ :embedding (boolean embedding?)+ :expires_at (t/plus (t/offset-date-time) (t/seconds ttl-seconds))})id)(defn find-unexpired@@ -75,7 +75,7 @@retried callback doesn't burn the key."[key](when (relay-state-key? key)- (t2/select-one :model/SsoRelayState :id (hash-key key) :expires_at [:> (t/offset-date-time)])))+ (sso.db/unexpired-relay-state (hash-key key) (t/offset-date-time))))(defn delete!"Consume (delete) the RelayState entry for the (plaintext) `key`. Called after a successful login; the single@@ -83,9 +83,9 @@nothing)."[key](when (relay-state-key? key)- (t2/delete! :model/SsoRelayState :id (hash-key key))))+ (sso.db/delete-relay-state! (hash-key key))))(defn delete-expired!"Delete all expired RelayState entries (abandoned logins that never came back). Returns the number deleted."[]- (t2/delete! :model/SsoRelayState :expires_at [:<= (t/offset-date-time)]))+ (sso.db/delete-relay-states-expired-at! (t/offset-date-time)))diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.cljindex 165c72ded7a..20f2d2b8bf9 100644--- a/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/jwt.clj@@ -2,6 +2,7 @@"JWT authentication provider implementation."(:require[buddy.sign.jwt :as jwt]+ [metabase-enterprise.sso.db :as sso.db][metabase-enterprise.sso.integrations.sso-utils :as sso-utils][metabase-enterprise.sso.settings :as sso-settings][metabase.auth-identity.core :as auth-identity]@@ -10,8 +11,7 @@[metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(set! *warn-on-reflection* true)@@ -163,7 +163,7 @@(sso-utils/group-names->ids group-names name-mappings)(let [names (into #{} (sso-utils/group-names->strings group-names))](when (seq names)- (t2/select-pks-set :model/PermissionsGroup :name [:in names])))))+ (sso.db/group-ids-by-name names)))))(methodical/defmethod auth-identity/login! :after :provider/jwt"Sync JWT group memberships after successful login.diff --git a/enterprise/backend/src/metabase_enterprise/stale/api.clj b/enterprise/backend/src/metabase_enterprise/stale/api.cljindex 0bc0858df48..5b751bbda3f 100644--- a/enterprise/backend/src/metabase_enterprise/stale/api.clj+++ b/enterprise/backend/src/metabase_enterprise/stale/api.clj@@ -3,6 +3,7 @@Currently supports Dashboards and Cards."(:require[java-time.api :as t]+ [metabase-enterprise.stale.db :as stale.db][metabase-enterprise.stale.impl :as stale][metabase.analytics.core :as analytics][metabase.api.common :as api]@@ -40,7 +41,7 @@(remove coll-id->coll))(vals coll-id->coll))coll-id->coll (merge (if (seq to-fetch)- (t2/select-pk->fn identity :model/Collection :id [:in to-fetch])+ (stale.db/collections-by-id to-fetch){})coll-id->coll)annotate (fn [x]@@ -56,36 +57,7 @@(map annotate rows)))(defmethod present-model-items :model/Card [_ cards]- (->> (t2/hydrate (t2/select [:model/Card- :id- :dashboard_id- :description- :collection_id- :name- :entity_id- :archived- :collection_position- :display- :collection_preview- :database_id- [nil :location]- :dataset_query- :card_schema- :last_used_at- [^:allow-subquery- {:select [:status]- :from [:moderation_review]- :where [:and- [:= :moderated_item_type "card"]- [:= :moderated_item_id :report_card.id]- [:= :most_recent true]]- ;; limit 1 to ensure that there is only one result but this invariant should hold true, just- ;; protecting against potential bugs- :order-by [[:id :desc]]- :limit 1}- :moderated_status]]- :id [:in (set (map :id cards))])- :can_write :can_delete :can_restore [:collection :effective_location] :dashboard_count [:dashboard :moderation_status])+ (->> (t2/hydrate (stale.db/stale-cards (set (map :id cards))) :can_write :can_delete :can_restore [:collection :effective_location] :dashboard_count [:dashboard :moderation_status])present-collections(map (fn [card](-> card@@ -104,21 +76,7 @@:is_tenant_dashboard (some-> parent-coll collection/shared-tenant-collection?))))(defmethod present-model-items :model/Dashboard [_ dashboards]- (->> (t2/hydrate (t2/select [:model/Dashboard- :id- :description- :collection_id- :name- :entity_id- :archived- :collection_position- [:last_viewed_at :last_used_at]- ["dashboard" :model]- [nil :dashboard_id]- [nil :location]- [nil :database_id]]- :id [:in (set (map :id dashboards))])- :can_write :can_delete :can_restore [:collection :effective_location])+ (->> (t2/hydrate (stale.db/stale-dashboards (set (map :id dashboards))) :can_write :can_delete :can_restore [:collection :effective_location])annotate-dashboard-with-collection-infopresent-collections))@@ -154,7 +112,7 @@(t/minus (t/local-date) (t/months 6)))collection (if (= id :root)collection/root-collection- (t2/select-one :model/Collection id))+ (stale.db/collection id))_ (api/read-check collection)collection-ids (->> (if is_recursive(conj (effective-children-ids collection @api/*current-user-permissions-set*)diff --git a/enterprise/backend/src/metabase_enterprise/stale/db.clj b/enterprise/backend/src/metabase_enterprise/stale/db.cljnew file mode 100644index 00000000000..48774e8b98c--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/stale/db.clj@@ -0,0 +1,92 @@+(ns metabase-enterprise.stale.db+ "Application database queries for the stale module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection collection-id))++(defn collections-by-id+ "A map of ID to Collection for `collection-ids`."+ [collection-ids]+ (t2/select-pk->fn identity :model/Collection :id [:in collection-ids]))++(defn stale-cards+ "The listing columns of the Cards with `card-ids`, with their latest moderation status."+ [card-ids]+ (t2/select [:model/Card+ :id+ :dashboard_id+ :description+ :collection_id+ :name+ :entity_id+ :archived+ :collection_position+ :display+ :collection_preview+ :database_id+ [nil :location]+ :dataset_query+ :card_schema+ :last_used_at+ [^:allow-subquery+ {:select [:status]+ :from [:moderation_review]+ :where [:and+ [:= :moderated_item_type "card"]+ [:= :moderated_item_id :report_card.id]+ [:= :most_recent true]]+ ;; limit 1 to ensure that there is only one result but this invariant should hold true, just+ ;; protecting against potential bugs+ :order-by [[:id :desc]]+ :limit 1}+ :moderated_status]]+ :id [:in card-ids]))++(defn stale-dashboards+ "The listing columns of the Dashboards with `dashboard-ids`."+ [dashboard-ids]+ (t2/select [:model/Dashboard+ :id+ :description+ :collection_id+ :name+ :entity_id+ :archived+ :collection_position+ [:last_viewed_at :last_used_at]+ ["dashboard" :model]+ [nil :dashboard_id]+ [nil :location]+ [nil :database_id]]+ :id [:in dashboard-ids]))++(defn- stale-content-union+ "The union of `union-queries` (per-model SELECTs from `metabase.staleness.core/find-stale-query`),+ aliased for use as a `:from` source."+ [union-queries]+ [[^:allow-subquery {:union-all union-queries} :dummy_alias]])++(defn stale-content-rows+ "A page of `:id`/`:model` rows from the union of `union-queries`, sorted by `sort-column` (`:name` or+ `:last_used_at`) in `sort-direction`, skipping `offset` and returning up to `limit` (either may be nil for no+ restriction)."+ [union-queries sort-column sort-direction limit offset]+ (t2/query (cond-> {:select [:id :model]+ :from (stale-content-union union-queries)+ :order-by [[(case sort-column+ :name :%lower.name+ :last_used_at :last_used_at)+ sort-direction]]}+ (some? limit) (assoc :limit limit)+ (some? offset) (assoc :offset offset))))++(defn stale-content-count+ "The total count of rows across every page [[stale-content-rows]] would return for `union-queries`."+ [union-queries]+ (:count (t2/query-one {:select [[:%count.* :count]]+ :from (stale-content-union union-queries)})))diff --git a/enterprise/backend/src/metabase_enterprise/stale/impl.clj b/enterprise/backend/src/metabase_enterprise/stale/impl.cljindex 3bed7ffaa07..e0d4647fabc 100644--- a/enterprise/backend/src/metabase_enterprise/stale/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/stale/impl.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.stale.impl(:require+ [metabase-enterprise.stale.db :as stale.db][metabase.staleness.core :as staleness][metabase.util.malli :as mu][toucan2.core :as t2]))@@ -16,11 +17,6 @@[:sort-direction [:enum {:doc "The direction to sort by."} :asc :desc]][:models {:optional true} [:set {:doc "The set of models to search for stale content."} :keyword]]])-(defn- sort-column [column]- (case column- :name :%lower.name- :last_used_at :last_used_at))-(defn- queries [{:keys [models] :or {models #{:model/Card :model/Dashboard}} :as args}];; Ensure each model's namespace is loaded so its `find-stale-query` method is registered before we;; dispatch — passing the `:model/X` keyword alone does not trigger Toucan model resolution.@@ -29,20 +25,6 @@(throw (ex-info (str "No staleness method registered for: " (vec unsupported)) {})))(map #(staleness/find-stale-query % args) models))-(mu/defn ^:private rows-query [{:keys [limit offset] :as args} :- FindStaleContentArgs]- (cond-> {:select [:id :model]- :from [[^:allow-subquery {:union-all (queries args)} :dummy_alias]]- :order-by [[(sort-column (:sort-column args))- (:sort-direction args)]]}- (some? limit) ;; limit- (assoc :limit limit)- (some? offset) ;; offset- (assoc :offset offset)))--(mu/defn ^:private total-query [args :- FindStaleContentArgs]- {:select [[:%count.* :count]]- :from [[^:allow-subquery {:union-all (queries args)} :dummy_alias]]})-(mu/defn find-candidates :- [:map[:rows [:sequential [:map[:id pos-int?]@@ -69,11 +51,12 @@- `:total` (the total count of stale elements that could be found if you iterated through all pages)"- [{:keys [collection-ids] :as args} :- FindStaleContentArgs]+ [{:keys [collection-ids limit offset sort-column sort-direction] :as args} :- FindStaleContentArgs](when (contains? collection-ids :root) (throw (ex-info "not implemented." {:collection-ids collection-ids})))- {:rows (into []- (comp- (map #(select-keys % [:id :model]))- (map (fn [v] (update v :model #(keyword "model" %)))))- (t2/query (rows-query args)))- :total (:count (t2/query-one (total-query args)))})+ (let [union-queries (queries args)]+ {:rows (into []+ (comp+ (map #(select-keys % [:id :model]))+ (map (fn [v] (update v :model #(keyword "model" %)))))+ (stale.db/stale-content-rows union-queries sort-column sort-direction limit offset))+ :total (stale.db/stale-content-count union-queries)}))diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.cljindex e6f6951882b..9e3bf710ff2 100644--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/core.clj@@ -2,6 +2,7 @@"Core business logic for support access grant management."(:require[java-time.api :as t]+ [metabase-enterprise.support-access-grants.db :as support-access-grants.db][metabase-enterprise.support-access-grants.models.support-access-grant-log :as sag.model][metabase-enterprise.support-access-grants.provider :as sag.provider][metabase-enterprise.support-access-grants.settings :as sag.settings]@@ -19,9 +20,7 @@"Check if there is an active (non-revoked, non-expired) grant."[](let [now (t/instant)]- (t2/exists? :model/SupportAccessGrantLog- :revoked_at nil- :grant_end_timestamp [:> now])))+ (support-access-grants.db/active-grant-exists? now)))(defn create-grant!"Create a new support access grant.@@ -47,7 +46,7 @@:notes notes:grant_start_timestamp now:grant_end_timestamp grant-end}- grant (-> (t2/insert-returning-instance! :model/SupportAccessGrantLog grant-record)+ grant (-> (support-access-grants.db/insert-grant! grant-record)(t2/hydrate :user_info))support-email (sag.settings/support-access-grant-email)support-user (sag.model/fetch-or-create-support-user!)@@ -80,7 +79,7 @@- Grant doesn't exist- Grant is already revoked"[user-id grant-id]- (let [grant (t2/select-one :model/SupportAccessGrantLog :id grant-id)]+ (let [grant (support-access-grants.db/grant grant-id)](when-not grant(throw (ex-info (tru "Grant not found"){:status-code 404})))@@ -88,10 +87,10 @@(throw (ex-info (tru "Grant is already revoked"){:status-code 400})))(let [now (t/instant)]- (t2/update! :model/SupportAccessGrantLog grant-id- {:revoked_at now- :revoked_by_user_id user-id})- (-> (t2/select-one :model/SupportAccessGrantLog :id grant-id)+ (support-access-grants.db/update-grant! grant-id+ {:revoked_at now+ :revoked_by_user_id user-id})+ (-> (support-access-grants.db/grant grant-id)(t2/hydrate :user_info)))))(defn expire-ended-grants!@@ -100,8 +99,8 @@A no-op when there is no support user, when a grant is still running, or when access is already torn down."[](when-let [{support-user-id :id, superuser? :is_superuser}- (t2/select-one [:model/User :id :is_superuser] :email (sag.settings/support-access-grant-email))]- (when (or superuser? (t2/exists? :model/Session :user_id support-user-id))+ (support-access-grants.db/user-superuser-flag-by-email (sag.settings/support-access-grant-email))]+ (when (or superuser? (support-access-grants.db/session-exists-for-user? support-user-id))(cluster-lock/with-cluster-lock grant-lifecycle-lock;; Re-check after acquiring the same lock used by grant creation. This makes credential teardown and grant;; creation mutually exclusive across the cluster, so teardown cannot invalidate a newly created grant.@@ -130,33 +129,9 @@(let [limit (min (or limit 50) 100)offset (or offset 0)- where-conditions (cond-> []- (not include-revoked)- (conj [:= :revoked_at nil])-- ticket-number- (conj [:= :ticket_number ticket-number])-- user-id- (conj [:= :user_id user-id]))- where-clause (when (seq where-conditions)- (if (= 1 (count where-conditions))- (first where-conditions)- (into [:and] where-conditions)))- grants (if where-clause- (t2/select :model/SupportAccessGrantLog- {:where where-clause- :limit limit- :offset offset- :order-by [[:created_at :desc]]})- (t2/select :model/SupportAccessGrantLog- {:limit limit- :offset offset- :order-by [[:created_at :desc]]}))+ grants (support-access-grants.db/grants-page include-revoked ticket-number user-id limit offset)grants-with-user-name (t2/hydrate grants :user_info)- total (if where-clause- (t2/count :model/SupportAccessGrantLog {:where where-clause})- (t2/count :model/SupportAccessGrantLog))]+ total (support-access-grants.db/grant-count include-revoked ticket-number user-id)]{:data grants-with-user-name:total total:limit limit@@ -167,9 +142,5 @@Returns the active grant record or nil if no active grant exists."[]- (some-> (t2/select-one :model/SupportAccessGrantLog- {:where [:and [:= :revoked_at nil]- [:> :grant_end_timestamp :%now]]- :order-by [[:created_at :desc]- [:id :desc]]})+ (some-> (support-access-grants.db/current-grant)(t2/hydrate :user_info)))diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/db.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/db.cljnew file mode 100644index 00000000000..0081b59162a--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/db.clj@@ -0,0 +1,127 @@+(ns metabase-enterprise.support-access-grants.db+ "Application database queries for the support-access-grants module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods, and transactions."+ (:require+ [toucan2.core :as t2]))++(defn active-grant-exists?+ "Whether a SupportAccessGrantLog is unrevoked and ends after `now`."+ [now]+ (t2/exists? :model/SupportAccessGrantLog :revoked_at nil :grant_end_timestamp [:> now]))++(defn grant+ "The SupportAccessGrantLog with `grant-id`, or nil."+ [grant-id]+ (t2/select-one :model/SupportAccessGrantLog :id grant-id))++(defn current-grant+ "The newest unrevoked SupportAccessGrantLog that has not ended, or nil."+ []+ (t2/select-one :model/SupportAccessGrantLog+ {:where [:and [:= :revoked_at nil]+ [:> :grant_end_timestamp :%now]]+ :order-by [[:created_at :desc]+ [:id :desc]]}))++(defn- grants-where+ [include-revoked? ticket-number user-id]+ (let [conditions (cond-> []+ (not include-revoked?) (conj [:= :revoked_at nil])+ ticket-number (conj [:= :ticket_number ticket-number])+ user-id (conj [:= :user_id user-id]))]+ (when (seq conditions)+ (into [:and] conditions))))++(defn grants-page+ "The newest-first SupportAccessGrantLogs, optionally narrowed to `ticket-number` and `user-id` and excluding revoked+ grants unless `include-revoked?`, paged by `limit` and `offset`."+ [include-revoked? ticket-number user-id limit offset]+ (let [where (grants-where include-revoked? ticket-number user-id)]+ (t2/select :model/SupportAccessGrantLog+ (cond-> {:limit limit+ :offset offset+ :order-by [[:created_at :desc]]}+ where (assoc :where where)))))++(defn grant-count+ "The number of SupportAccessGrantLogs [[grants-page]] would page through."+ [include-revoked? ticket-number user-id]+ (let [where (grants-where include-revoked? ticket-number user-id)]+ (t2/count :model/SupportAccessGrantLog+ (cond-> {}+ where (assoc :where where)))))++(defn insert-grant!+ "Insert `grant` and return the new instance."+ [grant]+ (t2/insert-returning-instance! :model/SupportAccessGrantLog grant))++(defn update-grant!+ "Apply `changes` to the SupportAccessGrantLog with `grant-id`."+ [grant-id changes]+ (t2/update! :model/SupportAccessGrantLog grant-id changes))++(defn user+ "The User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User user-id))++(defn user-by-email+ "The User with `email`, or nil."+ [email]+ (t2/select-one :model/User :email email))++(defn user-superuser-flag-by-email+ "The `:id` and `:is_superuser` of the User with `email`, or nil."+ [email]+ (t2/select-one [:model/User :id :is_superuser] :email email))++(defn user-names-and-emails+ "A map of User ID to first name and email for `user-ids`."+ [user-ids]+ (t2/select-pk->fn #(select-keys % [:first_name :email]) [:model/User :id :first_name :email] :id [:in user-ids]))++(defn insert-user!+ "Insert `user` and return the new instance."+ [user]+ (t2/insert-returning-instance! :model/User user))++(defn update-user!+ "Apply `changes` to the User with `user-id`."+ [user-id changes]+ (t2/update! :model/User user-id changes))++(defn session-exists-for-user?+ "Whether the User with `user-id` has a Session."+ [user-id]+ (t2/exists? :model/Session :user_id user-id))++(defn delete-sessions-of-user!+ "Delete the Sessions of the User with `user-id`."+ [user-id]+ (t2/delete! :model/Session :user_id user-id))++(defn auth-identity-ids-of-user+ "The IDs of the AuthIdentities of the User with `user-id`."+ [user-id]+ (t2/select-pks-vec :model/AuthIdentity :user_id user-id))++(defn support-access-auth-identity-id+ "The ID of the support-access-grant AuthIdentity of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one-pk :model/AuthIdentity :user_id user-id :provider "support-access-grant"))++(defn insert-auth-identity!+ "Insert the AuthIdentity `row`."+ [row]+ (t2/insert! :model/AuthIdentity row))++(defn update-auth-identity!+ "Apply `changes` to the AuthIdentity with `auth-identity-id`."+ [auth-identity-id changes]+ (t2/update! :model/AuthIdentity auth-identity-id changes))++(defn expire-auth-identities!+ "Set the expiry of the AuthIdentities with `auth-identity-ids` to `expires-at`."+ [auth-identity-ids expires-at]+ (t2/update! :model/AuthIdentity :id [:in auth-identity-ids] {:expires_at expires-at}))diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.cljindex 3d0eeb61d20..445dd20b794 100644--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/models/support_access_grant_log.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.support-access-grants.models.support-access-grant-log"Model for support access grant log entries. Tracks temporary access grants for customer support."(:require+ [metabase-enterprise.support-access-grants.db :as support-access-grants.db][metabase-enterprise.support-access-grants.settings :as sag.settings][metabase.models.interface :as mi][metabase.util :as u]@@ -24,23 +25,20 @@If the user exists but is deactivated, reactivate them.Always ensures the support user has superuser access."[]- (if-let [user (t2/select-one :model/User :email (sag.settings/support-access-grant-email))]+ (if-let [user (support-access-grants.db/user-by-email (sag.settings/support-access-grant-email))](do- (t2/update! :model/User (:id user) {:is_active true :is_superuser true})+ (support-access-grants.db/update-user! (:id user) {:is_active true :is_superuser true})(assoc user :is_active true :is_superuser true))- (t2/insert-returning-instance! :model/User- {:email (sag.settings/support-access-grant-email)- :first_name (sag.settings/support-access-grant-first-name)- :last_name (sag.settings/support-access-grant-last-name)- :is_superuser true})))+ (support-access-grants.db/insert-user! {:email (sag.settings/support-access-grant-email)+ :first_name (sag.settings/support-access-grant-first-name)+ :last_name (sag.settings/support-access-grant-last-name)+ :is_superuser true})))(methodical/defmethod t2/batched-hydrate [:model/SupportAccessGrantLog :user_info][_model _k grants](let [user-ids (keep :user_id grants)user-info (when (seq user-ids)- (t2/select-pk->fn #(select-keys % [:first_name :email])- [:model/User :id :first_name :email]- :id [:in user-ids]))]+ (support-access-grants.db/user-names-and-emails user-ids))](for [grant grants](let [user-info (get user-info (:user_id grant))](assoc grant@@ -52,20 +50,20 @@time-limited password can't be used again, and delete their sessions. Called both when a grant is explicitlyrevoked and when one simply runs out."[support-user-id ended-at]- (let [auth-identity-ids (t2/select-pks-vec :model/AuthIdentity :user_id support-user-id)]+ (let [auth-identity-ids (support-access-grants.db/auth-identity-ids-of-user support-user-id)](try- (t2/update! :model/User support-user-id {:is_superuser false})+ (support-access-grants.db/update-user! support-user-id {:is_superuser false})(catch Exception e;; If the support user is somehow the last admin, we can't remove superuser via model hooks.;; Sessions and auth identities are still cleaned up below, preventing further access.(log/warnf "Could not remove superuser from support user %d: %s" support-user-id (ex-message e))))(when (seq auth-identity-ids)- (t2/update! :model/AuthIdentity :id [:in auth-identity-ids] {:expires_at ended-at}))- (t2/delete! :model/Session :user_id support-user-id)))+ (support-access-grants.db/expire-auth-identities! auth-identity-ids ended-at))+ (support-access-grants.db/delete-sessions-of-user! support-user-id)))(t2/define-after-update :model/SupportAccessGrantLog[{revoked-at :revoked_at :as grant}](u/prog1 grant(when revoked-at- (when-let [support-user (t2/select-one :model/User :email (sag.settings/support-access-grant-email))]+ (when-let [support-user (support-access-grants.db/user-by-email (sag.settings/support-access-grant-email))](revoke-support-user-access! (:id support-user) revoked-at)))))diff --git a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.cljindex ac359190da6..b2fef0910bc 100644--- a/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj+++ b/enterprise/backend/src/metabase_enterprise/support_access_grants/provider.clj@@ -6,6 +6,7 @@end time and automatically set the user's password to expire when the grant expires."(:require[java-time.api :as t]+ [metabase-enterprise.support-access-grants.db :as support-access-grants.db][metabase-enterprise.support-access-grants.schema :as schema][metabase.auth-identity.core :as auth-identity][metabase.util :as u]@@ -71,16 +72,16 @@{:status-code 400})))(u/prog1 (auth-identity/generate-reset-token user-id)(t2/with-transaction [_]- (let [user (t2/select-one :model/User user-id)+ (let [user (support-access-grants.db/user user-id)auth-identity {:user_id user-id:provider "support-access-grant":provider_id (:email user):expires_at grant-ends-at:credentials (create-support-access-reset-token-credentials <> grant-ends-at):metadata (auth-identity/create-reset-token-metadata (:email user))}]- (if-let [auth-identity-id (t2/select-one-pk :model/AuthIdentity :user_id user-id :provider "support-access-grant")]- (t2/update! :model/AuthIdentity auth-identity-id auth-identity)- (t2/insert! :model/AuthIdentity auth-identity)))))))+ (if-let [auth-identity-id (support-access-grants.db/support-access-auth-identity-id user-id)]+ (support-access-grants.db/update-auth-identity! auth-identity-id auth-identity)+ (support-access-grants.db/insert-auth-identity! auth-identity)))))));;; -------------------------------------------------- Provider Registration --------------------------------------------------@@ -104,6 +105,6 @@(log/infof "Setting password expiration for user %s to %s based on support access grant"(:id user) grant-ends-at)(t2/with-transaction [_]- (t2/update! :model/AuthIdentity (:id auth-identity) (auth-identity/mark-token-consumed auth-identity))+ (support-access-grants.db/update-auth-identity! (:id auth-identity) (auth-identity/mark-token-consumed auth-identity))(auth-identity/set-password! (:id user) password {:expires-at grant-ends-at}))))result)diff --git a/enterprise/backend/src/metabase_enterprise/tenants/api.clj b/enterprise/backend/src/metabase_enterprise/tenants/api.cljindex c02a750a743..fa1c4e0a9c1 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/api.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/api.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.tenants.api(:require[malli.util]+ [metabase-enterprise.tenants.db :as tenants.db][metabase-enterprise.tenants.models :as tenant][metabase.api.common :as api][metabase.api.macros :as api.macros]@@ -49,7 +50,7 @@(api/check-403 api/*is-superuser?*)(api/check-400 (not (tenant/tenant-exists? tenant))"This tenant name or slug is already taken.")- (let [new-tenant (t2/insert-returning-instance! :model/Tenant tenant)]+ (let [new-tenant (tenants.db/insert-tenant! tenant)](events/publish-event! :event/tenant-create {:object new-tenant})(present-tenant new-tenant)))@@ -68,12 +69,9 @@_](api/check-403 (or api/*is-superuser?* (not (:tenant_id @api/*current-user*)))){:data (present-tenants- (t2/select :model/Tenant (cond-> {:order-by [[:id :asc]]}- (request/paged?) (assoc :limit (request/limit) :offset (request/offset))- true (assoc :where (case status- "all" [:= [:inline 1] [:inline 1]]- "active" [:= :is_active true]- "deactivated" [:= :is_active false])))))})+ (tenants.db/tenants-page status+ (when (request/paged?) (request/limit))+ (when (request/paged?) (request/offset))))})(def ^:private UpdateTenantArguments[:map {:closed true}@@ -87,22 +85,16 @@{:keys [is_active] :as tenant} :- UpdateTenantArguments](t2/with-transaction [_cn](collection/with-allow-modifying-tenant-root-collections- (let [tenant-before-update (t2/select-one :model/Tenant tenant-id)- _ (t2/update! :model/Tenant {:id tenant-id} tenant)- tenant-after-update (t2/select-one :model/Tenant tenant-id)]+ (let [tenant-before-update (tenants.db/tenant tenant-id)+ _ (tenants.db/update-tenant! tenant-id tenant)+ tenant-after-update (tenants.db/tenant tenant-id)](when (false? is_active)- (t2/update! :model/User {:is_active true :tenant_id tenant-id}- {:is_active false :deactivated_with_tenant true})- (some-> (t2/select-one :model/Collection- :id (:tenant_collection_id tenant-before-update)- :archived false)+ (tenants.db/deactivate-tenant-users! tenant-id)+ (some-> (tenants.db/collection-with-archived-state (:tenant_collection_id tenant-before-update) false)collection/archive-collection!))(when (true? is_active)- (t2/update! :model/User {:is_active false :tenant_id tenant-id :deactivated_with_tenant true}- {:is_active true :deactivated_with_tenant nil})- (some-> (t2/select-one :model/Collection- :id (:tenant_collection_id tenant-before-update)- :archived true)+ (tenants.db/reactivate-tenant-users! tenant-id)+ (some-> (tenants.db/collection-with-archived-state (:tenant_collection_id tenant-before-update) true)(collection/unarchive-collection! {})))(events/publish-event! :event/tenant-update {:object tenant-after-update:previous-object tenant-before-update})@@ -115,7 +107,7 @@tenant :- UpdateTenantArguments](api/check-403 api/*is-superuser?*)(when (:name tenant)- (api/check-400 (not (t2/exists? :model/Tenant :name (:name tenant) :id [:not= id]))+ (api/check-400 (not (tenants.db/other-tenant-named? (:name tenant) id))"This name is already taken."))(present-tenant (update-tenant! id tenant)))@@ -123,7 +115,7 @@"Get info about a tenant"[{id :id} :- [:map {:closed true} [:id ms/PositiveInt]]](api/check-403 (or api/*is-superuser?* (not (:tenant_id @api/*current-user*))))- (present-tenant (t2/select-one :model/Tenant :id id)))+ (present-tenant (tenants.db/tenant id)))(def ^{:arglists '([request respond raise])} routes"`/api/ee/tenant` routes"diff --git a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.cljindex b1eb7c14307..424610468a6 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/auth_provider.clj@@ -1,12 +1,12 @@(ns metabase-enterprise.tenants.auth-provider(:require[metabase-enterprise.tenants.api :as api.tenants]+ [metabase-enterprise.tenants.db :as tenants.db][metabase.auth-identity.core :as auth-identity][metabase.request.core :as request][metabase.settings.core :as setting][metabase.util :as u]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(defn- validate-user-and-tenant-slug![{:keys [tenant_id] :as user} existing-tenant user-will-have-tenant?]@@ -27,14 +27,14 @@user-has-tenant?)(throw (ex-info "Tenant claim required for external user"{:user/tenant-id tenant_id- :user/tenant-slug (t2/select-one-fn :slug :model/Tenant :id tenant_id)+ :user/tenant-slug (tenants.db/tenant-slug tenant_id):status-code 403}))(and user-exists?(not= tenant_id (u/id existing-tenant)))(throw (ex-info "Tenant ID mismatch with existing user"{:user/tenant-id tenant_id- :user/tenant-slug (t2/select-one-fn :slug :model/Tenant :id tenant_id)+ :user/tenant-slug (tenants.db/tenant-slug tenant_id):tenant-slug/tenant-id (:id existing-tenant):tenant-slug/slug (:slug existing-tenant):status-code 403})))))@@ -91,7 +91,7 @@(methodical/defmethod auth-identity/login! ::create-tenant-if-not-exists[provider {:keys [tenant-slug] :as request}]- (let [existing-tenant (when tenant-slug (t2/select-one :model/Tenant :slug tenant-slug))]+ (let [existing-tenant (when tenant-slug (tenants.db/tenant-by-slug tenant-slug))](next-method provider (create-tenant-if-not-exists! request existing-tenant))))(methodical/prefer-method! #'auth-identity/login! :metabase.auth-identity.provider/provider ::create-tenant-if-not-exists)diff --git a/enterprise/backend/src/metabase_enterprise/tenants/core.clj b/enterprise/backend/src/metabase_enterprise/tenants/core.cljindex f955d918a1d..21504b27a01 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/core.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/core.clj@@ -2,11 +2,11 @@(:require[metabase-enterprise.tenants.api :as tenants.api][metabase-enterprise.tenants.auth-provider]+ [metabase-enterprise.tenants.db :as tenants.db][metabase.api.common :as api][metabase.collections.models.collection :as collection][metabase.permissions.core :as perms]- [metabase.premium-features.core :refer [defenterprise]]- [toucan2.core :as t2]))+ [metabase.premium-features.core :refer [defenterprise]]))(defenterprise login-attributes"EE version of `login-attributes` - a map of tenant attributes that should be merged into the user's login@@ -14,7 +14,7 @@:feature :tenants[{:keys [tenant_id] :as _user}](or (when (and (perms/use-tenants) tenant_id)- (when-let [{:keys [slug attributes]} (t2/select-one :model/Tenant tenant_id)]+ (when-let [{:keys [slug attributes]} (tenants.db/tenant tenant_id)](merge attributes {"@tenant.slug" slug}))){}))@@ -27,10 +27,7 @@(comp(mapcat keys)(distinct))- (t2/select-fn-reducible :attributes [:model/Tenant :attributes]- {:where [:and- [:not= :attributes nil]- [:not= :attributes "{}"]]}))+ (tenants.db/tenant-attributes-reducible))#{}))(defenterprise tenant-is-active?@@ -38,7 +35,7 @@:feature :tenants[tenant-id](or (nil? tenant-id)- (t2/exists? :model/Tenant :id tenant-id :is_active true)))+ (tenants.db/active-tenant-exists? tenant-id)))(defenterprise create-tenant!"Creates a tenant"@@ -51,7 +48,7 @@:feature :tenants[user](when-let [tenant-id (:tenant_id user)]- (t2/select-one :model/Tenant :id tenant-id)))+ (tenants.db/tenant tenant-id)))(defenterprise validate-new-tenant-collection!"Throws API exceptions if the passed collection is an invalid tenant collection."diff --git a/enterprise/backend/src/metabase_enterprise/tenants/db.clj b/enterprise/backend/src/metabase_enterprise/tenants/db.cljnew file mode 100644index 00000000000..199ac216cc6--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/tenants/db.clj@@ -0,0 +1,124 @@+(ns metabase-enterprise.tenants.db+ "Application database queries for the tenants module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods, and transactions."+ (:require+ [toucan2.core :as t2]))++(defn tenant+ "The Tenant with `tenant-id`, or nil."+ [tenant-id]+ (t2/select-one :model/Tenant :id tenant-id))++(defn tenant-by-slug+ "The Tenant with `slug`, or nil."+ [slug]+ (t2/select-one :model/Tenant :slug slug))++(defn tenant-slug+ "The slug of the Tenant with `tenant-id`."+ [tenant-id]+ (t2/select-one-fn :slug :model/Tenant :id tenant-id))++(defn tenant-collection-id+ "The root Collection ID of the Tenant with `tenant-id`."+ [tenant-id]+ (t2/select-one-fn :tenant_collection_id :model/Tenant :id tenant-id))++(defn tenants-page+ "The Tenants in ID order, restricted by `status` (`\"all\"`, `\"active\"`, or `\"deactivated\"`) and paged by the+ optional `limit` and `offset`."+ [status limit offset]+ (t2/select :model/Tenant (cond-> {:order-by [[:id :asc]]+ :where (case status+ "all" [:= [:inline 1] [:inline 1]]+ "active" [:= :is_active true]+ "deactivated" [:= :is_active false])}+ limit (assoc :limit limit :offset offset))))++(defn tenant-attributes-reducible+ "Reducible attribute maps of the Tenants that have attributes."+ []+ (t2/select-fn-reducible :attributes [:model/Tenant :attributes]+ {:where [:and+ [:not= :attributes nil]+ [:not= :attributes "{}"]]}))++(defn tenant-names-and-ids-by-collection+ "A map of root Collection ID to `[name id]` for the Tenants owning `collection-ids`."+ [collection-ids]+ (t2/select-fn->fn :tenant_collection_id (juxt :name :id) :model/Tenant :tenant_collection_id [:in collection-ids]))++(defn active-tenant-exists?+ "Whether the Tenant with `tenant-id` exists and is active."+ [tenant-id]+ (t2/exists? :model/Tenant :id tenant-id :is_active true))++(defn tenant-name-or-slug-exists?+ "Whether a Tenant named `tenant-name` or with `slug` exists."+ [tenant-name slug]+ (t2/exists? :model/Tenant {:where [:or+ [:= :slug slug]+ [:= :name tenant-name]]}))++(defn other-tenant-named?+ "Whether a Tenant other than `tenant-id` is named `tenant-name`."+ [tenant-name tenant-id]+ (t2/exists? :model/Tenant :name tenant-name :id [:not= tenant-id]))++(defn insert-tenant!+ "Insert `tenant` and return the new instance."+ [tenant]+ (t2/insert-returning-instance! :model/Tenant tenant))++(defn update-tenant!+ "Apply `changes` to the Tenant with `tenant-id`."+ [tenant-id changes]+ (t2/update! :model/Tenant {:id tenant-id} changes))++(defn active-member-counts+ "Rows of `:tenant_id` and `:count` of active personal Users for `tenant-ids`."+ [tenant-ids]+ (t2/query {:select [[:tenant_id] [[:count :*] :count]]+ :from [(t2/table-name :model/User)]+ :where [:and+ [:in :tenant_id tenant-ids]+ [:= :type "personal"]+ :is_active]+ :group-by [:tenant_id]}))++(defn deactivate-tenant-users!+ "Deactivate the active Users of the Tenant with `tenant-id`, marking them as deactivated with it."+ [tenant-id]+ (t2/update! :model/User {:is_active true :tenant_id tenant-id} {:is_active false :deactivated_with_tenant true}))++(defn reactivate-tenant-users!+ "Reactivate the Users of the Tenant with `tenant-id` that were deactivated with it."+ [tenant-id]+ (t2/update! :model/User {:is_active false :tenant_id tenant-id :deactivated_with_tenant true}+ {:is_active true :deactivated_with_tenant nil}))++(defn user-tenant-id+ "The Tenant ID of the User with `user-id`."+ [user-id]+ (t2/select-one-fn :tenant_id :model/User :id user-id))++(defn collection-with-archived-state+ "The Collection with `collection-id` if its archived flag is `archived?`, or nil."+ [collection-id archived?]+ (t2/select-one :model/Collection :id collection-id :archived archived?))++(defn descendant-collection-ids+ "The IDs of the Collections under the Collection with `collection-id`."+ [collection-id]+ (t2/select-pks-set :model/Collection :location [:like (str "/" collection-id "/%")]))++(defn insert-collection!+ "Insert `collection` and return its ID."+ [collection]+ (t2/insert-returning-pk! :model/Collection collection))++(defn delete-permissions-with-objects!+ "Delete the Permissions rows for `objects`."+ [objects]+ (t2/query-one {:delete-from :permissions+ :where [:in :object objects]}))diff --git a/enterprise/backend/src/metabase_enterprise/tenants/models.clj b/enterprise/backend/src/metabase_enterprise/tenants/models.cljindex b5a23411e25..2e625c1f227 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/models.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/models.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.tenants.models(:require+ [metabase-enterprise.tenants.db :as tenants.db][metabase.api.common :as api][metabase.audit-app.core :as audit-app][metabase.collections.models.collection :as collection]@@ -28,9 +29,9 @@(t2/define-before-insert :model/Tenant[tenant]- (let [tenant-collection-id (t2/insert-returning-pk! :model/Collection {:type collection/tenant-specific-root-collection-type- :name (format "Tenant Collection: %s" (:name tenant))- :namespace "tenant-specific"})]+ (let [tenant-collection-id (tenants.db/insert-collection! {:type collection/tenant-specific-root-collection-type+ :name (format "Tenant Collection: %s" (:name tenant))+ :namespace "tenant-specific"})](u/prog1 (assoc tenant :tenant_collection_id tenant-collection-id);; The API layer is responsible for doing validation with nice error messages, here we just throw as a final layer;; of defense.@@ -39,9 +40,7 @@(defn tenant-exists?"Given a tenant name, returns truthy if the name (or its slugified version) is already reserved."[{n :name slug :slug}]- (t2/exists? :model/Tenant {:where [:or- [:= :slug slug]- [:= :name n]]}))+ (tenants.db/tenant-name-or-slug-exists? n slug))(doto :model/Tenant(derive :metabase/model)@@ -52,13 +51,7 @@(mi/instances-with-hydrated-datatenants k(fn []- (->> (t2/query {:select [[:tenant_id] [[:count :*] :count]]- :from [(t2/table-name :model/User)]- :where [:and- [:in :tenant_id (map u/the-id tenants)]- [:= :type "personal"]- :is_active]- :group-by [:tenant_id]})+ (->> (tenants.db/active-member-counts (map u/the-id tenants))(map (juxt :tenant_id :count))(into {}))):id@@ -94,11 +87,9 @@:feature :tenants[user-or-id](into []- (when-let [tenant-id (t2/select-one-fn :tenant_id :model/User :id (u/the-id user-or-id))]- (when-let [tenant-collection-id (t2/select-one-fn :tenant_collection_id :model/Tenant :id tenant-id)]- (let [descendant-ids (t2/select-pks-set :model/Collection- :location- [:like (str "/" tenant-collection-id "/%")])]+ (when-let [tenant-id (tenants.db/user-tenant-id (u/the-id user-or-id))]+ (when-let [tenant-collection-id (tenants.db/tenant-collection-id tenant-id)]+ (let [descendant-ids (tenants.db/descendant-collection-ids tenant-collection-id)](conj descendant-ids tenant-collection-id))))))(defenterprise maybe-localize-tenant-collection-names@@ -111,9 +102,7 @@collections)collection-id->tenant-name-and-id(when (seq tenant-collection-ids)- (t2/select-fn->fn :tenant_collection_id (juxt :name :id)- :model/Tenant- :tenant_collection_id [:in tenant-collection-ids]))]+ (tenants.db/tenant-names-and-ids-by-collection tenant-collection-ids))](mapv (fn [{ttype :type id :id :as coll}](cond-> coll(= ttype collection/tenant-specific-root-collection-type)diff --git a/enterprise/backend/src/metabase_enterprise/tenants/permissions.clj b/enterprise/backend/src/metabase_enterprise/tenants/permissions.cljindex 9a44f519304..7b050d2052c 100644--- a/enterprise/backend/src/metabase_enterprise/tenants/permissions.clj+++ b/enterprise/backend/src/metabase_enterprise/tenants/permissions.clj@@ -1,12 +1,12 @@(ns metabase-enterprise.tenants.permissions"Enterprise implementation of tenant-specific collection permissions management."(:require+ [metabase-enterprise.tenants.db :as tenants.db][metabase.collections.models.collection :as collection][metabase.permissions.core :as perms][metabase.premium-features.core :refer [defenterprise]][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(mu/defn- revoke-perms-when-moving-into-tenant-specific!"When moving a `collection` that is *not* in the tenant-specific namespace into the tenant-specific namespace@@ -15,11 +15,10 @@This needs to be done recursively for all descendants as well."[collection :- (ms/InstanceOf :model/Collection)]- (t2/query-one {:delete-from :permissions- :where [:in :object (for [coll (cons collection (collection/descendants collection))- path-fn [perms/collection-read-path- perms/collection-readwrite-path]]- (path-fn coll))]}))+ (tenants.db/delete-permissions-with-objects! (for [coll (cons collection (collection/descendants collection))+ path-fn [perms/collection-read-path+ perms/collection-readwrite-path]]+ (path-fn coll))))(mu/defn- grant-perms-when-moving-out-of-tenant-specific!"When moving a descendant of a tenant-specific Collection into a regular Collection namespace, we need to grant itdiff --git a/enterprise/backend/src/metabase_enterprise/transforms/core.clj b/enterprise/backend/src/metabase_enterprise/transforms/core.cljindex af43f09920a..634b8532bb2 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/core.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/core.clj@@ -7,10 +7,10 @@But we need a 'real' module, because all tests must belong to a module."(:require[java-time.api :as t]+ [metabase-enterprise.transforms.db :as transforms.db][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.util.json :as json]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(defenterprise persist-table-dependencies!"Best-effort write-back of `:uncached` deps from `transform-ordering` into the@@ -19,7 +19,7 @@[id->raw-deps](doseq [[id raw-deps] id->raw-deps](try- (t2/update! (t2/table-name :model/Transform) id {:table_dependencies (json/encode (vec raw-deps))})+ (transforms.db/cache-table-dependencies! id (json/encode (vec raw-deps)))(catch Throwable e(log/warnf "Failed to cache table-dependencies for transform %s: %s" id (ex-message e))))))@@ -56,12 +56,7 @@yesterday-utc (t/minus today-utc (t/days 1))counts-for (fn [date](into {} (map (juxt :metered_as :cnt))- (t2/query {:select [:r.metered_as [[:count :r.id] :cnt]]- :from [[:transform_run :r]]- :where [:and- [:= :r.status "succeeded"]- [:= [:cast :r.end_time :date] [:cast date :date]]]- :group-by [:r.metered_as]})))+ (transforms.db/succeeded-run-counts-by-meter date)))yesterday (counts-for yesterday-utc)today (counts-for today-utc)]{:transform-basic-runs (get yesterday "transform-basic" 0)diff --git a/enterprise/backend/src/metabase_enterprise/transforms/db.clj b/enterprise/backend/src/metabase_enterprise/transforms/db.cljnew file mode 100644index 00000000000..c715e7e8f79--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/transforms/db.clj@@ -0,0 +1,20 @@+(ns metabase-enterprise.transforms.db+ "Application database queries for the transforms module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn cache-table-dependencies!+ "Store `dependencies-json` as the cached table dependencies of the Transform with `transform-id`."+ [transform-id dependencies-json]+ (t2/update! (t2/table-name :model/Transform) transform-id {:table_dependencies dependencies-json}))++(defn succeeded-run-counts-by-meter+ "Rows of `:metered_as` and `:cnt` of the TransformRuns that succeeded on `date`."+ [date]+ (t2/query {:select [:r.metered_as [[:count :r.id] :cnt]]+ :from [[:transform_run :r]]+ :where [:and+ [:= :r.status "succeeded"]+ [:= [:cast :r.end_time :date] [:cast date :date]]]+ :group-by [:r.metered_as]}))diff --git a/enterprise/backend/src/metabase_enterprise/transforms_inspector/context.clj b/enterprise/backend/src/metabase_enterprise/transforms_inspector/context.cljindex a1b870931e6..c1003c55f0f 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_inspector/context.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_inspector/context.clj@@ -3,6 +3,7 @@(:require[clojure.set :as set][clojure.string :as str]+ [metabase-enterprise.transforms-inspector.db :as transforms-inspector.db][metabase-enterprise.transforms-inspector.query-analysis :as query-analysis][metabase-enterprise.transforms-inspector.schema :as transforms-inspector.schema][metabase.driver :as driver]@@ -13,8 +14,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(set! *warn-on-reflection* true)@@ -24,7 +24,7 @@"Fetch tables by ID and build source info maps."[table-ids](when (seq table-ids)- (t2/select [:model/Table [:id :table-id] [:name :table-name] :schema [:db_id :db-id]] :id [:in table-ids])))+ (transforms-inspector.db/table-source-rows table-ids)))(defmulti extract-sources"Extract source table information for a transform.@@ -51,7 +51,7 @@transforms-base.u/massage-sql-queryqp.preprocess/preprocess)db-id (transforms-base.u/transform-source-database transform)- driver (t2/select-one-fn (comp keyword :engine) :model/Database :id db-id)+ driver (keyword (transforms-inspector.db/database-engine db-id))deps (driver/native-query-deps driver query)table-ids (keep :table deps)](table-ids->source-info table-ids))@@ -107,7 +107,7 @@(mu/defn- collect-field-metadata :- [:sequential ::transforms-inspector.schema/field]"Collect metadata for fields in a table."[table-id]- (let [fields (t2/select :model/Field :table_id table-id :active true)]+ (let [fields (transforms-inspector.db/active-fields-for-table table-id)](mapv (fn [field](cond-> (select-keys field [:id :name :display_name :base_type :semantic_type])(get-field-stats field)@@ -269,7 +269,7 @@:target target-info:db-id db-id:driver (or (:driver query-info)- (t2/select-one-fn (comp keyword :engine) :model/Database :id db-id))+ (keyword (transforms-inspector.db/database-engine db-id))):from-table-id (:from-table-id query-info):has-joins? (boolean (seq join-structure)):visited-fields (:visited-fields query-info)diff --git a/enterprise/backend/src/metabase_enterprise/transforms_inspector/db.clj b/enterprise/backend/src/metabase_enterprise/transforms_inspector/db.cljnew file mode 100644index 00000000000..a878f8b1ace--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/transforms_inspector/db.clj@@ -0,0 +1,20 @@+(ns metabase-enterprise.transforms-inspector.db+ "Application database queries for the transforms-inspector module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn table-source-rows+ "The ID, name, schema, and Database ID of the Tables with `table-ids`, as source info."+ [table-ids]+ (t2/select [:model/Table [:id :table-id] [:name :table-name] :schema [:db_id :db-id]] :id [:in table-ids]))++(defn database-engine+ "The engine of the Database with `database-id`."+ [database-id]+ (t2/select-one-fn :engine :model/Database :id database-id))++(defn active-fields-for-table+ "The active Fields of the Table with `table-id`."+ [table-id]+ (t2/select :model/Field :table_id table-id :active true))diff --git a/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj b/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.cljindex 0b077850669..56d46f840fc 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_inspector/query_analysis.clj@@ -12,6 +12,7 @@;; TODO (Bronsa 16/02/26): get rid of macaw[macaw.ast :as macaw.ast][macaw.core :as macaw]+ [metabase-enterprise.transforms-inspector.db :as transforms-inspector.db][metabase.driver :as driver][metabase.driver.sql.normalize :as sql.normalize][metabase.lib.core :as lib]@@ -20,8 +21,7 @@[metabase.transforms-base.util :as transforms-base.u][metabase.util :as u][metabase.util.honey-sql-2 :as h2x]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -216,7 +216,7 @@qp.preprocess/preprocess)sql (lib/raw-native-query native-query)db-id (transforms-base.u/transform-source-database transform)- driver (t2/select-one-fn (comp keyword :engine) :model/Database :id db-id)+ driver (keyword (transforms-inspector.db/database-engine db-id))parsed (macaw-parsed-query sql driver)ast (macaw.ast/->ast parsed {:with-instance? false})](when (and ast (= (:type ast) :macaw.ast/select))diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/api.cljindex fcc1e3de4a1..5748034fec9 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/api.clj@@ -1,6 +1,7 @@(ns metabase-enterprise.transforms-python.api(:require[clojure.string :as str]+ [metabase-enterprise.transforms-python.db :as transforms-python.db][metabase-enterprise.transforms-python.models.python-library :as python-library][metabase-enterprise.transforms-python.python-runner :as python-runner][metabase-enterprise.transforms-python.settings :as transforms-python.settings]@@ -12,8 +13,7 @@[metabase.permissions.core :as perms][metabase.transforms-base.util :as transforms-base.u][metabase.util.i18n :as i18n]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(defn get-python-library-by-path"Get Python library details by path for use by other APIs."@@ -69,7 +69,7 @@[:output_row_limit {:optional true} [:and :int [:> 1] [:<= 100]]][:per_input_row_limit {:optional true} [:and :int [:> 1] [:<= 100]]]]](let [table-ids (map :table_id source_tables)- db-ids (t2/select-fn-set :db_id [:model/Table :db_id] :id [:in table-ids])]+ db-ids (transforms-python.db/table-database-ids table-ids)](api/check-400 (= (count db-ids) 1) (i18n/deferred-tru "All source tables must belong to the same database."))(api/check-403 (perms/has-db-transforms-permission? api/*current-user-id* (first db-ids)))(doseq [table-id table-ids]diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/base.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/base.cljindex fad7e49299e..c92b318db34 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/base.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/base.clj@@ -8,6 +8,7 @@[clojure.core.async :as a][clojure.java.io :as io][clojure.string :as str]+ [metabase-enterprise.transforms-python.db :as transforms-python.db][metabase-enterprise.transforms-python.python-runner :as python-runner][metabase-enterprise.transforms-python.s3 :as s3][metabase-enterprise.transforms-python.settings :as transforms-python.settings]@@ -23,8 +24,7 @@[metabase.util.format :as u.format][metabase.util.i18n :as i18n][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(java.io File)(java.nio.file Files)@@ -360,7 +360,7 @@(when (and cancelled? (cancelled?))(throw (ex-info "Transform cancelled before start" {:status :cancelled})))(let [{:keys [target] transform-id :id} transform- db (t2/select-one :model/Database (:database target))+ db (transforms-python.db/database (:database target));; Use run-id if provided, otherwise generate a temp one for python runnereffective-run-id (or run-id (rand-int Integer/MAX_VALUE))cancel-chan (or cancel-chandiff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/db.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/db.cljnew file mode 100644index 00000000000..b588dc6c6d9--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/db.clj@@ -0,0 +1,56 @@+(ns metabase-enterprise.transforms-python.db+ "Application database queries for the transforms-python module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration methods."+ (:require+ [toucan2.core :as t2]))++(defn table-database-ids+ "The set of Database IDs of the Tables with `table-ids`."+ [table-ids]+ (t2/select-fn-set :db_id [:model/Table :db_id] :id [:in table-ids]))++(defn table-database-id+ "The Database ID of the raw table row with `table-id`."+ [table-id]+ (t2/select-one-fn :db_id (t2/table-name :model/Table) :id table-id))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn database-engine+ "The engine of the Database with `database-id`."+ [database-id]+ (t2/select-one-fn :engine :model/Database database-id))++(defn update-run-message!+ "Set the message of the TransformRun with `run-id`."+ [run-id message]+ (t2/update! :model/TransformRun :id run-id {:message message}))++(defn python-library+ "The PythonLibrary with `library-id`, or nil."+ [library-id]+ (t2/select-one :model/PythonLibrary library-id))++(defn python-library-by-path+ "The PythonLibrary at `path`, or nil."+ [path]+ (t2/select-one :model/PythonLibrary :path path))++(defn library-sources-by-path+ "A map of path to source for every PythonLibrary."+ []+ (t2/select-fn->fn :path :source :model/PythonLibrary))++(defn top-level-fields-metadata+ "The export metadata columns of the active top-level Fields of the Table with `table-id`, in database order."+ [table-id]+ (t2/select [:model/Field :id :name :base_type :effective_type :semantic_type :database_type :database_position]+ :table_id table-id+ :active true+ ;; we are only interested in top-level objects, so filter out nested fields (parent or path)+ :parent_id nil+ :nfc_path nil+ {:order-by [[:database_position :asc]]}))diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.cljindex 57931d51471..cff7726ba2b 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj@@ -3,6 +3,7 @@[clojure.core.async :as a][clojure.string :as str][metabase-enterprise.transforms-python.base :as base]+ [metabase-enterprise.transforms-python.db :as transforms-python.db][metabase-enterprise.transforms-python.python-runner :as python-runner][metabase.app-db.core :as app-db][metabase.driver :as driver]@@ -14,8 +15,7 @@[metabase.transforms.util :as transforms.u][metabase.util.i18n :as i18n][metabase.util.jvm :as u.jvm]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.io Closeable)(java.net SocketException SocketTimeoutException)@@ -26,9 +26,7 @@(defn- save-log-to-transform-run-message!"Saves the content of the log into the transform_run's message field. Lossy, string contains user facing information only."[run-id message-log]- (t2/update! :model/TransformRun- :id run-id- {:message (base/message-log->string message-log)}))+ (transforms-python.db/update-run-message! run-id (base/message-log->string message-log)))(def ^:private ^Duration python-message-loop-sleep-duration(Duration/ofMillis 1000))@@ -107,7 +105,7 @@(try(let [message-log (base/empty-message-log){:keys [target owner_user_id creator_id] transform-id :id} transform- {driver :engine :as db} (t2/select-one :model/Database (transforms-base.i/target-db-id transform))+ {driver :engine :as db} (transforms-python.db/database (transforms-base.i/target-db-id transform))run-user-id (if (and (= run-method :manual) user-id)user-id(or owner_user_id creator_id))diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/models/python_library.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/models/python_library.cljindex 30d29ac2ed0..e8529c101bf 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/models/python_library.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/models/python_library.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.transforms-python.models.python-library(:require+ [metabase-enterprise.transforms-python.db :as transforms-python.db][metabase.api.common :as api][metabase.app-db.core :as app-db][metabase.events.core :as events]@@ -70,7 +71,7 @@[path](let [normalized-path (normalize-path path)](validate-path! normalized-path)- (t2/select-one :model/PythonLibrary :path normalized-path)))+ (transforms-python.db/python-library-by-path normalized-path)))(defn update-python-library-source!"Update the Python library source code. Creates a new record if none exists. Returns the updated library."@@ -80,7 +81,7 @@(let [id (app-db/update-or-insert! :model/PythonLibrary{:path normalized-path}(constantly {:path normalized-path :source source}))]- (t2/select-one :model/PythonLibrary id))))+ (transforms-python.db/python-library id))));;; ------------------------------------------------- Serialization --------------------------------------------------diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.cljindex 93d3c5d95f5..de46a2e34e7 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj@@ -5,6 +5,7 @@[clojure.java.io :as io][clojure.string :as str][medley.core :as m]+ [metabase-enterprise.transforms-python.db :as transforms-python.db][metabase-enterprise.transforms-python.s3 :as s3][metabase-enterprise.transforms-python.settings :as transforms-python.settings][metabase.analytics-interface.core :as analytics]@@ -20,8 +21,7 @@[metabase.util.i18n :as i18n][metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(clojure.lang PersistentQueue)(java.io BufferedWriter File InputStream OutputStream OutputStreamWriter)@@ -230,7 +230,7 @@source-tables)run-timeout-secs (or timeout-secs (transforms-python.settings/python-runner-timeout-seconds))payload {:code code- :library (t2/select-fn->fn :path :source :model/PythonLibrary)+ :library (transforms-python.db/library-sources-by-path):timeout run-timeout-secs:request_id (or request-id run-id):output_url (:url output)@@ -285,18 +285,12 @@(try (.delete file) (catch Exception _)))(defn- fields-metadata [_driver table-id]- (t2/select [:model/Field :id :name :base_type :effective_type :semantic_type :database_type :database_position]- :table_id table-id- :active true- ;; we are only interested in top-level objects, so filter out nested fields (parent or path)- :parent_id nil- :nfc_path nil- {:order-by [[:database_position :asc]]}))+ (transforms-python.db/top-level-fields-metadata table-id))(defn- build-table-query"Build a mbql query for table, might add a proper filter for incremental transforms."[table-id source-incremental-strategy source-range-params limit]- (let [db-id (t2/select-one-fn :db_id (t2/table-name :model/Table) :id table-id)+ (let [db-id (transforms-python.db/table-database-id table-id)metadata-provider (lib-be/application-database-metadata-provider db-id)table-metadata (lib.metadata/table metadata-provider table-id)](cond-> (-> (lib/query metadata-provider table-metadata)@@ -324,8 +318,8 @@(let [tmp-data-file (File/createTempFile data-path "")tmp-meta-file (File/createTempFile manifest-path "")](try- (let [db-id (t2/select-one-fn :db_id (t2/table-name :model/Table) :id table_id)- driver (t2/select-one-fn :engine :model/Database db-id)+ (let [db-id (transforms-python.db/table-database-id table_id)+ driver (transforms-python.db/database-engine db-id)fields-meta (fields-metadata driver table_id)manifest (generate-manifest table_id fields-meta)](transforms.instrumentation/with-stage-timing [run-id [:export :dwh-to-file]]diff --git a/enterprise/backend/src/metabase_enterprise/upload_management/api.clj b/enterprise/backend/src/metabase_enterprise/upload_management/api.cljindex 008e07a12fe..a1d3377f481 100644--- a/enterprise/backend/src/metabase_enterprise/upload_management/api.clj+++ b/enterprise/backend/src/metabase_enterprise/upload_management/api.clj@@ -1,5 +1,6 @@(ns metabase-enterprise.upload-management.api(:require+ [metabase-enterprise.upload-management.db :as upload-management.db][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]@@ -8,16 +9,15 @@[metabase.premium-features.core :as premium-features][metabase.upload.core :as upload][metabase.util.i18n :refer [tru]]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(defn- attached-dwh-tables"Used for adding attached DWH tables to the list of tables visible to the user. In practice these are to managegoogle sheets uploads. Excludes tables with is_upload=true since those are already included in the main query."[](when (premium-features/has-feature? :attached-dwh)- (when-let [dw-db-id (t2/select-one-fn :id :model/Database :is_attached_dwh true)]- (when-let [dw-tables (t2/select :model/Table :db_id dw-db-id :active true :is_upload false)]+ (when-let [dw-db-id (upload-management.db/attached-dwh-database-id)]+ (when-let [dw-tables (upload-management.db/non-upload-tables-for-database dw-db-id)]dw-tables))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -27,7 +27,7 @@(api.macros/defendpoint :get "/tables""Get all `Tables` visible to the current user which were created by uploading a file."[]- (as-> (t2/select :model/Table, :active true, :is_upload true, {:order-by [[:name :asc]]}) tables+ (as-> (upload-management.db/upload-tables) tables;; See https://github.com/metabase/metabase/issues/41023(concat tables (attached-dwh-tables))(map #(update % :schema str) tables)@@ -49,7 +49,7 @@[:archive-cards {:optional true} [:maybe {:default false} ms/BooleanValue]]]](try;; To be idempotent, we do not check whether the table has already been deactivated.- (let [table (api/check-404 (t2/select-one :model/Table id))+ (let [table (api/check-404 (upload-management.db/table id))result (upload/delete-upload! table :archive-cards? archive-cards)]{:status 200:body (= :done result)})diff --git a/enterprise/backend/src/metabase_enterprise/upload_management/db.clj b/enterprise/backend/src/metabase_enterprise/upload_management/db.cljnew file mode 100644index 00000000000..12e9db3bf1c--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/upload_management/db.clj@@ -0,0 +1,25 @@+(ns metabase-enterprise.upload-management.db+ "Application database queries for the upload-management module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn attached-dwh-database-id+ "The ID of the attached data warehouse Database, or nil."+ []+ (t2/select-one-fn :id :model/Database :is_attached_dwh true))++(defn non-upload-tables-for-database+ "The active Tables of the Database with `database-id` that were not uploaded."+ [database-id]+ (t2/select :model/Table :db_id database-id :active true :is_upload false))++(defn upload-tables+ "The active uploaded Tables, ordered by name."+ []+ (t2/select :model/Table :active true :is_upload true {:order-by [[:name :asc]]}))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table table-id))diff --git a/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj b/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.cljindex 2c718ddc3e8..824ae34e9a2 100644--- a/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj+++ b/enterprise/backend/test/metabase_enterprise/cache/task/refresh_cache_configs_test.clj@@ -149,24 +149,24 @@:query {}}](testing "Happy path: we find the query and card ID for a query to rerun"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query) {:card_id card-id})]- (is (= [{:query {} :card-id card-id}]- (t2/select :model/Query (@#'task.cache/scheduled-base-query-to-rerun-honeysql card-id))))))+ (is (= {:query {} :card-id card-id}+ (@#'task.cache/scheduled-base-query-to-rerun card-id)))))(testing "We don't rerun a query execution older than 30 days"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query){:started_at (t/minus (t/offset-date-time) (t/days 31))})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-base-query-to-rerun-honeysql card-id))))))+ (is (nil? (@#'task.cache/scheduled-base-query-to-rerun card-id)))))(testing "We don't rerun a cache refresh query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query) {:context :cache-refresh})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-base-query-to-rerun-honeysql card-id))))))+ (is (nil? (@#'task.cache/scheduled-base-query-to-rerun card-id)))))(testing "We don't rerun an errored query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query) {:error "Error"})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-base-query-to-rerun-honeysql card-id))))))+ (is (nil? (@#'task.cache/scheduled-base-query-to-rerun card-id)))))(testing "We don't rerun a sandboxed query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query) {:is_sandboxed true})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-base-query-to-rerun-honeysql card-id))))))+ (is (nil? (@#'task.cache/scheduled-base-query-to-rerun card-id)))))(testing "We don't rerun a parameterized query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query) {:parameterized true})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-base-query-to-rerun-honeysql card-id)))))))))+ (is (nil? (@#'task.cache/scheduled-base-query-to-rerun card-id))))))))(deftest scheduled-parameterized-queries-to-rerun-edge-cases-test(let [query {:database (mt/id), :type :native, :native {:query "SELECT 1;"}}]@@ -182,52 +182,40 @@:parameterized true:started_at (t/plus rerun-cutoff (t/days 1))})](is (= [{:query {} :card-id card-id}]- (t2/select :model/Query (@#'task.cache/scheduled-parameterized-queries-to-rerun-honeysql- card-id- rerun-cutoff))))))+ (@#'task.cache/scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)))))(testing "We don't rerun a query execution older than the provided cutoff"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query){:card_id card-id:parameterized true:started_at (t/minus rerun-cutoff (t/days 1))})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-parameterized-queries-to-rerun-honeysql- card-id- rerun-cutoff))))))+ (is (= [] (@#'task.cache/scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)))))(testing "We don't rerun a cache refresh query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query){:card_id card-id:parameterized true:started_at (t/minus rerun-cutoff (t/days 1)):context :cache-refresh})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-parameterized-queries-to-rerun-honeysql- card-id- rerun-cutoff))))))+ (is (= [] (@#'task.cache/scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)))))(testing "We don't rerun an errored query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query){:card_id card-id:parameterized true:started_at (t/minus rerun-cutoff (t/days 1)):error "Error"})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-parameterized-queries-to-rerun-honeysql- card-id- rerun-cutoff))))))+ (is (= [] (@#'task.cache/scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)))))(testing "We don't rerun a sandboxed query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query){:card_id card-id:parameterized true:started_at (t/minus rerun-cutoff (t/days 1)):is_sandboxed true})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-parameterized-queries-to-rerun-honeysql- card-id- rerun-cutoff))))))+ (is (= [] (@#'task.cache/scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)))))(testing "We don't rerun a non-parameterized query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query){:card_id card-id:parameterized false:started_at (t/minus rerun-cutoff (t/days 1))})]- (is (= [] (t2/select :model/Query (@#'task.cache/scheduled-parameterized-queries-to-rerun-honeysql- card-id- rerun-cutoff))))))))))+ (is (= [] (@#'task.cache/scheduled-parameterized-queries-to-rerun card-id rerun-cutoff)))))))))(deftest duration-queries-to-rerun-test(mt/with-premium-features #{:cache-granular-controls :cache-preemptive}@@ -324,15 +312,13 @@(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1})](is (= [query-1-rerun-def]- (->> (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] false))+ (->> (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] false)(map #(update % :cache-hash vec)))))(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-2){:card_id card-id-2})](is (= (->> [query-1-rerun-def query-2-rerun-def](sort-by :card-id))- (->> (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1 question-cache-config-2] false))+ (->> (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1 question-cache-config-2] false)(map #(update % :cache-hash vec))(sort-by :card-id)))))))(testing "Cache configs on dashboards"@@ -343,34 +329,29 @@(is (= (->> [(assoc query-1-rerun-def :dashboard-id dashboard-id)(assoc query-2-rerun-def :dashboard-id dashboard-id)](sort-by :card-id))- (->> (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [dashboard-cache-config] false))+ (->> (@#'task.cache/duration-queries-to-rerun-for [dashboard-cache-config] false)(map #(update % :cache-hash vec))(sort-by :card-id)))))))(testing "We don't rerun a query execution older than 30 days"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:started_at (t/minus (t/offset-date-time) (t/days 32))})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] false))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] false)))))(testing "We don't rerun an errored query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:error "Error"})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] false))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] false)))))(testing "We don't rerun a sandboxed query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:is_sandboxed true})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] false))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] false)))))(testing "We don't rerun a parameterized query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:parameterized true})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] false))))))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] false)))))))))(deftest duration-parameterized-queries-to-rerun-edge-cases-test(let [query-1 {:database (mt/id), :type "native", :native {:query "SELECT * FROM x"}}@@ -411,8 +392,7 @@:cache_hit true:parameterized true})](is (= [query-1-rerun-def]- (->> (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] true))+ (->> (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] true)(map #(update % :cache-hash vec)))))(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-2){:card_id card-id-2@@ -420,8 +400,7 @@:parameterized true})](is (= (->> [query-1-rerun-def query-2-rerun-def](sort-by :card-id))- (->> (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1 question-cache-config-2] true))+ (->> (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1 question-cache-config-2] true)(map #(update % :cache-hash vec))(sort-by :card-id)))))))(testing "Cache configs on dashboards"@@ -438,8 +417,7 @@(is (= (->> [(assoc query-1-rerun-def :dashboard-id dashboard-id)(assoc query-2-rerun-def :dashboard-id dashboard-id)](sort-by :card-id))- (->> (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [dashboard-cache-config] true))+ (->> (@#'task.cache/duration-queries-to-rerun-for [dashboard-cache-config] true)(map #(update % :cache-hash vec))(sort-by :card-id)))))))(testing "We don't rerun a query execution older than 30 days"@@ -447,29 +425,25 @@{:card_id card-id-1:cache_hit true:started_at (t/minus (t/offset-date-time) (t/days 32))})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] true))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] true)))))(testing "We don't rerun an errored query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:cache_hit true:error "Error"})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] true))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] true)))))(testing "We don't rerun a sandboxed query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:cache_hit true:is_sandboxed true})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] true))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] true)))))(testing "We don't rerun a non parameterized query execution"(mt/with-temp [:model/QueryExecution {} (merge (query-execution-defaults query-1){:card_id card-id-1:cache_hit true:parameterized false})]- (is (= [] (t2/select :model/Query (@#'task.cache/duration-queries-to-rerun-honeysql- [question-cache-config-1] true))))))))))+ (is (= [] (@#'task.cache/duration-queries-to-rerun-for [question-cache-config-1] true)))))))))(defn- compare-query-results"Compares a normal query result with a query result generated after a preemptive caching job runs, and assertsdiff --git a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.cljindex 207ded48fb7..516c1b090d5 100644--- a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj+++ b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj@@ -4,7 +4,8 @@superuser-only permission gating."(:require[clojure.test :refer :all]- [metabase-enterprise.data-apps.models.data-app :as data-app]+ [metabase-enterprise.data-apps.db :as data-apps.db]+ [metabase-enterprise.data-apps.models.data-app][metabase.api.common :as api][metabase.models.interface :as mi][metabase.test :as mt]@@ -36,15 +37,11 @@(deftest non-blob-selects-exclude-the-bundle-test(mt/with-model-cleanup [:model/DataApp](insert-app! :allowed_hosts ["https://api.example.com"])- (testing "select-one-non-blob returns metadata without the bundle blob"- (let [app (data-app/select-one-non-blob :name "m")]+ (testing "non-blob-data-app-by-slug returns metadata without the bundle blob"+ (let [app (data-apps.db/non-blob-data-app-by-slug "m")](is (not (contains? app :bundle)))(is (= "M" (:display_name app)))- (is (= ["https://api.example.com"] (:allowed_hosts app)))))- (testing "select-non-blob returns a seq of blob-free rows"- (let [apps (data-app/select-non-blob :name "m")]- (is (= 1 (count apps)))- (is (not (contains? (first apps) :bundle)))))))+ (is (= ["https://api.example.com"] (:allowed_hosts app)))))))(deftest allowed-hosts-reads-as-a-vector-never-nil-test(mt/with-model-cleanup [:model/DataApp]diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/models/dependency_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/models/dependency_test.cljindex 47dd34d4808..dcefe1b4346 100644--- a/enterprise/backend/test/metabase_enterprise/dependencies/models/dependency_test.clj+++ b/enterprise/backend/test/metabase_enterprise/dependencies/models/dependency_test.clj@@ -238,21 +238,13 @@(is (= #{[:card id2] [:card id1] [:table (mt/id :orders)]}(set deps)))))(testing "with filter excluding card1, omits card1 and its dependencies"- (let [filter-fn (fn [entity-type-field entity-id-field]- [:and- [:= entity-type-field "card"]- [:in entity-id-field [id2 id3]]])- graph (deps.graph/filtered-graph-dependencies filter-fn)+ (let [graph (deps.graph/filtered-graph-dependencies {:entity-type :card :ids [id2 id3]})deps (graph/transitive graph [[:card id3]])](is (= #{[:card id2]}(set deps))"Should only include card2, not card1 or table")))(testing "with filter excluding card2, breaks the chain"- (let [filter-fn (fn [entity-type-field entity-id-field]- [:and- [:= entity-type-field "card"]- [:in entity-id-field [id1 id3]]])- graph (deps.graph/filtered-graph-dependencies filter-fn)+ (let [graph (deps.graph/filtered-graph-dependencies {:entity-type :card :ids [id1 id3]})deps (graph/transitive graph [[:card id3]])](is (= #{}(set deps))@@ -273,21 +265,13 @@(is (= #{[:card id2] [:card id3]}(set deps)))))(testing "with filter excluding card3, omits card3"- (let [filter-fn (fn [entity-type-field entity-id-field]- [:and- [:= entity-type-field "card"]- [:in entity-id-field [id1 id2]]])- graph (deps.graph/filtered-graph-dependents filter-fn)+ (let [graph (deps.graph/filtered-graph-dependents {:entity-type :card :ids [id1 id2]})deps (graph/transitive graph [[:card id1]])](is (= #{[:card id2]}(set deps))"Should only include card2, not card3")))(testing "with filter excluding card2, breaks the chain"- (let [filter-fn (fn [entity-type-field entity-id-field]- [:and- [:= entity-type-field "card"]- [:in entity-id-field [id1 id3]]])- graph (deps.graph/filtered-graph-dependents filter-fn)+ (let [graph (deps.graph/filtered-graph-dependents {:entity-type :card :ids [id1 id3]})deps (graph/transitive graph [[:card id1]])](is (= #{}(set deps))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.cljindex 583a226d488..920a76e9beb 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj@@ -3,6 +3,7 @@[clojure.set :as set][clojure.test :refer :all][java-time.api :as t]+ [metabase-enterprise.remote-sync.db :as remote-sync.db][metabase-enterprise.remote-sync.spec :as spec][metabase-enterprise.transforms-python.core :as transforms-python][metabase.test :as mt]@@ -65,8 +66,8 @@(testing (str "Spec for " model-key)(let [tracking (:tracking spec)](is (or (contains? tracking :select-fields)- (contains? tracking :hydrate-query))- "tracking should have either :select-fields or :hydrate-query")+ (:hydrate-query? tracking))+ "tracking should have either :select-fields or :hydrate-query? true")(is (map? (:field-mappings tracking))"tracking :field-mappings should be a map"))))))@@ -503,17 +504,17 @@(is (= {:built_in_type nil} (spec/removal-conditions spec))"removal-conditions falls back to :conditions for TransformTag"))))-(deftest removal-condition-clauses-value-shapes-test+(deftest removal-condition-exprs-value-shapes-test(testing "removal conditions render each value shape into a well-formed HoneySQL fragment"(testing "a scalar value renders as [:= k v]"(is (= [[:= :built_in_type nil]]- (spec/removal-where-clauses {:removal-conditions {:built_in_type nil}} #{} []))))+ (#'remote-sync.db/removal-condition-exprs {:built_in_type nil}))))(testing "an :entity_id [op value] pair keeps its operator"(is (= [[:not= :entity_id "builtin-eid"]]- (spec/removal-where-clauses {:removal-conditions {:entity_id [:not= "builtin-eid"]}} #{} []))))+ (#'remote-sync.db/removal-condition-exprs {:entity_id [:not= "builtin-eid"]}))))(testing "a vector value on any other key renders as [:in k v], not a broken scalar [:= k v]"(is (= [[:in :status ["removed" "delete"]]]- (spec/removal-where-clauses {:removal-conditions {:status ["removed" "delete"]}} #{} []))))))+ (#'remote-sync.db/removal-condition-exprs {:status ["removed" "delete"]}))))))(deftest check-eligibility-applies-conditions-uniformly-test(testing ":conditions are enforced for non-:collection eligibility types"@@ -590,10 +591,10 @@(is (= 1 (:count conflict)) "the unsynced snippet is flagged; the synced one is excluded")(is (= ["Local Snippet"] (:names conflict)))))))-(deftest removal-where-clauses-parity-test+(deftest removal-exprs-parity-test(testing "GHY-4019: the deletion-conflict warning is exactly the unsynced subset of what an import removes";; Both the delete path (remove-unsynced!) and the warning build their WHERE from- ;; spec/removal-where-clauses, so they can't diverge. This locks in that relationship: the rows the+ ;; remote-sync.db/removal-exprs, so they can't diverge. This locks in that relationship: the rows the;; predicate removes (absent from the import, in a synced collection) minus the already-synced ones are;; exactly the rows the warning flags.(mt/with-temp [:model/Collection coll {:name "Synced" :is_remote_synced true :location "/"}@@ -606,10 +607,13 @@imported-data {:by-entity-id {"Card" imported-eids}}synced-ids (spec/all-syncable-collection-ids)card-spec (spec/spec-for-model-key :model/Card)+ removal-opts {:scope-key (get-in card-spec [:removal :scope-key])+ :synced-collection-ids synced-ids+ :entity-ids imported-eids+ :removal-conditions (spec/removal-conditions card-spec)};; what remove-unsynced! would delete for Card (its predicate, run as a SELECT rather than a delete)would-delete (t2/select-fn-set :name :model/Card- {:where (into [:and] (spec/removal-where-clauses- card-spec synced-ids imported-eids))})+ {:where (into [:and] (#'remote-sync.db/removal-exprs removal-opts))})flagged (into #{}(comp (filter #(= "Card" (:model %))) (mapcat :names))(spec/check-content-deletion-conflicts imported-data))]diff --git a/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.cljindex 5d9b3b90898..949e5bdb04a 100644--- a/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj+++ b/enterprise/backend/test/metabase_enterprise/snippet_collections/models/native_query_snippet/permissions_test.clj@@ -88,6 +88,13 @@:grant-collection-perms! #(perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll):revoke-collection-perms! #(perms/revoke-collection-permissions! (perms-group/all-users) coll))))))+(deftest nonexistent-snippet-perms-test+ (testing "checking perms for a nonexistent Snippet ID throws instead of silently allowing root-collection access"+ (mt/with-premium-features #{:snippet-collections}+ (mt/with-test-user :rasta+ (is (thrown? Exception (mi/can-read? :model/NativeQuerySnippet Integer/MAX_VALUE)))+ (is (thrown? Exception (mi/can-write? :model/NativeQuerySnippet Integer/MAX_VALUE)))))))+;;; ------------------------------------------- Remote Sync Read-Only Mode Tests -------------------------------------------(deftest remote-sync-read-only-write-perms-testdiff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.cljindex 8e539237ba2..78a22764102 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj@@ -7,6 +7,7 @@[metabase.driver :as driver][metabase.driver-api.core :as driver-api][metabase.driver.bigquery-cloud-sdk.common :as bigquery.common]+ [metabase.driver.bigquery-cloud-sdk.db :as bigquery.db][metabase.driver.bigquery-cloud-sdk.params :as bigquery.params][metabase.driver.bigquery-cloud-sdk.query-processor :as bigquery.qp][metabase.driver.common :as driver.common]@@ -28,10 +29,7 @@[metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.performance :as perf]- ;; sync fix-ups read and write Database/Table/Field rows directly; the metadata provider is read-only- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [metabase.util.performance :as perf])(:import(clojure.lang PersistentList)(com.google.api.gax.rpc FixedHeaderProvider)@@ -763,7 +761,7 @@(defn- ingestion-time-partitioned-table?[table-id]- (t2/exists? :model/Field :table_id table-id :name partitioned-time-field-name :database_partitioned true :active true))+ (bigquery.db/active-partitioned-field-exists? table-id partitioned-time-field-name))(defmethod driver/table-rows-sample :bigquery-cloud-sdk[driver {table-name :name, dataset-id :schema :as table} fields rff opts]@@ -1176,13 +1174,7 @@(log/infof "DB %s had hardcoded dataset-id; changing to an inclusion pattern and updating table schemas"(pr-str db-id))(try- (t2/query-one {:update (t2/table-name :model/Table)- :set {:schema dataset-id}- :where [:and- [:= :db_id db-id]- [:or- [:= :schema nil]- [:not= :schema dataset-id]]]})+ (bigquery.db/set-table-schemas! db-id dataset-id);; if we are upgrading to the sdk driver after having downgraded back to the old driver we end up with;; duplicated tables with nil schema. Happily only in the "dataset-id" schema and not all schemas. But just;; leave them with nil schemas and they will get deactivated in sync.@@ -1191,7 +1183,7 @@(assoc :dataset-filters-type "inclusion")(assoc :dataset-filters-patterns dataset-id)(dissoc :dataset-id))]- (t2/update! :model/Database db-id {:details updated-details})+ (bigquery.db/update-database-details! db-id updated-details)(assoc database :details updated-details))));; TODO: THIS METHOD SHOULD NOT BE UPDATING THE APP-DB (which it does in [convert-dataset-id-to-filters!])@@ -1306,14 +1298,14 @@(let [base (#'driver.sql-jdbc/create-table!-sql driver table-name column-definitions :primary-key primary-key)cluster (clustering-clause indexes)sql (if cluster (str base " " cluster) base)- database (t2/select-one :model/Database database-id)+ database (bigquery.db/database database-id)conn-spec (driver/connection-spec driver database)](driver/execute-raw-queries! driver conn-spec [sql])))(defmethod driver/drop-table! :bigquery-cloud-sdk[driver database-id table-name](let [sql (driver/compile-drop-table driver table-name)- database (t2/select-one :model/Database database-id)+ database (bigquery.db/database database-id)conn-spec (driver/connection-spec driver database)](driver/execute-raw-queries! driver conn-spec [sql])))@@ -1368,7 +1360,7 @@;; update their metadata caches frequently enough for timely transform runs (or interactive previews).;; rather than waiting many minutes, we trade torward consistency by using SQL DML, whose table metadata;; is consistent, and we do not see cached non-existence and things like that causing trouble.- (let [database (t2/select-one :model/Database db-id)+ (let [database (bigquery.db/database db-id)col-kws (perf/mapv (comp keyword name :name) columns)num-cols (count col-kws);; bigquery allows 10k query parameters per requestdiff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.cljindex 33d2dcb61d8..917ffef9138 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/common.clj@@ -1,13 +1,11 @@(ns metabase.driver.bigquery-cloud-sdk.common"Common utility functions and utilities for the bigquery-cloud-sdk driver and related namespaces."(:require+ [metabase.driver.bigquery-cloud-sdk.db :as bigquery.db][metabase.driver.connection :as driver.conn][metabase.util :as u][metabase.util.log :as log]- [metabase.util.malli :as mu]- ;; persists the project-id resolved from credentials back to the Database row; a write, not metadata- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(com.google.auth.oauth2 ServiceAccountCredentials)(java.io ByteArrayInputStream)))@@ -81,7 +79,5 @@"(%s vs %s). The cached project-id-from-credentials uses the read SA's project; ""query qualification may be incorrect for write connections.")(u/the-id database) creds-proj-id write-proj-id))))- (t2/update! :model/Database- (u/the-id database)- {:details (assoc details :project-id-from-credentials creds-proj-id)})+ (bigquery.db/update-database-details! (u/the-id database) (assoc details :project-id-from-credentials creds-proj-id))creds-proj-id))diff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/db.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/db.cljnew file mode 100644index 00000000000..6e706a8f615--- /dev/null+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk/db.clj@@ -0,0 +1,34 @@+(ns metabase.driver.bigquery-cloud-sdk.db+ "Application database queries for the bigquery-cloud-sdk driver. Every function here is a direct Toucan 2 call with+ no additional logic, so the rest of the driver never talks to `toucan2.core` itself."+ (:require+ ;; the driver persists dataset-filter and project-id migrations of its Database details back to the app DB+ ^{:clj-kondo/ignore [:discouraged-namespace]}+ [toucan2.core :as t2]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn update-database-details!+ "Set the details of the Database with `database-id`."+ [database-id details]+ (t2/update! :model/Database database-id {:details details}))++(defn set-table-schemas!+ "Set the schema of the Tables of the Database with `database-id` that do not have `schema` yet, overwriting any+ stale schema they already have."+ [database-id schema]+ (t2/query-one {:update (t2/table-name :model/Table)+ :set {:schema schema}+ :where [:and+ [:= :db_id database-id]+ [:or+ [:= :schema nil]+ [:not= :schema schema]]]}))++(defn active-partitioned-field-exists?+ "Whether the Table with `table-id` has an active database-partitioned Field named `field-name`."+ [table-id field-name]+ (t2/exists? :model/Field :table_id table-id :name field-name :database_partitioned true :active true))diff --git a/src/metabase/actions/actions.clj b/src/metabase/actions/actions.cljindex d05c82fc30a..b052d716ae0 100644--- a/src/metabase/actions/actions.clj+++ b/src/metabase/actions/actions.clj@@ -3,6 +3,7 @@(:require[malli.error :as me][metabase.actions.args :as actions.args]+ [metabase.actions.db :as actions.db][metabase.actions.events :as actions.events][metabase.actions.scope :as actions.scope][metabase.actions.settings :as actions.settings]@@ -22,8 +23,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [methodical.core :as methodical]- [toucan2.core :as t2])+ [methodical.core :as methodical])(:import(clojure.lang ExceptionInfo)))@@ -145,11 +145,7 @@nil)(defn- database-for-action [action-or-id]- (t2/select-one :model/Database {:select [:db.*]- :from :action- :join [[:report_card :card] [:= :card.id :action.model_id]- [:metabase_database :db] [:= :db.id :card.database_id]]- :where [:= :action.id (u/the-id action-or-id)]}))+ (actions.db/database-for-action (u/the-id action-or-id)))(defn check-actions-enabled!"Throws an appropriate error if actions are unsupported or disabled for the database of the action's model,@@ -237,7 +233,7 @@"Uses cache to prevent redundant look-ups with an action call chain."[table-id](assert table-id "Id cannot be nil")- (cached-database (:db_id (cached-value [:table-by-db-ids table-id] #(t2/select-one [:model/Table :db_id] table-id)))))+ (cached-database (cached-value [:table-by-db-ids table-id] #(actions.db/table-database-id table-id))))(mu/defn- check-permissions[policy :- :keyworddiff --git a/src/metabase/actions/args.clj b/src/metabase/actions/args.cljindex ecf00b368a8..caadeabf06f 100644--- a/src/metabase/actions/args.clj+++ b/src/metabase/actions/args.clj@@ -1,13 +1,13 @@(ns ^:instrument/always metabase.actions.args(:require+ [metabase.actions.db :as actions.db];; legacy usage, do not use this in new code^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.normalize :as mbql.normalize][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.parameter :as lib.schema.parameter][metabase.util :as u][metabase.util.log :as log]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(defmulti action-arg-map-schema"Return the appropriate malli schema to use to validate the arg map passed to [[perform-action!*]].@@ -169,6 +169,6 @@(when (seq row-arg)(log/warn ":arg is deprecated, use :row instead"));; TODO it would be nice to use cached-database-via-table-id here, but need to solve circular dependency.- {:database (or database (when table-id (t2/select-one-fn :db_id [:model/Table :db_id] table-id)))+ {:database (or database (when table-id (actions.db/table-database-id table-id))):table-id table-id:row (update-keys (or row row-arg) u/qualified-name)})diff --git a/src/metabase/actions/core.clj b/src/metabase/actions/core.cljindex 95c0d5be859..1b2daff7713 100644--- a/src/metabase/actions/core.clj+++ b/src/metabase/actions/core.clj@@ -57,6 +57,9 @@insert!select-actionselect-actions+ select-actions-for-ids+ select-actions-for-models+ select-actions-non-http-for-modelsupdate!][metabase.actions.eventspublish-action-success!]diff --git a/src/metabase/actions/db.clj b/src/metabase/actions/db.cljnew file mode 100644index 00000000000..eecf2681d7e--- /dev/null+++ b/src/metabase/actions/db.clj@@ -0,0 +1,233 @@+(ns metabase.actions.db+ "Application database queries for the actions module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn database-for-action+ "The Database of the model Card of the Action with `action-id`, or nil."+ [action-id]+ (t2/select-one :model/Database {:select [:db.*]+ :from :action+ :join [[:report_card :card] [:= :card.id :action.model_id]+ [:metabase_database :db] [:= :db.id :card.database_id]]+ :where [:= :action.id action-id]}))++(defn table-database-id+ "The Database id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id [:model/Table :db_id] table-id))++(defn card-query+ "The query of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :dataset_query :model/Card :id card-id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn cards+ "The Cards with `card-ids`."+ [card-ids]+ (t2/select :model/Card :id [:in card-ids]))++(defn cards-by-id+ "A map of Card id to Card for the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn identity :model/Card :id [:in card-ids]))++(defn card-type+ "The type of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :type [:model/Card :type :card_schema] :id card-id))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn dashcard-in-dashboard+ "The DashboardCard with `dashcard-id` on the Dashboard with `dashboard-id`, or nil."+ [dashcard-id dashboard-id]+ (t2/select-one :model/DashboardCard :id dashcard-id :dashboard_id dashboard-id))++(defn dashcard-dashboard-id+ "The `:dashboard_id` of the DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one-fn :dashboard_id [:model/DashboardCard :dashboard_id] dashcard-id))++(defn dashcard-action-id+ "The Action id of the DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one-fn :action_id :model/DashboardCard :id dashcard-id))++(defn delete-dashcards-for-action!+ "Delete the DashboardCards of the Action with `action-id`."+ [action-id]+ (t2/delete! :model/DashboardCard :action_id action-id))++(defn insert-action!+ "Insert the Action `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Action row))++(defn update-action!+ "Apply `changes` to the Action with `action-id`."+ [action-id changes]+ (t2/update! :model/Action action-id changes))++(defn insert-query-action!+ "Insert the QueryAction `action`."+ [action]+ (t2/insert! :model/QueryAction action))++(defn insert-http-action!+ "Insert the HTTPAction `action`."+ [action]+ (t2/insert! :model/HTTPAction action))++(defn insert-implicit-action!+ "Insert the ImplicitAction `action`."+ [action]+ (t2/insert! :model/ImplicitAction action))++(defn update-query-action!+ "Apply `changes` to the QueryAction with `action-id`."+ [action-id changes]+ (t2/update! :model/QueryAction action-id changes))++(defn update-http-action!+ "Apply `changes` to the HTTPAction with `action-id`."+ [action-id changes]+ (t2/update! :model/HTTPAction action-id changes))++(defn update-implicit-action!+ "Apply `changes` to the ImplicitAction with `action-id`."+ [action-id changes]+ (t2/update! :model/ImplicitAction action-id changes))++(defn delete-query-action!+ "Delete the QueryAction of the Action with `action-id`."+ [action-id]+ (t2/delete! :model/QueryAction :action_id action-id))++(defn delete-http-action!+ "Delete the HTTPAction of the Action with `action-id`."+ [action-id]+ (t2/delete! :model/HTTPAction :action_id action-id))++(defn delete-implicit-action!+ "Delete the ImplicitAction of the Action with `action-id`."+ [action-id]+ (t2/delete! :model/ImplicitAction :action_id action-id))++(defn query-actions+ "The QueryActions of the Actions with `action-ids`."+ [action-ids]+ (t2/select :model/QueryAction :action_id [:in action-ids]))++(defn query-action+ "The QueryAction of the Action with `action-id`, or nil."+ [action-id]+ (t2/select-one :model/QueryAction :action_id action-id))++(defn http-actions+ "The HTTPActions of the Actions with `action-ids`."+ [action-ids]+ (t2/select :model/HTTPAction :action_id [:in action-ids]))++(defn implicit-actions+ "The ImplicitActions of the Actions with `action-ids`."+ [action-ids]+ (t2/select :model/ImplicitAction :action_id [:in action-ids]))++(defn actions-with-id+ "The Actions with `action-id` (usually a single Action, since ids are unique)."+ [action-id]+ (t2/select :model/Action :id action-id))++(defn actions-with-ids+ "The Actions whose `:id` is in `action-ids`."+ [action-ids]+ (t2/select :model/Action :id [:in action-ids]))++(defn unarchived-action-with-id+ "The unarchived Actions with `action-id` (usually a single Action, since ids are unique)."+ [action-id]+ (t2/select :model/Action :id action-id :archived false))++(defn action-with-entity-id+ "The Actions with `entity-id` (usually a single Action, since entity ids are unique)."+ [entity-id]+ (t2/select :model/Action :entity_id entity-id))++(defn actions-of-type+ "The Actions of `action-type`."+ [action-type]+ (t2/select :model/Action :type action-type))++(defn unarchived-actions-for-models+ "The unarchived Actions whose `:model_id` is in `model-ids`."+ [model-ids]+ (t2/select :model/Action :model_id [:in model-ids] :archived false))++(defn unarchived-non-http-actions-for-model+ "The unarchived, non-HTTP Actions of the model Card with `model-id`."+ [model-id]+ (t2/select :model/Action :model_id model-id :archived false :type [:not= "http"]))++(defn unarchived-non-http-actions-for-models+ "The unarchived, non-HTTP Actions whose `:model_id` is in `model-ids`."+ [model-ids]+ (t2/select :model/Action :model_id [:in model-ids] :archived false :type [:not= "http"]))++(defn fields-for-parameters+ "The id, base type, display name, and description of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :base_type :display_name :description] :id [:in field-ids]))++(defn action-database-settings+ "The id and Database settings of the Actions with `action-ids`."+ [action-ids]+ (t2/query {:select [:action.id :db.settings]+ :from :action+ :join [[:report_card :card] [:= :card.id :action.model_id]+ [:metabase_database :db] [:= :db.id :card.database_id]]+ :where [:in :action.id action-ids]}))++(defn card-scope-columns+ "The query, Collection id, Database id, and display of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :dataset_query :collection_id :database_id :display] card-id))++(defn dashboard-collection-id+ "The Collection id of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one-fn :collection_id [:model/Dashboard :collection_id] dashboard-id))++(defn destination-database-exists-for-router?+ "Whether the Database with `database-id` has routing destinations."+ [database-id]+ (t2/exists? :model/Database :router_database_id database-id))++(defn writable-table-exists?+ "Whether the Database with `database-id` has a writable Table."+ [database-id]+ (t2/exists? :model/Table :db_id database-id :is_writable true))++(defn table-with-unknown-writability-exists?+ "Whether the Database with `database-id` has a Table whose writability is unknown."+ [database-id]+ (t2/exists? :model/Table :db_id database-id :is_writable nil))diff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.cljindex 5509b58b170..fe95bdf4136 100644--- a/src/metabase/actions/execution.clj+++ b/src/metabase/actions/execution.clj@@ -4,6 +4,7 @@[medley.core :as m][metabase.actions.actions :as actions][metabase.actions.args :as actions.args]+ [metabase.actions.db :as actions.db][metabase.actions.http-action :as http-action][metabase.actions.models :as action][metabase.analytics.core :as analytics]@@ -54,20 +55,20 @@(mu/defn- implicit-action-table[card-id :- ::lib.schema.id/card]- (let [query (t2/select-one-fn :dataset_query :model/Card :id card-id)+ (let [query (actions.db/card-query card-id){:keys [table-id]} (query/query->database-and-table-ids query)]- (t2/hydrate (t2/select-one :model/Table :id table-id) :fields)))+ (t2/hydrate (actions.db/table table-id) :fields)))(defn- execute-custom-action! [action request-parameters](let [{action-type :type} action](actions/check-actions-enabled! action)- (let [model (t2/select-one :model/Card :id (:model_id action))+ (let [model (actions.db/card (:model_id action));; the query executes against its own :database; fall back to the derived column if absentaction-db-id (or (:database (:dataset_query action)) (:database_id action))](when (and (= action-type :query) (not= (:database_id model) action-db-id));; the above check checks the db of the model. We check the db of the query action here(actions/check-actions-enabled-for-database!- (t2/select-one :model/Database :id action-db-id))))+ (actions.db/database action-db-id))))(try(case action-type:query@@ -229,9 +230,7 @@dashcard-id :- ::lib.schema.id/dashcardrequest-parameters :- [:maybe [:map-of :string :any]]opts]- (let [dashcard (api/check-404 (t2/select-one :model/DashboardCard- :id dashcard-id- :dashboard_id dashboard-id))+ (let [dashcard (api/check-404 (actions.db/dashcard-in-dashboard dashcard-id dashboard-id))action (api/check-404 (action/select-action :id (:action_id dashcard)))](analytics/track-event! :snowplow/action{:event :action-executed@@ -250,7 +249,7 @@info {:executed-by api/*current-user-id*:context :action:action-id (:id action)}- card (t2/select-one :model/Card :id (:model_id action))+ card (actions.db/card (:model_id action));; prefilling a form with day old data would be badresult (model-persistence/with-persisted-substituion-disabled(qp/process-querydiff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex 24f36789974..90e252673d3 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -1,6 +1,7 @@(ns metabase.actions.models(:require[medley.core :as m]+ [metabase.actions.db :as actions.db][metabase.actions.schema :as actions.schema][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]@@ -80,12 +81,12 @@[_model k actions](mi/instances-with-hydrated-dataactions k- #(t2/select-pk->fn identity :model/Card :id [:in (map :model_id actions)])+ #(actions.db/cards-by-id (map :model_id actions)):model_id))(defn- check-model-is-not-a-saved-question[model-id]- (when-not (= (t2/select-one-fn :type [:model/Card :type :card_schema] :id model-id) :model)+ (when-not (= (actions.db/card-type model-id) :model)(throw (ex-info (tru "Actions must be made with models, not cards."){:status-code 400}))))@@ -98,29 +99,20 @@[{archived? :archived, id :id, model-id :model_id, :as changes}](u/prog1 (public-sharing/add-public-uuid-prefix-if-changed changes)(if archived?- (t2/delete! :model/DashboardCard :action_id id)+ (actions.db/delete-dashcards-for-action! id)(check-model-is-not-a-saved-question model-id))))(mu/defmethod mi/perms-objects-set :model/Action :- [:set {:min 1} :string][instance :- [:map[:model_id pos-int?]]read-or-write :- [:enum :read :write]]- (mi/perms-objects-set (t2/select-one :model/Card :id (:model_id instance)) read-or-write))+ (mi/perms-objects-set (actions.db/card (:model_id instance)) read-or-write))(def ^:private action-columns"The columns that are common to all Action types."[:archived :created_at :creator_id :description :entity_id :made_public_by_id :model_id :name :parameter_mappings:parameters :public_uuid :public_uuid_prefix :type :updated_at :visualization_settings])-(mu/defn- type->model- "Returns the model from an action type.- `action-type` can be a string or a keyword."- [action-type :- ::actions.schema/type]- (case action-type- :http :model/HTTPAction- :implicit :model/ImplicitAction- :query :model/QueryAction))-;;; ------------------------------------------------ CRUD fns -----------------------------------------------------(defn- query->database-id@@ -150,12 +142,14 @@[action-data :- ::actions.schema/action.for-insert](let [action-data (derive-query-action-database-id action-data)](t2/with-transaction [_conn]- (let [action (first (t2/insert-returning-instances! :model/Action (select-keys action-data action-columns)))- model (type->model (:type action))+ (let [action (actions.db/insert-action! (select-keys action-data action-columns))row (-> (apply dissoc action-data action-columns)(assoc :action_id (:id action))(cond-> (= (:type action) :implicit) (dissoc :database_id)))]- (t2/insert! model row)+ (case (:type action)+ :query (actions.db/insert-query-action! row)+ :http (actions.db/insert-http-action! row)+ :implicit (actions.db/insert-implicit-action! row))(:id action)))))(mu/defn insert! :- ::actions.schema/id@@ -171,18 +165,26 @@(:dataset_query existing-action))](t2/with-transaction [_conn](when-let [action-row (not-empty (select-keys updates action-columns))]- (t2/update! :model/Action id action-row))+ (actions.db/update-action! id action-row))(when-let [type-row (not-empty (cond-> (apply dissoc updates :id action-columns)(= (or (:type updates) (:type existing-action)):implicit)(dissoc :database_id)))]- (let [type-row (assoc type-row :action_id id)- existing-model (type->model (:type existing-action))]+ (let [type-row (assoc type-row :action_id id)](if (and (:type updates) (not= (:type updates) (:type existing-action)))- (let [new-model (type->model (:type updates))]- (t2/delete! existing-model :action_id id)- (t2/insert! new-model (assoc type-row :action_id id)))- (t2/update! existing-model id type-row)))))))+ (do+ (case (:type existing-action)+ :query (actions.db/delete-query-action! id)+ :http (actions.db/delete-http-action! id)+ :implicit (actions.db/delete-implicit-action! id))+ (case (:type updates)+ :query (actions.db/insert-query-action! type-row)+ :http (actions.db/insert-http-action! type-row)+ :implicit (actions.db/insert-implicit-action! type-row)))+ (case (:type existing-action)+ :query (actions.db/update-query-action! id type-row)+ :http (actions.db/update-http-action! id type-row)+ :implicit (actions.db/update-implicit-action! id type-row))))))))(mu/defn update!"Updates an Action and the related type table.@@ -195,14 +197,14 @@(defn- normalize-query-actions [actions](when (seq actions)- (let [query-actions (t2/select :model/QueryAction :action_id [:in (map :id actions)])+ (let [query-actions (actions.db/query-actions (map :id actions))action-id->query-actions (m/index-by :action_id query-actions)](for [action actions](merge action (-> action :id action-id->query-actions (dissoc :action_id)))))))(defn- normalize-http-actions [actions](when (seq actions)- (let [http-actions (t2/select :model/HTTPAction :action_id [:in (map :id actions)])+ (let [http-actions (actions.db/http-actions (map :id actions))http-actions-by-action-id (m/index-by :action_id http-actions)](map (fn [action](let [http-action (get http-actions-by-action-id (:id action))]@@ -215,7 +217,7 @@(defn- normalize-implicit-actions [actions](when (seq actions)- (let [implicit-actions (t2/select :model/ImplicitAction :action_id [:in (map :id actions)])+ (let [implicit-actions (actions.db/implicit-actions (map :id actions))implicit-actions-by-action-id (m/index-by :action_id implicit-actions)](map (fn [action](let [implicit-action (get implicit-actions-by-action-id (:id action))]@@ -223,17 +225,40 @@(select-keys implicit-action [:kind]))))actions))))-(defn- select-actions-without-implicit-params- "Select Actions and fill in sub type information. Don't use this if you need implicit parameters- for implicit actions, use [[select-action]] instead.- `options` is passed to `t2/select` `& options` arg."- [& options]- (let [{:keys [query http implicit]} (group-by :type (apply t2/select :model/Action options))+(defn- select-actions-matching-options+ "Interprets the fixed set of kv-arg shapes [[select-action]]/[[select-actions]] callers use (also a bare id, Toucan's+ primary-key shorthand), and returns the matching Actions."+ [options]+ (if (and (= 1 (count options)) (not (keyword? (first options))))+ (actions.db/actions-with-id (first options))+ (let [opts (apply hash-map options)+ {:keys [id entity_id model_id type archived]} opts]+ (cond+ (contains? opts :id) (if (false? archived)+ (actions.db/unarchived-action-with-id id)+ (actions.db/actions-with-id id))+ (contains? opts :entity_id) (actions.db/action-with-entity-id entity_id)+ (and (contains? opts :model_id) (contains? opts :type))+ (actions.db/unarchived-non-http-actions-for-model model_id)+ (contains? opts :type) (actions.db/actions-of-type type)+ :else (throw (ex-info "Unsupported Action query options" {:options options}))))))++(defn- normalize-actions-by-type+ "Groups `actions` by `:type` and fills in each subtype's sub type information."+ [actions]+ (let [{:keys [query http implicit]} (group-by :type actions)query-actions (normalize-query-actions query)http-actions (normalize-http-actions http)implicit-actions (normalize-implicit-actions implicit)](sort-by :updated_at (concat query-actions http-actions implicit-actions))))+(defn- select-actions-without-implicit-params+ "Select Actions and fill in sub type information. Don't use this if you need implicit parameters+ for implicit actions, use [[select-action]] instead.+ `options` is interpreted by [[select-actions-matching-options]]."+ [& options]+ (normalize-actions-by-type (select-actions-matching-options options)))+(defn unique-field-slugs?"Makes sure that if `coll` is indexed by `index-by`, no keys will be in conflict."[fields]@@ -248,7 +273,7 @@:when table-id][table-id card]))tables (when-let [table-ids (seq (keys card-by-table-id))]- (t2/hydrate (t2/select :model/Table :id [:in table-ids]) :fields))]+ (t2/hydrate (actions.db/tables table-ids) :fields))](into {}(for [table tables:let [fields (:fields table)]@@ -319,25 +344,25 @@(keep ::field-id))implicit-parameters)](when (seq field-ids)- (t2/select-pk->fn (fn [field]- (merge- (select-keys field [:base_type :display_name :description])- {:title (:display_name field)- :placeholder (:display_name field)- ;; these "illegal" camelCase keys are for viz- ;; settings purposes, and that's what the FE uses.- ;; See- ;; https://metaboat.slack.com/archives/C0645JP1W81/p1759981400217489?thread_ts=1759289751.539169&cid=C0645JP1W81- :fieldType (if (isa? (:base_type field) :type/Number) :number :string)- :inputType (condp #(isa? %2 %1) (:base_type field)- :type/Number :number- :type/DateTime :datetime- :type/Time :time- :type/Temporal :date- :type/Boolean :boolean- :string)}))- [:model/Field :id :base_type :display_name :description]- :id [:in field-ids]))))+ (into {}+ (map (juxt :id (fn [field]+ (merge+ (select-keys field [:base_type :display_name :description])+ {:title (:display_name field)+ :placeholder (:display_name field)+ ;; these "illegal" camelCase keys are for viz+ ;; settings purposes, and that's what the FE uses.+ ;; See+ ;; https://metaboat.slack.com/archives/C0645JP1W81/p1759981400217489?thread_ts=1759289751.539169&cid=C0645JP1W81+ :fieldType (if (isa? (:base_type field) :type/Number) :number :string)+ :inputType (condp #(isa? %2 %1) (:base_type field)+ :type/Number :number+ :type/DateTime :datetime+ :type/Time :time+ :type/Temporal :date+ :type/Boolean :boolean+ :string)}))))+ (actions.db/fields-for-parameters field-ids)))))(defn- enrich-viz-settings-fields [viz-fields implicit-params field-id->viz-field](let [param-ids (map :id implicit-params)@@ -373,20 +398,18 @@(:query :http)action))-(mu/defn select-actions :- [:maybe [:sequential ::actions.schema/action]]- "Find actions with given options and generate implicit parameters for execution. Also adds the `:database_id` of the- model for implicit actions.+(defn- enrich-actions-with-implicit-params+ "Fills in implicit parameters for `actions` and adds the `:database_id` of the model for implicit actions.Pass in known-models to save a second Card lookup."- [known-models & options]- (let [actions (apply select-actions-without-implicit-params options)- implicit-action-model-ids (set (map :model_id (filter #(= :implicit (:type %)) actions)))+ [known-models actions]+ (let [implicit-action-model-ids (set (map :model_id (filter #(= :implicit (:type %)) actions)))implicit-action-models (if known-models(->> known-models(filter #(contains? implicit-action-model-ids (:id %)))distinct)(when (seq implicit-action-model-ids)- (t2/select :model/Card :id [:in implicit-action-model-ids])))+ (actions.db/cards implicit-action-model-ids)))model-id->db-id (into {} (for [card implicit-action-models][(:id card) (:database_id card)]))model-id->implicit-parameters (when (seq implicit-action-models)@@ -395,12 +418,43 @@(for [action actions](enrich-action action model-id->db-id model-id->implicit-parameters field-id->viz-field))))+(mu/defn select-actions :- [:maybe [:sequential ::actions.schema/action]]+ "Find actions with given options and generate implicit parameters for execution. Also adds the `:database_id` of the+ model for implicit actions.++ Pass in known-models to save a second Card lookup."+ [known-models & options]+ (enrich-actions-with-implicit-params known-models (apply select-actions-without-implicit-params options)))++(mu/defn select-actions-for-ids :- [:maybe [:sequential ::actions.schema/action]]+ "Find the Actions whose `:id` is in `action-ids`, filling in implicit parameters as [[select-actions]] does.++ Pass in known-models to save a second Card lookup."+ [known-models action-ids]+ (enrich-actions-with-implicit-params known-models (normalize-actions-by-type (actions.db/actions-with-ids action-ids))))++(mu/defn select-actions-for-models :- [:maybe [:sequential ::actions.schema/action]]+ "Find the unarchived Actions whose `:model_id` is in `model-ids`, filling in implicit parameters as+ [[select-actions]] does.++ Pass in known-models to save a second Card lookup."+ [known-models model-ids]+ (enrich-actions-with-implicit-params known-models (normalize-actions-by-type (actions.db/unarchived-actions-for-models model-ids))))++(mu/defn select-actions-non-http-for-models :- [:maybe [:sequential ::actions.schema/action]]+ "Find the unarchived, non-HTTP Actions whose `:model_id` is in `model-ids`, filling in implicit parameters as+ [[select-actions]] does.++ Pass in known-models to save a second Card lookup."+ [known-models model-ids]+ (enrich-actions-with-implicit-params known-models (normalize-actions-by-type (actions.db/unarchived-non-http-actions-for-models model-ids))))+(mu/defn select-action :- [:maybe ::actions.schema/action]"Selects an Action and fills in the subtype data and implicit parameters.- `options` is [[apply]]ed to [[t2/select]]."+ `options` is interpreted by [[select-actions-matching-options]]."[& options]- ;; TODO -- it's dumb that we're calling `t2/select` rather than `t2/select-one` above, limiting like this should never- ;; be done server-side. I don't have time to fix this right now. -- Cam+ ;; TODO -- it's dumb that we're selecting all matches rather than a single one above, limiting like this should+ ;; never be done server-side. I don't have time to fix this right now. -- Cam(first (apply select-actions nil options)))(defn- map-assoc-database-enable-actions@@ -414,11 +468,7 @@:database-enable-actions)))id->database-enable-actions (into {}(map (juxt :id get-database-enable-actions))- (t2/query {:select [:action.id :db.settings]- :from :action- :join [[:report_card :card] [:= :card.id :action.model_id]- [:metabase_database :db] [:= :db.id :card.database_id]]- :where [:in :action.id action-ids]}))]+ (actions.db/action-database-settings action-ids))](map (fn [action](assoc action :database_enabled_actions (get id->database-enable-actions (:id action))))actions)))@@ -429,7 +479,7 @@[_model _k dashcards](let [actions-by-id(when-let [action-ids (seq (keep :action_id dashcards))]- (->> (select-actions nil :id [:in action-ids])+ (->> (select-actions-for-ids nil action-ids)map-assoc-database-enable-actions(m/index-by :id)))](for [dashcard dashcards@@ -440,7 +490,7 @@(defn dashcard->action"Get the action associated with a dashcard if exists, return `nil` otherwise."[dashcard-or-dashcard-id]- (some->> (t2/select-one-fn :action_id :model/DashboardCard :id (u/the-id dashcard-or-dashcard-id))+ (some->> (actions.db/dashcard-action-id (u/the-id dashcard-or-dashcard-id))(select-action :id)));;; ------------------------------------------------ Serialization ---------------------------------------------------@@ -502,7 +552,7 @@(concat(when model_id [[{:model "Card" :id model_id}]])(when (= type :query)- (when-let [{:keys [database_id dataset_query]} (t2/select-one :model/QueryAction :action_id id)]+ (when-let [{:keys [database_id dataset_query]} (actions.db/query-action id)](concat(when database_id [[{:model "Database" :id database_id}]])(serdes/mbql-deps true dataset_query)))))))diff --git a/src/metabase/actions/scope.clj b/src/metabase/actions/scope.cljindex d882443f37e..243c158ecd7 100644--- a/src/metabase/actions/scope.clj+++ b/src/metabase/actions/scope.clj@@ -1,9 +1,9 @@(ns metabase.actions.scope(:require+ [metabase.actions.db :as actions.db][metabase.actions.types :as types][metabase.lib.core :as lib]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]));; TODO Perhaps we will prefer the FE just sending this explicitly instead?;; For now, it is not doing this, so we infer it.@@ -22,13 +22,13 @@(defn- hydrate-from-dashcard [scope](if (and (contains? scope :card-id) (contains? scope :dashboard-id))scope- (let [{:keys [dashboard_id]} (t2/select-one [:model/DashboardCard :dashboard_id] (:dashcard-id scope))]- (merge {:dashboard-id (or dashboard_id missing-id)} scope))))+ (let [dashboard-id (actions.db/dashcard-dashboard-id (:dashcard-id scope))]+ (merge {:dashboard-id (or dashboard-id missing-id)} scope))))(defn- hydrate-from-card [scope card-id](if (and (contains? scope :collection-id) (contains? scope :table-id) (contains? scope :database-id))scope- (let [card (t2/select-one [:model/Card :dataset_query :collection_id :database_id :display] card-id)+ (let [card (actions.db/card-scope-columns card-id)table-id (lib/primary-source-table-id (:dataset_query card))](merge {:table-id table-id:collection-id (:collection_id card missing-id)@@ -40,12 +40,12 @@(:dashcard-id scope) hydrate-from-dashcard(:dashboard-id scope)- (update :collection-id #(or % (t2/select-one-fn :collection_id [:model/Dashboard :collection_id] (:dashboard-id scope)) missing-id))+ (update :collection-id #(or % (actions.db/dashboard-collection-id (:dashboard-id scope)) missing-id))(:model-id scope) (hydrate-from-card (:model-id scope))(:table-id scope)- (update :database-id #(or % (t2/select-one-fn :db_id [:model/Table :db_id] (:table-id scope)) missing-id))))+ (update :database-id #(or % (actions.db/table-database-id (:table-id scope)) missing-id))))(defn- strip-nils"Remove any keys corresponding to nil values from the given map."diff --git a/src/metabase/actions/settings.clj b/src/metabase/actions/settings.cljindex df9a18699ae..e4b5ce30dbe 100644--- a/src/metabase/actions/settings.clj+++ b/src/metabase/actions/settings.clj@@ -1,9 +1,9 @@(ns metabase.actions.settings(:require+ [metabase.actions.db :as actions.db][metabase.settings.core :as setting][metabase.util.i18n :as i18n]- [metabase.warehouses.models.database :as database]- [toucan2.core :as t2]))+ [metabase.warehouses.models.database :as database]))(setting/defsetting database-enable-actions(i18n/deferred-tru "Whether to enable Actions for a specific Database.")@@ -46,13 +46,13 @@:enabled-for-db? (fn [db](setting/custom-disabled-reasons![(when (database/is-destination? db) db-routing-reason)- (when (t2/exists? :model/Database :router_database_id (:id db)) db-routing-reason)+ (when (actions.db/destination-database-exists-for-router? (:id db)) db-routing-reason)(cond;; TODO we also care about re-sync after connection details are changed(= (:initial_sync_status db) "incomplete") busy-sync-reason;; NOTE: we could optimize this into a single query, but the code would be less elegant.- (t2/exists? :model/Table :db_id (:id db) :is_writable true) nil- (t2/exists? :model/Table :db_id (:id db) :is_writable nil) missing-permissions-reason+ (actions.db/writable-table-exists? (:id db)) nil+ (actions.db/table-with-unknown-writability-exists? (:id db)) missing-permissions-reason:else no-writable-tables-reason)])):type :boolean:visibility :publicdiff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.cljindex a47decebbeb..9189e294ccd 100644--- a/src/metabase/actions_rest/api.clj+++ b/src/metabase/actions_rest/api.clj@@ -1,12 +1,12 @@(ns metabase.actions-rest.api"`/api/action/` endpoints."(:require+ [metabase.actions-rest.db :as actions-rest.db][metabase.actions.core :as actions][metabase.actions.schema :as actions.schema][metabase.analytics.core :as analytics][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.collections.models.collection :as collection][metabase.eid-translation.core :as eid-translation][metabase.lib.core :as lib][metabase.lib.schema.id :as lib.schema.id]@@ -37,20 +37,13 @@[:model-id {:optional true} [:maybe ::lib.schema.id/card]]]](letfn [(actions-for [models](if (seq models)- (t2/hydrate (actions/select-actions models- :model_id [:in (map :id models)]- :archived false)- :creator)+ (t2/hydrate (actions/select-actions-for-models models (map :id models)) :creator)[]))];; We don't check the permissions on the actions, we assume they are readable if the model is readable.(let [models (if model-id[(api/read-check :model/Card model-id)]- (t2/select :model/Card {:where- [:and- [:= :type "model"]- [:= :archived false]- ;; action permission keyed off of model permission- (collection/visible-collection-filter-clause)]}))]+ ;; action permission keyed off of model permission+ (actions-rest.db/unarchived-models-visible-to-user))](actions-for models))))(api.macros/defendpoint :get "/public" :- [:sequential ::actions.schema/action]@@ -58,7 +51,7 @@[](perms/check-has-application-permission :setting)(public-sharing.validation/check-public-sharing-enabled)- (t2/select [:model/Action :name :id :public_uuid :model_id], :public_uuid [:not= nil], :archived false))+ (actions-rest.db/public-actions))(api.macros/defendpoint :get "/:action-id" :- ::actions.schema/action"Fetch an Action."@@ -81,7 +74,7 @@{:event :action-deleted:type (:type action):action_id action-id}))- (t2/delete! :model/Action :id action-id)+ (actions-rest.db/delete-action! action-id)api/generic-204-no-content)(api.macros/defendpoint :post "/" :- ::actions.schema/action@@ -108,7 +101,7 @@{:status-code 400})))(doseq [db-id (cond-> [(:database_id model)] database_id (conj database_id))](actions/check-actions-enabled-for-database!- (t2/select-one :model/Database :id db-id))))+ (actions-rest.db/database db-id))))(let [action-id (actions/insert! (assoc action :creator_id api/*current-user-id*))](analytics/track-event! :snowplow/action{:event :action-created@@ -174,9 +167,7 @@(actions/check-actions-enabled! action){:uuid (or (:public_uuid action)(u/prog1 (str (random-uuid))- (t2/update! :model/Action id- {:public_uuid <>- :made_public_by_id api/*current-user-id*})))}))+ (actions-rest.db/set-action-public-uuid! id <> api/*current-user-id*)))}));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;@@ -195,7 +186,7 @@(public-sharing.validation/check-public-sharing-enabled)(api/check-exists? :model/Action :id id, :public_uuid [:not= nil], :archived false)(actions/check-actions-enabled! id)- (t2/update! :model/Action id {:public_uuid nil, :made_public_by_id nil})+ (actions-rest.db/set-action-public-uuid! id nil nil){:status 204, :body nil})(api.macros/defendpoint :post "/:action-id/execute/values" :- [:map-of :string :any]diff --git a/src/metabase/actions_rest/db.clj b/src/metabase/actions_rest/db.cljnew file mode 100644index 00000000000..ebb70b5d018--- /dev/null+++ b/src/metabase/actions_rest/db.clj@@ -0,0 +1,34 @@+(ns metabase.actions-rest.db+ "Application database queries for the actions REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.collections.models.collection :as collection]+ [toucan2.core :as t2]))++(defn unarchived-models-visible-to-user+ "The unarchived model Cards in Collections the current user can read."+ []+ (t2/select :model/Card {:where [:and+ [:= :type "model"]+ [:= :archived false]+ (collection/visible-collection-filter-clause)]}))++(defn public-actions+ "The name, id, public uuid, and model id of the unarchived Actions that are publicly shared."+ []+ (t2/select [:model/Action :name :id :public_uuid :model_id], :public_uuid [:not= nil], :archived false))++(defn delete-action!+ "Delete the Action with `action-id`."+ [action-id]+ (t2/delete! :model/Action :id action-id))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn set-action-public-uuid!+ "Set the public uuid of the Action with `action-id` and the User who made it public."+ [action-id public-uuid made-public-by-id]+ (t2/update! :model/Action action-id {:public_uuid public-uuid, :made_public_by_id made-public-by-id}))diff --git a/src/metabase/activity_feed/api.clj b/src/metabase/activity_feed/api.cljindex 6d506f7b224..34c051db607 100644--- a/src/metabase/activity_feed/api.clj+++ b/src/metabase/activity_feed/api.clj@@ -1,43 +1,21 @@(ns metabase.activity-feed.api(:require- [clojure.string :as str][medley.core :as m]+ [metabase.activity-feed.db :as activity-feed.db][metabase.activity-feed.models.recent-views :as recent-views][metabase.api.common :as api :refer [*current-user-id*]][metabase.api.macros :as api.macros]- [metabase.app-db.core :as app-db][metabase.models.interface :as mi]- [metabase.util.honey-sql-2 :as h2x][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))(defn- models-query[model ids]- (t2/select- (case model- "card" [:model/Card- :id :name :collection_id :description :display- :dataset_query :type :archived :card_schema- :collection.authority_level [:collection.name :collection_name]- [:dashboard.name :dashboard_name] :dashboard_id]- "dashboard" [:model/Dashboard- :id :name :collection_id :description- :archived- :collection.authority_level [:collection.name :collection_name]]- "table" [:model/Table- :id :name :db_id :active- :display_name [:metabase_database.initial_sync_status :initial-sync-status]- [:visibility_type :visibility_type]- [:metabase_database.name :database-name]])- (let [model-symb (symbol (str/capitalize model))- self-qualify #(app-db/qualify model-symb %)]- {:where [:in (self-qualify :id) ids]- :left-join (case model- "table" [:metabase_database [:= :metabase_database.id (self-qualify :db_id)]]- "card" [:collection [:= :collection.id (self-qualify :collection_id)]- [:report_dashboard :dashboard] [:= :dashboard.id (self-qualify :dashboard_id)]]- "dashboard" [:collection [:= :collection.id (self-qualify :collection_id)]])})))+ (case model+ "card" (activity-feed.db/recent-cards ids)+ "dashboard" (activity-feed.db/recent-dashboards ids)+ "table" (activity-feed.db/recent-tables ids)))(defn- models-for-views"Returns a map of {model {id instance}} for activity views suitable for looking up by model and id to get a model."@@ -69,38 +47,8 @@from the query_execution table. The query context is always a `:question`. The results are normalized and concatenated to thequery results for dashboard and table views."[views-limit card-runs-limit]- (let [dashboard-and-table-views (t2/select [:model/RecentViews- [[:min :recent_views.user_id] :user_id]- :model- :model_id- [[:max [:coalesce :d.view_count :t.view_count]] :cnt]- [:%max.timestamp :max_ts]]- {:group-by [:model :model_id]- :where [:and- [:= :context "view"]- [:in :model #{"dashboard" "table"}]- [:or [:= :active true] [:= :active nil]]- [:or [:= :archived false] [:= :archived nil]]]- :order-by [[:max_ts :desc] [:model :desc]]- :limit views-limit- :left-join [[:report_dashboard :d]- [:and- [:= :model "dashboard"]- [:= :d.id :model_id]]- [:metabase_table :t]- [:and- [:= :model "table"]- [:= :t.id :model_id]]]})- card-runs (->> (t2/select [:model/QueryExecution- [:%min.executor_id :user_id]- [(app-db/qualify :model/QueryExecution :card_id) :model_id]- [:%count.* :cnt]- [:%max.started_at :max_ts]]- {:group-by [(app-db/qualify :model/QueryExecution :card_id) :context]- :where [:and- [:= :context (h2x/literal :question)]]- :order-by [[:max_ts :desc]]- :limit card-runs-limit})+ (let [dashboard-and-table-views (activity-feed.db/recent-dashboard-and-table-views views-limit)+ card-runs (->> (activity-feed.db/recent-card-runs card-runs-limit)(mapv #(-> %(dissoc :row_count)(assoc :model "card"))))]@@ -154,11 +102,23 @@[:model (into [:enum] recent-views/rv-models)][:model_id ms/PositiveInt][:context [:enum :selection]]]]- (let [model-id model_id- model-type (recent-views/rv-model->model model)]- (when-not (t2/exists? model-type :id model-id)+ (let [model-id model_id+ model-type (recent-views/rv-model->model model)+ exists? (case model-type+ :model/Card (activity-feed.db/card-exists? model-id)+ :model/Dashboard (activity-feed.db/dashboard-exists? model-id)+ :model/Table (activity-feed.db/table-exists? model-id)+ :model/Collection (activity-feed.db/collection-exists? model-id)+ :model/Document (activity-feed.db/document-exists? model-id))+ entity (fn [] (case model-type+ :model/Card (activity-feed.db/card model-id)+ :model/Dashboard (activity-feed.db/dashboard model-id)+ :model/Table (activity-feed.db/table model-id)+ :model/Collection (activity-feed.db/collection model-id)+ :model/Document (activity-feed.db/document model-id)))]+ (when-not exists?(throw (ex-info "Model not found" {:model model :model_id model-id})))- (api/read-check (t2/select-one model-type :id model-id))+ (api/read-check (entity))(recent-views/update-users-recent-views! *current-user-id* model-type model-id context)));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API@@ -173,7 +133,7 @@in the last 24 hours."[](if-let [dashboard-id (recent-views/most-recently-viewed-dashboard-id *current-user-id*)]- (let [dashboard (-> (t2/select-one :model/Dashboard :id dashboard-id)+ (let [dashboard (-> (activity-feed.db/dashboard dashboard-id)api/check-404(t2/hydrate [:collection :is_personal]))](if (mi/can-read? dashboard)diff --git a/src/metabase/activity_feed/db.clj b/src/metabase/activity_feed/db.cljnew file mode 100644index 00000000000..e93735c5550--- /dev/null+++ b/src/metabase/activity_feed/db.clj@@ -0,0 +1,344 @@+(ns metabase.activity-feed.db+ "Application database queries for the activity feed module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.collections.models.collection :as collection]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn recent-cards+ "The recently viewed Cards with `ids`, with their Collection and Dashboard names."+ [ids]+ (t2/select [:model/Card+ :id :name :collection_id :description :display+ :dataset_query :type :archived :card_schema+ :collection.authority_level [:collection.name :collection_name]+ [:dashboard.name :dashboard_name] :dashboard_id]+ {:where [:in :report_card.id ids]+ :left-join [:collection [:= :collection.id :report_card.collection_id]+ [:report_dashboard :dashboard] [:= :dashboard.id :report_card.dashboard_id]]}))++(defn recent-dashboards+ "The recently viewed Dashboards with `ids`, with their Collection names."+ [ids]+ (t2/select [:model/Dashboard+ :id :name :collection_id :description+ :archived+ :collection.authority_level [:collection.name :collection_name]]+ {:where [:in :report_dashboard.id ids]+ :left-join [:collection [:= :collection.id :report_dashboard.collection_id]]}))++(defn recent-tables+ "The recently viewed Tables with `ids`, with their Database names and sync status."+ [ids]+ (t2/select [:model/Table+ :id :name :db_id :active+ :display_name [:metabase_database.initial_sync_status :initial-sync-status]+ [:visibility_type :visibility_type]+ [:metabase_database.name :database-name]]+ {:where [:in :metabase_table.id ids]+ :left-join [:metabase_database [:= :metabase_database.id :metabase_table.db_id]]}))++(defn recent-dashboard-and-table-views+ "Up to `limit` most recently viewed unarchived, active Dashboards and Tables with their view counts and last+ viewer."+ [limit]+ (t2/select [:model/RecentViews+ [[:min :recent_views.user_id] :user_id]+ :model+ :model_id+ [[:max [:coalesce :d.view_count :t.view_count]] :cnt]+ [:%max.timestamp :max_ts]]+ {:group-by [:model :model_id]+ :where [:and+ [:= :context "view"]+ [:in :model #{"dashboard" "table"}]+ [:or [:= :active true] [:= :active nil]]+ [:or [:= :archived false] [:= :archived nil]]]+ :order-by [[:max_ts :desc] [:model :desc]]+ :limit limit+ :left-join [[:report_dashboard :d]+ [:and+ [:= :model "dashboard"]+ [:= :d.id :model_id]]+ [:metabase_table :t]+ [:and+ [:= :model "table"]+ [:= :t.id :model_id]]]}))++(defn recent-card-runs+ "Up to `limit` most recently run question Cards with their run counts and last runner."+ [limit]+ (t2/select [:model/QueryExecution+ [:%min.executor_id :user_id]+ [:query_execution.card_id :model_id]+ [:%count.* :cnt]+ [:%max.started_at :max_ts]]+ {:group-by [:query_execution.card_id :context]+ :where [:and+ [:= :context (h2x/literal :question)]]+ :order-by [[:max_ts :desc]]+ :limit limit}))++(defn card-exists?+ "Whether a Card with `id` exists."+ [id]+ (t2/exists? :model/Card :id id))++(defn dashboard-exists?+ "Whether a Dashboard with `id` exists."+ [id]+ (t2/exists? :model/Dashboard :id id))++(defn table-exists?+ "Whether a Table with `id` exists."+ [id]+ (t2/exists? :model/Table :id id))++(defn collection-exists?+ "Whether a Collection with `id` exists."+ [id]+ (t2/exists? :model/Collection :id id))++(defn document-exists?+ "Whether a Document with `id` exists."+ [id]+ (t2/exists? :model/Document :id id))++(defn card+ "The Card with `id`, or nil."+ [id]+ (t2/select-one :model/Card :id id))++(defn table+ "The Table with `id`, or nil."+ [id]+ (t2/select-one :model/Table :id id))++(defn collection+ "The Collection with `id`, or nil."+ [id]+ (t2/select-one :model/Collection :id id))++(defn document+ "The Document with `id`, or nil."+ [id]+ (t2/select-one :model/Document :id id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn card-document-id+ "The Document id of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :document_id :model/Card :id card-id))++(defn recent-views-for-user-context+ "The RecentViews of the User with `user-id` in `context`, newest first."+ [user-id context]+ (t2/select :model/RecentViews :user_id user-id :context context {:order-by [[:timestamp :desc]]}))++(defn recent-view-ids-to-prune+ "The ids of the RecentViews of the User with `user-id` for `db-model` in `context` beyond the newest `keep` of+ them, restricted to the Cards of `card-type` when non-nil."+ [db-model user-id context card-type keep]+ (t2/select-fn-set :id+ :model/RecentViews+ {:select [:rv.id]+ :from [[:recent_views :rv]]+ :where [:and+ [:= :rv.model db-model]+ [:= :rv.user_id user-id]+ [:= :rv.context (h2x/literal context)]+ (when card-type+ [:= :rc.type (h2x/literal card-type)])]+ :left-join [[:report_card :rc]+ [:and+ [:= :rc.id :rv.model_id]+ [:= :rv.model (h2x/literal "card")]]]+ :order-by [[:rv.timestamp :desc]]+ ;; mysql doesn't support offset without limit :derp:+ :limit 100000+ :offset keep}))++(defn insert-recent-views!+ "Insert the RecentViews `rows`."+ [rows]+ (t2/insert! :model/RecentViews rows))++(defn delete-recent-views!+ "Delete the RecentViews with `ids`."+ [ids]+ (t2/delete! :model/RecentViews :id [:in ids]))++(defn most-recently-viewed-dashboard-id+ "The id of the unarchived Dashboard the User with `user-id` viewed most recently after `since`, or nil."+ [user-id since]+ (t2/select-one-fn+ :model_id+ :model/RecentViews+ {:where [:and+ [:= :user_id user-id]+ [:= :model (h2x/literal "dashboard")]+ [:> :timestamp since]+ [:not= :d.archived true]]+ :order-by [[:recent_views.id :desc]]+ :left-join [[:report_dashboard :d]+ [:= :recent_views.model_id :d.id]]}))++(defn cards-for-recent-views+ "The Cards with `card-ids` with their Dashboard, Collection, and moderation status."+ [card-ids]+ (t2/select :model/Card+ {:select [:card.name+ :card.description+ :card.archived+ :card.id+ :card.database_id+ :card.display+ :card.card_schema+ :card.result_metadata+ :card.dataset_query+ :card.entity_id+ :card.visualization_settings+ [:dashboard.id :dashboard_id]+ [:dashboard.name :dashboard_name]+ [:card.collection_id :entity-coll-id]+ [:mr.status :moderated-status]+ [:collection.id :collection_id]+ [:collection.name :collection_name]+ [:collection.authority_level :collection_authority_level]]+ :from [[:report_card :card]]+ :where [:in :card.id card-ids]+ :left-join [[:moderation_review :mr]+ [:and+ [:= :mr.moderated_item_id :card.id]+ [:= :mr.moderated_item_type "card"]+ [:= :mr.most_recent true]]+ [:collection]+ [:and+ [:= :collection.id :card.collection_id]+ [:= :collection.archived false]]+ [:report_dashboard :dashboard]+ [:= :dashboard.id :card.dashboard_id]]}))++(defn dashboards-for-recent-views+ "The Dashboards with `dashboard-ids` with their Collection and moderation status."+ [dashboard-ids]+ (t2/select :model/Dashboard+ {:select [:dash.id+ :dash.name+ :dash.description+ :dash.archived+ [:dash.collection_id :entity-coll-id]+ [:c.id :collection_id]+ [:c.name :collection_name]+ [:c.authority_level :collection_authority_level]+ [:mr.status :moderated-status]]+ :from [[:report_dashboard :dash]]+ :where [:in :dash.id dashboard-ids]+ :left-join [[:moderation_review :mr]+ [:and+ [:= :mr.moderated_item_id :dash.id]+ [:= :mr.moderated_item_type "dashboard"]+ [:= :mr.most_recent true]]+ [:collection :c]+ [:and+ [:= :c.id :dash.collection_id]+ [:= :c.archived false]]]}))++(defn unarchived-collections-with-details+ "The unarchived Collections with `collection-ids`, with their location, type, and authority level."+ [collection-ids]+ (t2/select :model/Collection+ {:select [:id :name :description :authority_level+ :archived :location :type]+ :where [:and+ [:in :id collection-ids]+ [:= :archived false]]}))++(defn visible-tables-for-recent-views+ "The non-hidden Tables with `table-ids` with their Database name and sync status."+ [table-ids]+ (t2/select :model/Table+ {:select [:t.id :t.name :t.description+ :t.display_name :t.active :t.visibility_type :t.schema+ [:db.name :database-name]+ [:db.id :db_id]+ [:db.initial_sync_status :initial-sync-status]]+ :from [[:metabase_table :t]]+ :where [:and+ [:or+ [:= :visibility_type nil]+ [:!= :visibility_type "hidden"]]+ [:in :t.id table-ids]]+ :left-join [[:metabase_database :db]+ [:= :db.id :t.db_id]]}))++(defn recent-views-with-card-type+ "The RecentViews of the User with `user-id` in `contexts`, newest first, with the type of the viewed Card. Narrowed+ to `db-models` and to the Cards of `card-types` when given; excludes trashed and namespaced Collections, exploration+ Documents, and, when `selections?`, the instance analytics Collection."+ [user-id contexts db-models card-types selections?]+ (t2/select :model/RecentViews+ {:select [:rv.* [:rc.type :card_type]]+ :from [[:recent_views :rv]]+ :where [:and+ [:= :rv.user_id user-id]+ [:in :rv.context contexts]+ (when (seq db-models)+ [:in :rv.model db-models])+ ;; Additionally filter by card type to distinguish questions/models/metrics+ (when (seq card-types)+ [:or+ [:!= :rv.model "card"]+ [:in :rc.type (map h2x/literal card-types)]])+ ;; include non-collections, or collections without a namespace/type.+ [:or+ [:= :coll.id nil]+ [:and+ ;; trash collection is never returned+ [:or [:= nil :coll.type] [:not= :coll.type collection/trash-collection-type]]+ ;; collections in a different namespace can't interact with collections+ ;; in the normal NULL namespace.+ [:= nil :coll.namespace]+ ;; exclude instance analytics for selects+ (when selections?+ [:or [:= nil :coll.type] [:not= :coll.type collection/instance-analytics-collection-type]])]]+ ;; exploration documents are accessible only through their owning Exploration;+ ;; hide them from recents to match search and collection-listing behavior.+ [:or [:!= :rv.model "document"] [:= :doc.exploration_id nil]]]+ :left-join [[:report_card :rc]+ [:and+ ;; only want to join on card_type if it's a card+ [:= :rv.model "card"]+ [:= :rc.id :rv.model_id]]+ [:collection :coll]+ [:and+ [:= :rv.model "collection"]+ [:= :coll.id :rv.model_id]]+ [:document :doc]+ [:and+ [:= :rv.model "document"]+ [:= :doc.id :rv.model_id]]]+ :order-by [[:rv.timestamp :desc]]}))++(defn documents-for-recent-views+ "The Documents with `document-ids` with their Collection."+ [document-ids]+ (t2/select :model/Document+ {:select [:d.id+ :d.name+ :d.archived+ [:d.collection_id :entity-coll-id]+ [:c.id :collection_id]+ [:c.name :collection_name]+ [:c.authority_level :collection_authority_level]]+ :from [[:document :d]]+ :where [:in :d.id document-ids]+ :left-join [[:collection :c]+ [:and+ [:= :c.id :d.collection_id]+ [:= :c.archived false]]]}))diff --git a/src/metabase/activity_feed/events/recent_views.clj b/src/metabase/activity_feed/events/recent_views.cljindex c8bfbc92703..e2379eeb81a 100644--- a/src/metabase/activity_feed/events/recent_views.clj+++ b/src/metabase/activity_feed/events/recent_views.clj@@ -1,14 +1,14 @@(ns metabase.activity-feed.events.recent-views"This namespace is responsible for subscribing to events which should update the recent views for a user."(:require+ [metabase.activity-feed.db :as activity-feed.db][metabase.activity-feed.models.recent-views :as recent-views][metabase.api.common :as api][metabase.events.core :as events][metabase.util :as u][metabase.util.log :as log][methodical.core :as m]- [steffan-westcott.clj-otel.api.trace.span :as span]- [toucan2.core :as t2]))+ [steffan-westcott.clj-otel.api.trace.span :as span]))(events/derive! ::dashboard-read :metabase/event)(events/derive! :event/dashboard-read ::dashboard-read)@@ -52,7 +52,7 @@;; we don't want to count pinned card views or document cards(when (and user-id(not (#{:collection :dashboard :dashboard-subscription} context))- (not (t2/select-one-fn :document_id :model/Card :id card-id)))+ (not (activity-feed.db/card-document-id card-id)))(recent-views/update-users-recent-views! user-id :model/Card card-id :view)))(catch Throwable e(log/warnf "Failed to process recent_views event %s: %s" topic (ex-message e)))))@@ -78,7 +78,7 @@(let [user-id (or user-id api/*current-user-id*)](when (and user-id(= context :question)- (nil? (t2/select-one-fn :document_id :model/Card :id object-id)))+ (nil? (activity-feed.db/card-document-id object-id)))(try(recent-views/update-users-recent-views! user-id :model/Card object-id :view)(catch Throwable ediff --git a/src/metabase/activity_feed/models/recent_views.clj b/src/metabase/activity_feed/models/recent_views.cljindex 318be6485db..c16aa4aac1f 100644--- a/src/metabase/activity_feed/models/recent_views.clj+++ b/src/metabase/activity_feed/models/recent_views.clj@@ -29,14 +29,13 @@[malli.core :as mc][malli.error :as me][medley.core :as m]+ [metabase.activity-feed.db :as activity-feed.db][metabase.batch-processing.core :as grouper]- [metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as root][metabase.config.core :as config][metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]@@ -65,10 +64,7 @@"Returns a set of IDs of duplicate models in the RecentViews table. Duplicate means that the same model and model_idshows up more than once. This returns the ids for the copies that are not the most recent entry."[user-id context]- (->> (t2/select :model/RecentViews- :user_id user-id- :context context- {:order-by [[:timestamp :desc]]})+ (->> (activity-feed.db/recent-views-for-user-context user-id context)(group-by (juxt :model :model_id));; skip the first row for each group, since it's the most recent(into #{} (comp (mapcat (fn [[_ rows]] (drop 1 rows)))@@ -114,24 +110,11 @@(name model)))(defn- ids-to-prune-for-user+model [user-id model context]- (t2/select-fn-set :id- :model/RecentViews- {:select [:rv.id]- :from [[:recent_views :rv]]- :where [:and- [:= :rv.model (rv-model->db-model model)]- [:= :rv.user_id user-id]- [:= :rv.context (h2x/literal (name context))]- (when-let [card-type (rv-model->card-type model)]- [:= :rc.type (h2x/literal card-type)])]- :left-join [[:report_card :rc]- [:and- [:= :rc.id :rv.model_id]- [:= :rv.model (h2x/literal "card")]]]- :order-by [[:rv.timestamp :desc]]- ;; mysql doesn't support offset without limit :derp:- :limit 100000- :offset *recent-views-stored-per-user-per-model*}))+ (activity-feed.db/recent-view-ids-to-prune (rv-model->db-model model)+ user-id+ (name context)+ (rv-model->card-type model)+ *recent-views-stored-per-user-per-model*))(defn- overflowing-model-buckets [user-id context](into #{} (mapcat #(ids-to-prune-for-user+model user-id % context)) rv-models))@@ -152,13 +135,13 @@(when (seq views)(try(t2/with-transaction [_conn]- (t2/insert! :model/RecentViews- (for [{:keys [user-id model model-id context timestamp]} views]- {:user_id user-id- :model (u/lower-case-en (name model))- :model_id model-id- :context (name context)- :timestamp timestamp}))+ (activity-feed.db/insert-recent-views!+ (for [{:keys [user-id model model-id context timestamp]} views]+ {:user_id user-id+ :model (u/lower-case-en (name model))+ :model_id model-id+ :context (name context)+ :timestamp timestamp}));; The prune queries are per (user, context), not per view, so collapse the batch down to its distinct;; pairs first: N views by one user become one set of prune queries instead of N.(let [prune-ids (into #{}@@ -167,7 +150,7 @@(mapcat (fn [[user-id context]] (ids-to-prune user-id context))))views)](when (seq prune-ids)- (t2/delete! :model/RecentViews :id [:in prune-ids]))))+ (activity-feed.db/delete-recent-views! prune-ids))))(catch Exception e(log/error e "Failed to update users recent views")))))@@ -197,17 +180,7 @@(defn most-recently-viewed-dashboard-id"Returns ID of the most recently viewed dashboard for a given user within the last 24 hours, or `nil`."[user-id]- (t2/select-one-fn- :model_id- :model/RecentViews- {:where [:and- [:= :user_id user-id]- [:= :model (h2x/literal "dashboard")]- [:> :timestamp (t/minus (t/zoned-date-time) (t/days 1))]- [:not= :d.archived true]]- :order-by [[:recent_views.id :desc]]- :left-join [[:report_dashboard :d]- [:= :recent_views.model_id :d.id]]}))+ (activity-feed.db/most-recently-viewed-dashboard-id user-id (t/minus (t/zoned-date-time) (t/days 1))))(def Item"The shape of a recent view item, returned from `GET /recent_views`."@@ -293,38 +266,7 @@[card-ids](if-not (seq card-ids)[]- (t2/select :model/Card- {:select [:card.name- :card.description- :card.archived- :card.id- :card.database_id- :card.display- :card.card_schema- :card.result_metadata- :card.dataset_query- :card.entity_id- :card.visualization_settings- [:dashboard.id :dashboard_id]- [:dashboard.name :dashboard_name]- [:card.collection_id :entity-coll-id]- [:mr.status :moderated-status]- [:collection.id :collection_id]- [:collection.name :collection_name]- [:collection.authority_level :collection_authority_level]]- :from [[:report_card :card]]- :where [:in :card.id card-ids]- :left-join [[:moderation_review :mr]- [:and- [:= :mr.moderated_item_id :card.id]- [:= :mr.moderated_item_type "card"]- [:= :mr.most_recent true]]- [:collection]- [:and- [:= :collection.id :card.collection_id]- [:= :collection.archived false]]- [:report_dashboard :dashboard]- [:= :dashboard.id :card.dashboard_id]]})))+ (activity-feed.db/cards-for-recent-views card-ids)))(defn- fill-parent-coll [model-object](if (:collection_id model-object)@@ -406,27 +348,7 @@[dashboard-ids](if (empty? dashboard-ids)[]- (t2/select :model/Dashboard- {:select [:dash.id- :dash.name- :dash.description- :dash.archived- [:dash.collection_id :entity-coll-id]- [:c.id :collection_id]- [:c.name :collection_name]- [:c.authority_level :collection_authority_level]- [:mr.status :moderated-status]]- :from [[:report_dashboard :dash]]- :where [:in :dash.id dashboard-ids]- :left-join [[:moderation_review :mr]- [:and- [:= :mr.moderated_item_id :dash.id]- [:= :mr.moderated_item_type "dashboard"]- [:= :mr.most_recent true]]- [:collection :c]- [:and- [:= :c.id :dash.collection_id]- [:= :c.archived false]]]})))+ (activity-feed.db/dashboards-for-recent-views dashboard-ids)))(defmethod fill-recent-view-info :dashboard [{:keys [_model model_id timestamp model_object]}](when-let [dashboard (and (mi/can-read? model_object)@@ -449,12 +371,7 @@(if-not (seq collection-ids)[](let [;; these have their parent collection id in effective_location, but we need the id, name, and authority_level.- collections (t2/select :model/Collection- {:select [:id :name :description :authority_level- :archived :location :type]- :where [:and- [:in :id collection-ids]- [:= :archived false]]})]+ collections (activity-feed.db/unarchived-collections-with-details collection-ids)](->> (t2/hydrate collections :effective_parent)(map #(m/dissoc-in % [:effective_parent :type]))))))@@ -480,20 +397,7 @@[table-ids](if-not (seq table-ids)[]- (t2/select :model/Table- {:select [:t.id :t.name :t.description- :t.display_name :t.active :t.visibility_type :t.schema- [:db.name :database-name]- [:db.id :db_id]- [:db.initial_sync_status :initial-sync-status]]- :from [[:metabase_table :t]]- :where [:and- [:or- [:= :visibility_type nil]- [:!= :visibility_type "hidden"]]- [:in :t.id table-ids]]- :left-join [[:metabase_database :db]- [:= :db.id :t.db_id]]})))+ (activity-feed.db/visible-tables-for-recent-views table-ids)))(defmethod fill-recent-view-info :table [{:keys [_model model_id timestamp model_object]}](let [table model_object]@@ -527,48 +431,11 @@(when-not (seq context)(throw (ex-info "context must be non-empty" {:context context})))(let [db-models (rv-models->db-models models)]- (t2/select :model/RecentViews {:select [:rv.* [:rc.type :card_type]]- :from [[:recent_views :rv]]- :where [:and- [:= :rv.user_id user-id]- [:in :rv.context (map query-context->recent-context context)]- (when (seq db-models)- [:in :rv.model db-models])- ;; Additionally filter by card type to distinguish questions/models/metrics- (let [card-types (keep rv-model->card-type models)]- (when (seq card-types)- [:or- [:!= :rv.model "card"]- [:in :rc.type (map h2x/literal card-types)]]))- ;; include non-collections, or collections without a namespace/type.- [:or- [:= :coll.id nil]- [:and- ;; trash collection is never returned- [:or [:= nil :coll.type] [:not= :coll.type collection/trash-collection-type]]- ;; collections in a different namespace can't interact with collections- ;; in the normal NULL namespace.- [:= nil :coll.namespace]- ;; exclude instance analytics for selects- (when (contains? (set context) :selections)- [:or [:= nil :coll.type] [:not= :coll.type collection/instance-analytics-collection-type]])]]- ;; exploration documents are accessible only through their owning Exploration;- ;; hide them from recents to match search and collection-listing behavior.- [:or [:!= :rv.model "document"] [:= :doc.exploration_id nil]]]- :left-join [[:report_card :rc]- [:and- ;; only want to join on card_type if it's a card- [:= :rv.model "card"]- [:= :rc.id :rv.model_id]]- [:collection :coll]- [:and- [:= :rv.model "collection"]- [:= :coll.id :rv.model_id]]- [:document :doc]- [:and- [:= :rv.model "document"]- [:= :doc.id :rv.model_id]]]- :order-by [[:rv.timestamp :desc]]})))+ (activity-feed.db/recent-views-with-card-type user-id+ (map query-context->recent-context context)+ db-models+ (keep rv-model->card-type models)+ (contains? (set context) :selections))))(mu/defn- model->return-model [model :- :keyword](if (= :question model) :card model))@@ -594,20 +461,7 @@[document-ids](if-not (seq document-ids)[]- (let [documents (t2/select :model/Document- {:select [:d.id- :d.name- :d.archived- [:d.collection_id :entity-coll-id]- [:c.id :collection_id]- [:c.name :collection_name]- [:c.authority_level :collection_authority_level]]- :from [[:document :d]]- :where [:in :d.id document-ids]- :left-join [[:collection :c]- [:and- [:= :c.id :d.collection_id]- [:= :c.archived false]]]})]+ (let [documents (activity-feed.db/documents-for-recent-views document-ids)]documents)))(defn- get-entity->id->data [views]diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 6c9b2882e41..80906880ef6 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -3,6 +3,7 @@Endpoints are versioned (e.g., /v1/search) and use standard HTTP semantics."(:require[clojure.string :as str]+ [metabase.agent-api.db :as agent-api.db][metabase.agent-api.query-guards :as query-guards][metabase.agent-api.settings :as agent-api.settings][metabase.agent-api.validation :as agent-api.validation]@@ -72,9 +73,7 @@[collection-id](if-not collection-id(:name (collection/root-collection-with-ui-details nil))- (let [coll (t2/select-one [:model/Collection :id :name :location :personal_owner_id- :namespace :archived_directly]- collection-id)+ (let [coll (agent-api.db/collection-breadcrumb-columns collection-id);; `:effective_ancestors` is the app breadcrumb: it leads with the "Our analytics" root and;; drops ancestors the caller can't read. A personal subtree leads with the personal;; collection instead, so drop that root crumb for them.@@ -872,7 +871,7 @@:card-updates card-updates:actor @api/*current-user*:delete-old-dashcards? false})- (update-card-response (t2/select-one :model/Card :id id))))+ (update-card-response (agent-api.db/card id))))(mr/def ::create-question-request[:map@@ -1170,8 +1169,7 @@"The dashboard's tabs as `{:id :name}` in display order, [] when it has none."[dashboard-id](mapv #(select-keys % [:id :name])- (t2/select [:model/DashboardTab :id :name] :dashboard_id dashboard-id- {:order-by [[:position :asc] [:id :asc]]})))+ (agent-api.db/dashboard-tab-names dashboard-id)))(mr/def ::create-dashboard-response[:map@@ -1218,19 +1216,17 @@(let [cards (when (seq question_ids)(mapv #(api/read-check :model/Card %) question_ids))dash (t2/with-transaction [_conn]- (let [dash (first (t2/insert-returning-instances!- :model/Dashboard- {:name dashboard-name- :description description- :parameters []- :creator_id api/*current-user-id*- :collection_id collection_id}))]+ (let [dash (agent-api.db/insert-dashboard!+ {:name dashboard-name+ :description description+ :parameters []+ :creator_id api/*current-user-id*+ :collection_id collection_id})](when (seq cards)(reduce (fn [placed card](let [display (or (:display card) :table)position (autoplaced-position placed display nil)]- (t2/insert-returning-instance!- :model/DashboardCard+ (agent-api.db/insert-dashcard!(merge position {:dashboard_id (:id dash):card_id (:id card)}))(conj placed position)))@@ -1245,8 +1241,7 @@:collection_path (collection-path (:collection_id dash)):description (:description dash);; select-fn-vec returns nil, not [], when there are no rows- :dashcard_ids (or (t2/select-fn-vec :id :model/DashboardCard :dashboard_id (:id dash)- {:order-by [[:row :asc] [:col :asc]]})+ :dashcard_ids (or (agent-api.db/dashcard-ids-in-layout-order (:id dash))[]):tabs (dashboard-tabs (:id dash))})))@@ -1345,10 +1340,9 @@Placement is per-tab: adds go on the mutation's `tab_id` (default: the first tab) and onlycollide with that tab's cards; a move only reflows cards sharing the moved card's tab."[dashboard-id mutations]- (let [current (t2/select :model/DashboardCard :dashboard_id dashboard-id)+ (let [current (agent-api.db/dashcards dashboard-id);; one fetch serves the default tab, per-mutation tab_id validation, and collision grouping- tab-ids (t2/select-pks-vec :model/DashboardTab :dashboard_id dashboard-id- {:order-by [[:position :asc] [:id :asc]]})+ tab-ids (agent-api.db/dashboard-tab-ids dashboard-id);; new dashcards land on the first tab, alongside any nil-tab dashcards, which the;; frontend renders there; nil when the dashboard has no tabsdefault-tab-id (first tab-ids)@@ -1405,8 +1399,7 @@"update_text"(let [existing (api/check-404- (t2/select-one :model/DashboardCard- :id dashcard_id :dashboard_id dashboard-id))+ (agent-api.db/dashcard-in-dashboard dashcard_id dashboard-id))vs (:visualization_settings existing)display (some-> (get-in vs [:virtual_card :display]) name)](api/check (or (contains? #{"heading" "text"} display)@@ -1417,13 +1410,11 @@(string? (:text vs))))[400 "Only heading and text cards support update_text."]);; In-place: position and size stay put, unlike a remove + add_* round-trip.- (t2/update! :model/DashboardCard dashcard_id- {:visualization_settings (assoc vs :text text)}))+ (agent-api.db/update-dashcard! dashcard_id {:visualization_settings (assoc vs :text text)}))"remove"(let [existing (api/check-404- (t2/select-one :model/DashboardCard- :id dashcard_id :dashboard_id dashboard-id))]+ (agent-api.db/dashcard-in-dashboard dashcard_id dashboard-id))];; Model-level delete also cleans up orphaned inline parameters and pulse cards.(dashboard-card/delete-dashboard-cards! [dashcard_id])(swap! state #(-> %@@ -1432,8 +1423,7 @@"move"(let [existing (api/check-404- (t2/select-one :model/DashboardCard- :id dashcard_id :dashboard_id dashboard-id))+ (agent-api.db/dashcard-in-dashboard dashcard_id dashboard-id));; A move only makes sense relative to the moved card's own tab: collision checks;; and the move-to-top reflow must not touch cards on other tabs. Compared via;; `effective-tab` so nil-tab dashcards group with the first tab they render on.@@ -1456,9 +1446,8 @@(when (= position "top")(let [shift (:size_y existing)](doseq [{:keys [id row]} tab-placed]- (t2/update! :model/DashboardCard id {:row (+ row shift)}))))- (t2/update! :model/DashboardCard dashcard_id- (select-keys new-pos [:row :col]))+ (agent-api.db/update-dashcard! id {:row (+ row shift)}))))+ (agent-api.db/update-dashcard! dashcard_id (select-keys new-pos [:row :col]))(swap! state #(-> %(assoc :placed(conj (mapv (fn [c]@@ -1480,7 +1469,7 @@;; this dashboard. Sync their archived state from the final dashcard set, like the REST path.(when (or (seq (:added @state)) (seq (:removed @state)))(dashboard/archive-or-unarchive-internal-dashboard-questions!- dashboard-id (t2/select :model/DashboardCard :dashboard_id dashboard-id)))+ dashboard-id (agent-api.db/dashcards dashboard-id)))(select-keys @state [:added :removed :moved])))(api.macros/defendpoint :put "/v1/dashboard/:id" :- ::update-dashboard-response@@ -1548,7 +1537,7 @@result (t2/with-transaction [_conn](when (seq updates)(dashboard/cascade-card-state-from-dashboard-update! current-dash updates)- (t2/update! :model/Dashboard id updates)+ (agent-api.db/update-dashboard! id updates);; Fire :event/collection-touch with the *target* collection id so the;; activity feed records the right collection. Note: the dashboards-rest;; PUT-dashboard endpoint passes the dashboard id here instead, which@@ -1572,7 +1561,7 @@{:object current-dash:user-id api/*current-user-id*:dashcards (:removed result)}))- (let [updated (t2/select-one :model/Dashboard :id id)]+ (let [updated (agent-api.db/dashboard id)](events/publish-event! :event/dashboard-update{:object updated :user-id api/*current-user-id*}){:id (:id updated)@@ -1582,8 +1571,7 @@:description (:description updated):archived (boolean (:archived updated));; select-fn-vec returns nil, not [], when there are no rows- :dashcard_ids (or (t2/select-fn-vec :id :model/DashboardCard :dashboard_id id- {:order-by [[:row :asc] [:col :asc]]})+ :dashcard_ids (or (agent-api.db/dashcard-ids-in-layout-order id)[]):tabs (dashboard-tabs id)})))@@ -1680,7 +1668,7 @@;; JWT is valid - look up user from the email extracted by the JWT provider;; The provider uses jwt-attribute-email setting to extract the email from claims(if-let [user (when-let [email (get-in result [:user-data :email])]- (t2/select-one :model/User :%lower.email (u/lower-case-en email) :is_active true))]+ (agent-api.db/active-user-by-email email))](let [scope-entry (-> result :jwt-data (find :scope))](cond-> {:user user}scope-entrydiff --git a/src/metabase/agent_api/db.clj b/src/metabase/agent_api/db.cljnew file mode 100644index 00000000000..a574f482673--- /dev/null+++ b/src/metabase/agent_api/db.clj@@ -0,0 +1,72 @@+(ns metabase.agent-api.db+ "Application database queries for the agent API module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn collection-breadcrumb-columns+ "The id, name, location, owner, namespace, and archival of the Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one [:model/Collection :id :name :location :personal_owner_id :namespace :archived_directly]+ collection-id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn dashboard-tab-names+ "The id and name of the DashboardTabs of the Dashboard with `dashboard-id`, in position order."+ [dashboard-id]+ (t2/select [:model/DashboardTab :id :name] :dashboard_id dashboard-id {:order-by [[:position :asc] [:id :asc]]}))++(defn dashboard-tab-ids+ "The ids of the DashboardTabs of the Dashboard with `dashboard-id`, in position order."+ [dashboard-id]+ (t2/select-pks-vec :model/DashboardTab :dashboard_id dashboard-id {:order-by [[:position :asc] [:id :asc]]}))++(defn insert-dashboard!+ "Insert the Dashboard `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Dashboard row))++(defn insert-dashcard!+ "Insert the DashboardCard `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/DashboardCard row))++(defn dashcard-ids-in-layout-order+ "The ids of the DashboardCards of the Dashboard with `dashboard-id`, in row then column order."+ [dashboard-id]+ (t2/select-fn-vec :id :model/DashboardCard :dashboard_id dashboard-id {:order-by [[:row :asc] [:col :asc]]}))++(defn dashcards+ "The DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id))++(defn dashcard-in-dashboard+ "The DashboardCard with `dashcard-id` on the Dashboard with `dashboard-id`, or nil."+ [dashcard-id dashboard-id]+ (t2/select-one :model/DashboardCard :id dashcard-id :dashboard_id dashboard-id))++(defn update-dashcard!+ "Apply `changes` to the DashboardCard with `dashcard-id`."+ [dashcard-id changes]+ (t2/update! :model/DashboardCard dashcard-id changes))++(defn update-dashboard!+ "Apply `changes` to the Dashboard with `dashboard-id`."+ [dashboard-id changes]+ (t2/update! :model/Dashboard dashboard-id changes))++(defn active-user-by-email+ "The active User with `email`, compared case-insensitively, or nil."+ [email]+ (t2/select-one :model/User :%lower.email (u/lower-case-en email) :is_active true))diff --git a/src/metabase/analytics/db.clj b/src/metabase/analytics/db.cljnew file mode 100644index 00000000000..63815914b27--- /dev/null+++ b/src/metabase/analytics/db.clj@@ -0,0 +1,378 @@+(ns metabase.analytics.db+ "Application database queries for the analytics module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [clojure.string :as str]+ [metabase.app-db.core :as app-db]+ [metabase.models.interface :as mi]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn first-user-date-joined+ "The earliest join date among all Users, or nil."+ []+ (t2/select-one-fn :min [:model/User [:%min.date_joined :min]]))++(defn sample-database-exists?+ "Whether a sample Database exists."+ []+ (t2/exists? :model/Database, :is_sample true))++(defn sample-database-id+ "The id of the sample Database, or nil."+ []+ (t2/select-one-pk :model/Database :is_sample true))++(defn personal-user-stats-columns+ "The active, superuser, last login, and SSO source of every personal User."+ []+ (t2/select [:model/User :is_active :is_superuser :last_login :sso_source] :type :personal))++(defn document-archived-flags+ "The archived flag of every Document."+ []+ (t2/select [:model/Document :archived]))++(defn collection-by-type+ "The id and location of a Collection of `collection-type`, or nil."+ [collection-type]+ (t2/select-one [:model/Collection :id :location] :type collection-type))++(defn descendant-collection-ids+ "The ids of the Collections whose location starts with `location-prefix`, or nil."+ [location-prefix]+ (t2/select-pks-set :model/Collection :location [:like (str location-prefix "%")]))++(defn published-table-count-in-collections+ "The number of published Tables in the Collections with `collection-ids`."+ [collection-ids]+ (t2/count :model/Table {:where [:and+ [:= :is_published true]+ [:in :collection_id collection-ids]]}))++(defn unarchived-metric-count-in-collections+ "The number of unarchived metric Cards in the Collections with `collection-ids`."+ [collection-ids]+ (t2/count :model/Card {:where [:and+ [:= :type "metric"]+ [:= :archived false]+ [:in :collection_id collection-ids]]}))++(defn permissions-group-count+ "The number of PermissionsGroups."+ []+ (t2/count :model/PermissionsGroup))++(defn dashboard-stats-columns+ "The creator, public uuid, parameters, and embedding columns of the non-internal Dashboards."+ []+ (t2/select [:model/Dashboard :creator_id :public_uuid :parameters :enable_embedding :embedding_params]+ {:where (mi/exclude-internal-content-hsql :model/Dashboard)}))++(defn dashcards-of-dashboards+ "The DashboardCards of the non-internal Dashboards."+ []+ (t2/query {:select :dc.*+ :from [[(t2/table-name :model/DashboardCard) :dc]]+ :join [[(t2/table-name :model/Dashboard) :d] [:= :d.id :dc.dashboard_id]]+ :where (mi/exclude-internal-content-hsql :model/Dashboard :table-alias :d)}))++(defn- notification-frequencies-by-column*+ [model column alerts? left-join?]+ (t2/select [model [column :k] [:%count.* :count]]+ (cond-> {:group-by [column]+ :where [(if alerts? :not= :=) :pulse.alert_condition nil]}+ left-join? (assoc :left-join [:pulse [:= :pulse.id :pulse_id]]))))++(defn pulse-channel-frequencies-by-column+ "The distinct `column` values (as `:k`) and their `:count` among the PulseChannels of alerts when `alerts?`, or of+ pulses otherwise."+ [column alerts?]+ (notification-frequencies-by-column* :model/PulseChannel column alerts? true))++(defn pulse-frequencies-by-column+ "The distinct `column` values (as `:k`) and their `:count` among the Pulses of alerts when `alerts?`, or of pulses+ otherwise."+ [column alerts?]+ (notification-frequencies-by-column* :model/Pulse column alerts? false))++(defn pulse-card-frequencies-by-column+ "The distinct `column` values (as `:k`) and their `:count` among the PulseCards of alerts when `alerts?`, or of+ pulses otherwise."+ [column alerts?]+ (notification-frequencies-by-column* :model/PulseCard column alerts? true))++(defn pulse-count+ "The number of Pulses that are not alerts."+ []+ (t2/count :model/Pulse :alert_condition nil))++(defn notification-xls-or-csv-card-count+ "The `:count` of Notifications with at least one PulseCard with `:include_xls` or `:include_csv`, of alerts when+ `alerts?`, or of pulses otherwise."+ [alerts?]+ (t2/query-one {:select [[[::h2x/distinct-count :pulse.id] :count]]+ :from [:pulse]+ :left-join [:pulse_card [:= :pulse.id :pulse_card.pulse_id]]+ :where [:and+ [:or+ [:= :pulse_card.include_csv true]+ [:= :pulse_card.include_xls true]]+ [(if alerts? :not= :=) :alert_condition nil]]}))++(defn alert-count+ "The number of Pulses that are alerts."+ []+ (t2/count :model/Pulse :alert_condition [:not= nil]))++(defn first-time-only-alert-count+ "The number of alert Pulses that fire only once."+ []+ (t2/count :model/Pulse :alert_condition [:not= nil], :alert_first_only true))++(defn above-goal-alert-count+ "The number of alert Pulses that fire above their goal."+ []+ (t2/count :model/Pulse :alert_condition [:not= nil], :alert_above_goal true))++(defn collection-count+ "The number of non-internal Collections."+ []+ (t2/count :model/Collection {:where (mi/exclude-internal-content-hsql :model/Collection)}))++(defn card-collection-ids+ "The Collection id and schema of the non-internal Cards."+ []+ (t2/select [:model/Card :collection_id :card_schema] {:where [:and (mi/exclude-internal-content-hsql :model/Card)]}))++(defn database-stats-columns+ "The sync, engine, and DBMS version of the non-internal Databases."+ []+ (t2/select [:model/Database :is_full_sync :engine :dbms_version]+ {:where (mi/exclude-internal-content-hsql :model/Database)}))++(defn table-database-and-schema+ "The Database id and schema of the Tables of the non-internal Databases."+ []+ (t2/query {:select [:t.db_id :t.schema]+ :from [[(t2/table-name :model/Table) :t]]+ :join [[(t2/table-name :model/Database) :d] [:= :d.id :t.db_id]]+ :where (mi/exclude-internal-content-hsql :model/Database :table-alias :d)}))++(defn field-table-ids+ "The Table id of the Fields of the non-internal Databases."+ []+ (t2/query {:select [:f.table_id]+ :from [[(t2/table-name :model/Field) :f]]+ :join [[(t2/table-name :model/Table) :t] [:= :t.id :f.table_id]+ [(t2/table-name :model/Database) :d] [:= :d.id :t.db_id]]+ :where (mi/exclude-internal-content-hsql :model/Database :table-alias :d)}))++(defn segment-count+ "The number of Segments."+ []+ (t2/count :model/Segment))++(defn unarchived-metric-card-count+ "The number of unarchived metric Cards."+ []+ (t2/count :model/Card :type :metric :archived false))++(defn- execution-metrics-sql []+ ;; Postgres automatically adjusts for daylight saving time when performing time calculations on TIMESTAMP WITH TIME+ ;; ZONE. This can cause discrepancies when subtracting 30 days if the calculation crosses a DST boundary (e.g., in the+ ;; Pacific/Auckland timezone). To avoid this, we ensure all date computations are done in UTC on Postgres to prevent+ ;; any time shifts due to DST. See PR #48204+ (let [thirty-days-ago (case (app-db/db-type)+ :postgres "CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '30 days'"+ :h2 "DATEADD('DAY', -30, CURRENT_TIMESTAMP)"+ :mysql "CURRENT_TIMESTAMP - INTERVAL 30 DAY")+ started-at (case (app-db/db-type)+ :postgres "started_at AT TIME ZONE 'UTC'"+ :h2 "started_at"+ :mysql "started_at")+ timestamp-where (str started-at " > " thirty-days-ago)]+ (str/join+ "\n"+ ["WITH user_executions AS ("+ " SELECT executor_id, COUNT(*) AS num_executions"+ " FROM query_execution"+ " WHERE " timestamp-where+ " GROUP BY executor_id"+ "),"+ "query_stats_1 AS ("+ " SELECT"+ " COUNT(*) AS executions,"+ " SUM(CASE WHEN error IS NULL OR length(error) = 0 THEN 1 ELSE 0 END) AS by_status__completed,"+ " SUM(CASE WHEN error IS NOT NULL OR length(error) > 0 THEN 1 ELSE 0 END) AS by_status__failed,"+ " COALESCE(SUM(CASE WHEN running_time = 0 THEN 1 ELSE 0 END), 0) AS num_by_latency__0,"+ " COALESCE(SUM(CASE WHEN running_time > 0 AND running_time < 1000 THEN 1 ELSE 0 END), 0) AS num_by_latency__lt_1,"+ " COALESCE(SUM(CASE WHEN running_time >= 1000 AND running_time < 10000 THEN 1 ELSE 0 END), 0) AS num_by_latency__1_10,"+ " COALESCE(SUM(CASE WHEN running_time >= 10000 AND running_time < 50000 THEN 1 ELSE 0 END), 0) AS num_by_latency__11_50,"+ " COALESCE(SUM(CASE WHEN running_time >= 50000 AND running_time < 250000 THEN 1 ELSE 0 END), 0) AS num_by_latency__51_250,"+ " COALESCE(SUM(CASE WHEN running_time >= 250000 AND running_time < 1000000 THEN 1 ELSE 0 END), 0) AS num_by_latency__251_1000,"+ " COALESCE(SUM(CASE WHEN running_time >= 1000000 AND running_time < 10000000 THEN 1 ELSE 0 END), 0) AS num_by_latency__1001_10000,"+ " COALESCE(SUM(CASE WHEN running_time >= 10000000 THEN 1 ELSE 0 END), 0) AS num_by_latency__10000_plus"+ " FROM query_execution"+ " WHERE " timestamp-where+ "),"+ "query_stats_2 AS ("+ " SELECT"+ " COALESCE(SUM(CASE WHEN num_executions = 0 THEN 1 ELSE 0 END), 0) AS num_per_user__0,"+ " COALESCE(SUM(CASE WHEN num_executions > 0 AND num_executions < 1 THEN 1 ELSE 0 END), 0) AS num_per_user__lt_1,"+ " COALESCE(SUM(CASE WHEN num_executions >= 1 AND num_executions < 10 THEN 1 ELSE 0 END), 0) AS num_per_user__1_10,"+ " COALESCE(SUM(CASE WHEN num_executions >= 10 AND num_executions < 50 THEN 1 ELSE 0 END), 0) AS num_per_user__11_50,"+ " COALESCE(SUM(CASE WHEN num_executions >= 50 AND num_executions < 250 THEN 1 ELSE 0 END), 0) AS num_per_user__51_250,"+ " COALESCE(SUM(CASE WHEN num_executions >= 250 AND num_executions < 1000 THEN 1 ELSE 0 END), 0) AS num_per_user__251_1000,"+ " COALESCE(SUM(CASE WHEN num_executions >= 1000 AND num_executions < 10000 THEN 1 ELSE 0 END), 0) AS num_per_user__1001_10000,"+ " COALESCE(SUM(CASE WHEN num_executions >= 10000 THEN 1 ELSE 0 END), 0) AS num_per_user__10000_plus"+ " FROM user_executions"+ ")"+ "SELECT q1.*, q2.* FROM query_stats_1 q1, query_stats_2 q2;"])))++(defn execution-metrics+ "The execution statistics over the last 30 days of QueryExecutions."+ []+ (first (t2/query (execution-metrics-sql))))++(defn query-cache-stats+ "The average result `:length` and `:count` of the QueryCache entries."+ []+ (t2/select-one [:model/QueryCache [[:avg [:length :results]] :length] [:%count.* :count]]))++(defn user-count-joined-before+ "The number (up to `limit`) of non-internal Users who joined at or before `joined-before`."+ [joined-before limit]+ (t2/count :model/User {:where [:and+ [:<= :date_joined joined-before]+ (mi/exclude-internal-content-hsql :model/User)]+ :limit limit}))++(defn query-execution-ids-excluding-database+ "Up to `limit` ids of QueryExecutions not run against the Database with `database-id`."+ [database-id limit]+ (t2/select-fn-set :id :model/QueryExecution+ {:where [:or+ [:not= :database_id database-id]+ [:= :database_id nil]]+ :limit limit}))++(defn transform-count+ "The number of Transforms."+ []+ (t2/count :model/Transform))++(defn transform-run-count-since+ "The number of TransformRuns started at or after `since`."+ [since]+ (t2/count :model/TransformRun :start_time [:>= since]))++(defn unarchived-model-count+ "The number of unarchived model Cards."+ []+ (t2/count :model/Card :type :model :archived false))++(defn new-embedded-dashboard-count-since+ "The number of unarchived Dashboards with embedding enabled created at or after `since`."+ [since]+ (t2/count :model/Dashboard :enable_embedding true :archived false :created_at [:>= since]))++(defn new-active-user-count-since+ "The number of active Users who joined at or after `since`."+ [since]+ (t2/count :model/User :is_active true :date_joined [:>= since]))++(defn unarchived-pivot-table-count+ "The number of unarchived pivot table Cards."+ []+ (t2/count :model/Card :display :pivot :archived false))++(defn query-execution-count-since+ "The number of QueryExecutions started at or after `since`."+ [since]+ (t2/count :model/QueryExecution :started_at [:>= since]))++(defn new-scim-user-count-since+ "The number of active SCIM-provisioned Users who joined at or after `since`."+ [since]+ (t2/count :model/User :sso_source :scim :is_active true :date_joined [:>= since]))++(defn database-engines-among+ "The set of engines of the Databases whose engine is one of `engine-names`."+ [engine-names]+ (t2/select-fn-set :engine :model/Database {:where [:in :engine engine-names]}))++(defn embedded-dashboard-exists?+ "Whether a Dashboard with embedding enabled exists."+ []+ (t2/exists? :model/Dashboard :enable_embedding true))++(defn embedded-card-exists?+ "Whether a Card with embedding enabled exists."+ []+ (t2/exists? :model/Card :enable_embedding true))++(defn public-dashboard-exists?+ "Whether a publicly shared Dashboard exists."+ []+ (t2/exists? :model/Dashboard :public_uuid [:not= nil]))++(defn public-card-exists?+ "Whether a publicly shared Card exists."+ []+ (t2/exists? :model/Card :public_uuid [:not= nil]))++(defn custom-viz-plugin-exists?+ "Whether a CustomVizPlugin exists."+ []+ (t2/exists? :model/CustomVizPlugin))++(defn uploads-database-exists?+ "Whether a Database with uploads enabled exists."+ []+ (t2/exists? :model/Database :uploads_enabled true))++(defn official-collection-exists?+ "Whether an official Collection exists."+ []+ (t2/exists? :model/Collection :authority_level "official"))++(defn cache-config-exists?+ "Whether any CacheConfig exists."+ []+ (t2/exists? :model/CacheConfig))++(defn preemptive-cache-config-exists?+ "Whether a CacheConfig that refreshes automatically exists."+ []+ (t2/exists? :model/CacheConfig :refresh_automatically true))++(defn database-router-exists?+ "Whether a DatabaseRouter exists."+ []+ (t2/exists? :model/DatabaseRouter))++(defn moderation-review-exists?+ "Whether a ModerationReview exists."+ []+ (t2/exists? :model/ModerationReview))++(defn filtered-pulse-exists?+ "Whether a Pulse with parameters exists."+ []+ (t2/exists? :model/Pulse {:where [:not= :parameters "[]"]}))++(defn upload-table-exists?+ "Whether an uploaded Table exists."+ []+ (t2/exists? :model/Table :is_upload true))++(defn snippet-collection-exists?+ "Whether a snippet Collection exists."+ []+ (t2/exists? :model/Collection :namespace "snippets"))++(defn starburst-database-details+ "The connection details of the Starburst Databases."+ []+ (t2/select-fn-set :details :model/Database :engine "starburst"))diff --git a/src/metabase/analytics/settings.clj b/src/metabase/analytics/settings.cljindex ff19900e46e..495f1a0ca20 100644--- a/src/metabase/analytics/settings.clj+++ b/src/metabase/analytics/settings.clj@@ -1,11 +1,11 @@(ns metabase.analytics.settings(:require[java-time.api :as t]+ [metabase.analytics.db :as analytics.db][metabase.config.core :as config][metabase.settings.core :as setting :refer [defsetting]][metabase.util.date-2 :as u.date]- [metabase.util.i18n :refer [deferred-tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [deferred-tru]]))(defsetting analytics-uuid(deferred-tru@@ -75,7 +75,7 @@(defn- first-user-creation"Returns the earliest user creation timestamp in the database"[]- (:min (t2/select-one [:model/User [:%min.date_joined :min]])))+ (analytics.db/first-user-date-joined))(defn- -instance-creation [](when-not (setting/get-value-of-type :timestamp :instance-creation)diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.cljindex a39d68610e2..bccc1de436f 100644--- a/src/metabase/analytics/stats.clj+++ b/src/metabase/analytics/stats.clj@@ -9,9 +9,9 @@[environ.core :as env][java-time.api :as t][medley.core :as m]+ [metabase.analytics.db :as analytics.db][metabase.analytics.event :as analytics.event][metabase.analytics.settings :as analytics.settings]- [metabase.app-db.core :as app-db][metabase.appearance.core :as appearance][metabase.config.core :as config][metabase.driver :as driver]@@ -19,19 +19,16 @@[metabase.internal-stats.core :as internal-stats][metabase.lib-be.core :as lib-be][metabase.models.humanization :as humanization]- [metabase.models.interface :as mi][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.session.settings :as session.settings][metabase.settings.core :as setting][metabase.sso.core :as sso][metabase.system.core :as system][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.version.core :as version]- [toucan2.core :as t2]))+ [metabase.version.core :as version]))(set! *warn-on-reflection* true)@@ -132,7 +129,7 @@:slack_configured (setting/get :slack-configured?):sso_configured (setting/get :google-auth-enabled):instance_started (analytics.settings/instance-creation)- :has_sample_data (t2/exists? :model/Database, :is_sample true)+ :has_sample_data (analytics.db/sample-database-exists?):enable_embedding (setting/get :enable-embedding):enable_embedding_sdk (setting/get :enable-embedding-sdk):enable_embedding_simple (setting/get :enable-embedding-simple)@@ -164,8 +161,7 @@"Get metrics based on user records.TODO: get activity in terms of created questions, pulses and dashboards"[]- {:users (merge-count-maps (for [user (t2/select [:model/User :is_active :is_superuser :last_login :sso_source]- :type :personal)]+ {:users (merge-count-maps (for [user (analytics.db/personal-user-stats-columns)]{:total 1:active (:is_active user):admin (:is_superuser user)@@ -175,7 +171,7 @@(defn- document-metrics"Get metrics based on documents."[]- {:documents (merge-count-maps (for [document (t2/select [:model/Document :archived])]+ {:documents (merge-count-maps (for [document (analytics.db/document-archived-flags)]{:total 1:archived (true? (:archived document))}))})@@ -184,31 +180,24 @@[](letfn [(collection-and-descendant-ids [type];; Get collection and build location prefix for descendants (location like "<parent-location><id>/%")- (when-let [{:keys [id location]} (t2/select-one [:model/Collection :id :location] :type type)]+ (when-let [{:keys [id location]} (analytics.db/collection-by-type type)](let [children-location (str location id "/")- descendant-ids (t2/select-pks-set :model/Collection :location [:like (str children-location "%")])]+ descendant-ids (analytics.db/descendant-collection-ids children-location)](conj (or descendant-ids #{}) id))))](let [library-data-ids (collection-and-descendant-ids "library-data")library-metrics-ids (collection-and-descendant-ids "library-metrics")]{:library_data (if (seq library-data-ids)- (t2/count :model/Table- {:where [:and- [:= :is_published true]- [:in :collection_id library-data-ids]]})+ (analytics.db/published-table-count-in-collections library-data-ids)0):library_metrics (if (seq library-metrics-ids)- (t2/count :model/Card- {:where [:and- [:= :type "metric"]- [:= :archived false]- [:in :collection_id library-metrics-ids]]})+ (analytics.db/unarchived-metric-count-in-collections library-metrics-ids)0)})))(defn- group-metrics"Get metrics based on groups:TODO characterize by # w/ sql access, # of users, no self-serve data access"[]- {:groups (t2/count :model/PermissionsGroup)})+ {:groups (analytics.db/permissions-group-count)})(defn- question-metrics"Get metrics based on questions@@ -232,12 +221,8 @@"Get metrics based on dashboardsTODO characterize by # of revisions, and created by an admin"[]- (let [dashboards (t2/select [:model/Dashboard :creator_id :public_uuid :parameters :enable_embedding :embedding_params]- {:where (mi/exclude-internal-content-hsql :model/Dashboard)})- dashcards (t2/query {:select :dc.*- :from [[(t2/table-name :model/DashboardCard) :dc]]- :join [[(t2/table-name :model/Dashboard) :d] [:= :d.id :dc.dashboard_id]]- :where (mi/exclude-internal-content-hsql :model/Dashboard :table-alias :d)})]+ (let [dashboards (analytics.db/dashboard-stats-columns)+ dashcards (analytics.db/dashcards-of-dashboards)]{:dashboards (count dashboards):with_params (count (filter (comp seq :parameters) dashboards)):num_dashs_per_user (medium-histogram dashboards :creator_id)@@ -257,82 +242,51 @@:with_disabled_params (contains? embedding-params-vals "disabled")})))}))(defn- db-frequencies- "Fetch the frequencies of a given `column` with a normal SQL `SELECT COUNT(*) ... GROUP BY` query. This is way more- efficient than fetching every single row and counting them in Clojure-land!+ "Fetch the frequencies of a given `column` of the notification `model` rows (Pulses, or rows joined to their Pulse)+ belonging to alerts when `alerts?`, or to pulses otherwise, with a normal SQL `SELECT COUNT(*) ... GROUP BY` query.+ This is way more efficient than fetching every single row and counting them in Clojure-land!- (db-frequencies Database :engine)- ;; -> {\"h2\" 2, \"postgres\" 1, ...}-- ;; include `WHERE` conditions or other arbitrary HoneySQL- (db-frequencies Database :engine {:where [:= :is_sample false]})- ;; -> {\"h2\" 1, \"postgres\" 1, ...}+ (db-frequencies :model/PulseChannel :channel_type false)+ ;; -> {\"email\" 2, \"slack\" 1, ...};; Generate a histogram:- (micro-histogram (vals (db-frequencies Database :engine)))- ;; -> {\"2\" 1, \"1\" 1, ...}-- ;; Include `WHERE` clause that includes conditions for a Table related by an FK relationship:- ;; (Number of Tables per DB engine)- (db-frequencies Table (app-db/qualify Database :engine)- {:left-join [Database [:= (app-db/qualify Database :id)- (app-db/qualify Table :db_id)]]})- ;; -> {\"googleanalytics\" 4, \"postgres\" 48, \"h2\" 9}"- [model column & [additonal-honeysql]]- (into {} (for [{:keys [k count]} (t2/select [model [column :k] [:%count.* :count]]- (merge {:group-by [column]}- additonal-honeysql))]+ (micro-histogram (vals (db-frequencies :model/PulseChannel :channel_type false)))+ ;; -> {\"2\" 1, \"1\" 1, ...}"+ [model column alerts?]+ (into {} (for [{:keys [k count]} (case model+ :model/PulseChannel (analytics.db/pulse-channel-frequencies-by-column column alerts?)+ :model/Pulse (analytics.db/pulse-frequencies-by-column column alerts?)+ :model/PulseCard (analytics.db/pulse-card-frequencies-by-column column alerts?))][k count])))-(defn- num-notifications-with-xls-or-csv-cards- "Return the number of Notifications that satisfy `where-conditions` that have at least one PulseCard with `include_xls` or- `include_csv`.-- ;; Pulses only (filter out Alerts)- (num-notifications-with-xls-or-csv-cards [:= :alert_condition nil])"- [& where-conditions]- (-> (app-db/query {:select [[[::h2x/distinct-count :pulse.id] :count]]- :from [:pulse]- :left-join [:pulse_card [:= :pulse.id :pulse_card.pulse_id]]- :where (into- [:and- [:or- [:= :pulse_card.include_csv true]- [:= :pulse_card.include_xls true]]]- where-conditions)})- first- :count))-(defn- pulse-metrics"Get metrics based on pulsesTODO: characterize by non-user account emails, # emails"[]- (let [pulse-conditions {:left-join [:pulse [:= :pulse.id :pulse_id]], :where [:= :pulse.alert_condition nil]}]- {:pulses (t2/count :model/Pulse :alert_condition nil)- ;; "Table Cards" are Cards that include a Table you can download- :with_table_cards (num-notifications-with-xls-or-csv-cards [:= :alert_condition nil])- :pulse_types (db-frequencies :model/PulseChannel :channel_type pulse-conditions)- :pulse_schedules (db-frequencies :model/PulseChannel :schedule_type pulse-conditions)- :num_pulses_per_user (medium-histogram (vals (db-frequencies :model/Pulse :creator_id (dissoc pulse-conditions :left-join))))- :num_pulses_per_card (medium-histogram (vals (db-frequencies :model/PulseCard :card_id pulse-conditions)))- :num_cards_per_pulses (medium-histogram (vals (db-frequencies :model/PulseCard :pulse_id pulse-conditions)))}))+ {:pulses (analytics.db/pulse-count)+ ;; "Table Cards" are Cards that include a Table you can download+ :with_table_cards (:count (analytics.db/notification-xls-or-csv-card-count false))+ :pulse_types (db-frequencies :model/PulseChannel :channel_type false)+ :pulse_schedules (db-frequencies :model/PulseChannel :schedule_type false)+ :num_pulses_per_user (medium-histogram (vals (db-frequencies :model/Pulse :creator_id false)))+ :num_pulses_per_card (medium-histogram (vals (db-frequencies :model/PulseCard :card_id false)))+ :num_cards_per_pulses (medium-histogram (vals (db-frequencies :model/PulseCard :pulse_id false)))})(defn- alert-metrics []- (let [alert-conditions {:left-join [:pulse [:= :pulse.id :pulse_id]], :where [:not= (app-db/qualify :model/Pulse :alert_condition) nil]}]- {:alerts (t2/count :model/Pulse :alert_condition [:not= nil])- :with_table_cards (num-notifications-with-xls-or-csv-cards [:not= :alert_condition nil])- :first_time_only (t2/count :model/Pulse :alert_condition [:not= nil], :alert_first_only true)- :above_goal (t2/count :model/Pulse :alert_condition [:not= nil], :alert_above_goal true)- :alert_types (db-frequencies :model/PulseChannel :channel_type alert-conditions)- :num_alerts_per_user (medium-histogram (vals (db-frequencies :model/Pulse :creator_id (dissoc alert-conditions :left-join))))- :num_alerts_per_card (medium-histogram (vals (db-frequencies :model/PulseCard :card_id alert-conditions)))- :num_cards_per_alerts (medium-histogram (vals (db-frequencies :model/PulseCard :pulse_id alert-conditions)))}))+ {:alerts (analytics.db/alert-count)+ :with_table_cards (:count (analytics.db/notification-xls-or-csv-card-count true))+ :first_time_only (analytics.db/first-time-only-alert-count)+ :above_goal (analytics.db/above-goal-alert-count)+ :alert_types (db-frequencies :model/PulseChannel :channel_type true)+ :num_alerts_per_user (medium-histogram (vals (db-frequencies :model/Pulse :creator_id true)))+ :num_alerts_per_card (medium-histogram (vals (db-frequencies :model/PulseCard :card_id true)))+ :num_cards_per_alerts (medium-histogram (vals (db-frequencies :model/PulseCard :pulse_id true)))})(defn- collection-metrics"Get metrics on Collection usage."[]- (let [collections (t2/count :model/Collection {:where (mi/exclude-internal-content-hsql :model/Collection)})- cards (t2/select [:model/Card :collection_id :card_schema] {:where- [:and (mi/exclude-internal-content-hsql :model/Card)]})]+ (let [collections (analytics.db/collection-count)+ cards (analytics.db/card-collection-ids)]{:collections collections:cards_in_collections (count (filter :collection_id cards)):cards_not_in_collections (count (remove :collection_id cards))@@ -342,8 +296,7 @@(defn- database-metrics"Get metrics based on Databases."[]- (let [databases (t2/select [:model/Database :is_full_sync :engine :dbms_version]- {:where (mi/exclude-internal-content-hsql :model/Database)})]+ (let [databases (analytics.db/database-stats-columns)]{:databases (merge-count-maps (for [{is-full-sync? :is_full_sync} databases]{:total 1:analyzed is-full-sync?}))@@ -357,10 +310,7 @@(defn- table-metrics"Get metrics based on Tables."[]- (let [tables (t2/query {:select [:t.db_id :t.schema]- :from [[(t2/table-name :model/Table) :t]]- :join [[(t2/table-name :model/Database) :d] [:= :d.id :t.db_id]]- :where (mi/exclude-internal-content-hsql :model/Database :table-alias :d)})]+ (let [tables (analytics.db/table-database-and-schema)]{:tables (count tables):num_per_database (medium-histogram tables :db_id):num_per_schema (medium-histogram tables :schema)}))@@ -368,78 +318,22 @@(defn- field-metrics"Get metrics based on Fields."[]- (let [fields (t2/query {:select [:f.table_id]- :from [[(t2/table-name :model/Field) :f]]- :join [[(t2/table-name :model/Table) :t] [:= :t.id :f.table_id]- [(t2/table-name :model/Database) :d] [:= :d.id :t.db_id]]- :where (mi/exclude-internal-content-hsql :model/Database :table-alias :d)})]+ (let [fields (analytics.db/field-table-ids)]{:fields (count fields):num_per_table (medium-histogram fields :table_id)}))(defn- segment-metrics"Get metrics based on Segments."[]- {:segments (t2/count :model/Segment)})+ {:segments (analytics.db/segment-count)})(defn- metric-metrics"Get metrics based on Metrics."[]- {:metrics (t2/count :model/Card :type :metric :archived false)})+ {:metrics (analytics.db/unarchived-metric-card-count)});;; Execution Metrics-(defn- execution-metrics-sql []- ;; Postgres automatically adjusts for daylight saving time when performing time calculations on TIMESTAMP WITH TIME- ;; ZONE. This can cause discrepancies when subtracting 30 days if the calculation crosses a DST boundary (e.g., in the- ;; Pacific/Auckland timezone). To avoid this, we ensure all date computations are done in UTC on Postgres to prevent- ;; any time shifts due to DST. See PR #48204- (let [thirty-days-ago (case (app-db/db-type)- :postgres "CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '30 days'"- :h2 "DATEADD('DAY', -30, CURRENT_TIMESTAMP)"- :mysql "CURRENT_TIMESTAMP - INTERVAL 30 DAY")- started-at (case (app-db/db-type)- :postgres "started_at AT TIME ZONE 'UTC'"- :h2 "started_at"- :mysql "started_at")- timestamp-where (str started-at " > " thirty-days-ago)]- (str/join- "\n"- ["WITH user_executions AS ("- " SELECT executor_id, COUNT(*) AS num_executions"- " FROM query_execution"- " WHERE " timestamp-where- " GROUP BY executor_id"- "),"- "query_stats_1 AS ("- " SELECT"- " COUNT(*) AS executions,"- " SUM(CASE WHEN error IS NULL OR length(error) = 0 THEN 1 ELSE 0 END) AS by_status__completed,"- " SUM(CASE WHEN error IS NOT NULL OR length(error) > 0 THEN 1 ELSE 0 END) AS by_status__failed,"- " COALESCE(SUM(CASE WHEN running_time = 0 THEN 1 ELSE 0 END), 0) AS num_by_latency__0,"- " COALESCE(SUM(CASE WHEN running_time > 0 AND running_time < 1000 THEN 1 ELSE 0 END), 0) AS num_by_latency__lt_1,"- " COALESCE(SUM(CASE WHEN running_time >= 1000 AND running_time < 10000 THEN 1 ELSE 0 END), 0) AS num_by_latency__1_10,"- " COALESCE(SUM(CASE WHEN running_time >= 10000 AND running_time < 50000 THEN 1 ELSE 0 END), 0) AS num_by_latency__11_50,"- " COALESCE(SUM(CASE WHEN running_time >= 50000 AND running_time < 250000 THEN 1 ELSE 0 END), 0) AS num_by_latency__51_250,"- " COALESCE(SUM(CASE WHEN running_time >= 250000 AND running_time < 1000000 THEN 1 ELSE 0 END), 0) AS num_by_latency__251_1000,"- " COALESCE(SUM(CASE WHEN running_time >= 1000000 AND running_time < 10000000 THEN 1 ELSE 0 END), 0) AS num_by_latency__1001_10000,"- " COALESCE(SUM(CASE WHEN running_time >= 10000000 THEN 1 ELSE 0 END), 0) AS num_by_latency__10000_plus"- " FROM query_execution"- " WHERE " timestamp-where- "),"- "query_stats_2 AS ("- " SELECT"- " COALESCE(SUM(CASE WHEN num_executions = 0 THEN 1 ELSE 0 END), 0) AS num_per_user__0,"- " COALESCE(SUM(CASE WHEN num_executions > 0 AND num_executions < 1 THEN 1 ELSE 0 END), 0) AS num_per_user__lt_1,"- " COALESCE(SUM(CASE WHEN num_executions >= 1 AND num_executions < 10 THEN 1 ELSE 0 END), 0) AS num_per_user__1_10,"- " COALESCE(SUM(CASE WHEN num_executions >= 10 AND num_executions < 50 THEN 1 ELSE 0 END), 0) AS num_per_user__11_50,"- " COALESCE(SUM(CASE WHEN num_executions >= 50 AND num_executions < 250 THEN 1 ELSE 0 END), 0) AS num_per_user__51_250,"- " COALESCE(SUM(CASE WHEN num_executions >= 250 AND num_executions < 1000 THEN 1 ELSE 0 END), 0) AS num_per_user__251_1000,"- " COALESCE(SUM(CASE WHEN num_executions >= 1000 AND num_executions < 10000 THEN 1 ELSE 0 END), 0) AS num_per_user__1001_10000,"- " COALESCE(SUM(CASE WHEN num_executions >= 10000 THEN 1 ELSE 0 END), 0) AS num_per_user__10000_plus"- " FROM user_executions"- ")"- "SELECT q1.*, q2.* FROM query_stats_1 q1, query_stats_2 q2;"])))-(defn- execution-metrics"Get metrics based on QueryExecutions."[]@@ -451,7 +345,7 @@"251_1000" "251-1000""1001_10000" "1001-10000""10000_plus" "10000+"} x x))- raw-results (-> (first (t2/query (execution-metrics-sql)))+ raw-results (-> (analytics.db/execution-metrics);; cast numbers to int because some DBs output bigdecimals(update-vals #(some-> % int)))](reduce (fn [acc [k v]]@@ -472,7 +366,7 @@(defn- cache-metrics"Metrics based on use of the QueryCache."[]- (let [{:keys [length count]} (t2/select-one [:model/QueryCache [[:avg [:length :results]] :length] [:%count.* :count]])]+ (let [{:keys [length count]} (analytics.db/query-cache-stats)]{:average_entry_size (int (or length 0)):num_queries_cached (bin-small-number count);; this value gets used in the snowplow ping 'metrics' section.@@ -559,26 +453,18 @@than or equal to `num-users`"[num-users](let [users-in-activation-period- (t2/count :model/User {:where [:and- [:<=- :date_joined- (t/plus (t/offset-date-time (analytics.settings/instance-creation))- (t/days activation-days))]- (mi/exclude-internal-content-hsql :model/User)]- :limit (inc num-users)})]+ (analytics.db/user-count-joined-before (t/plus (t/offset-date-time (analytics.settings/instance-creation))+ (t/days activation-days))+ (inc num-users))](>= users-in-activation-period num-users)))(defn- sufficient-queries?"Returns a Boolean indicating whether the number of queries recorded over non-sample content is greater than or equalto `num-queries`"[num-queries]- (let [sample-db-id (t2/select-one-pk :model/Database :is_sample true)+ (let [sample-db-id (analytics.db/sample-database-id);; QueryExecution can be large, so let's avoid counting everything- queries (t2/select-fn-set :id :model/QueryExecution- {:where [:or- [:not= :database_id sample-db-id]- [:= :database_id nil]]- :limit (inc num-queries)})]+ queries (analytics.db/query-execution-ids-excluding-database sample-db-id (inc num-queries))](>= (count queries) num-queries)))(defn- completed-activation-signals?@@ -676,9 +562,8 @@"Returns transform usage metrics for the Snowplow stats ping."[](let [one-day-ago (->one-day-ago)]- {:transforms (t2/count :model/Transform)- :transform_runs_last_24h (t2/count :model/TransformRun- :start_time [:>= one-day-ago])}))+ {:transforms (analytics.db/transform-count)+ :transform_runs_last_24h (analytics.db/transform-run-count-since one-day-ago)}))(defn- ->snowplow-metric-info"Collects Snowplow metrics data that is not in the legacy stats format. Also clears entity id translation count."@@ -686,20 +571,13 @@(let [one-day-ago (->one-day-ago)total-translation-count (:total (get-translation-count))](merge- {:models (t2/count :model/Card :type :model :archived false)- :new_embedded_dashboards (t2/count :model/Dashboard- :enable_embedding true- :archived false- :created_at [:>= one-day-ago])- :new_users_last_24h (t2/count :model/User- :is_active true- :date_joined [:>= one-day-ago])- :pivot_tables (t2/count :model/Card :display :pivot :archived false)- :query_executions_last_24h (t2/count :model/QueryExecution :started_at [:>= one-day-ago])+ {:models (analytics.db/unarchived-model-count)+ :new_embedded_dashboards (analytics.db/new-embedded-dashboard-count-since one-day-ago)+ :new_users_last_24h (analytics.db/new-active-user-count-since one-day-ago)+ :pivot_tables (analytics.db/unarchived-pivot-table-count)+ :query_executions_last_24h (analytics.db/query-execution-count-since one-day-ago):entity_id_translations_last_24h total-translation-count- :scim_users_last_24h (t2/count :model/User :sso_source :scim- :is_active true- :date_joined [:>= one-day-ago])}+ :scim_users_last_24h (analytics.db/new-scim-user-count-since one-day-ago)}(transform-metrics))))(mu/defn- snowplow-metrics@@ -782,8 +660,7 @@(boolean(let [major-version (config/current-major-version)minor-version (config/current-minor-version)- engines (t2/select-fn-set :engine :model/Database- {:where [:in :engine (map name (keys csv-upload-version-availability))]})]+ engines (analytics.db/database-engines-among (map name (keys csv-upload-version-availability)))](when (and major-version minor-version)(some(fn [engine]@@ -824,7 +701,7 @@:enabled (sso/ldap-enabled)}{:name :sample-data:available true- :enabled (t2/exists? :model/Database, :is_sample true)}+ :enabled (analytics.db/sample-database-exists?)}{:name :interactive-embedding:available (premium-features/hide-embed-branding?):enabled (and@@ -836,15 +713,15 @@:enabled (and(setting/get :enable-embedding-static)(or- (t2/exists? :model/Dashboard :enable_embedding true)- (t2/exists? :model/Card :enable_embedding true)))}+ (analytics.db/embedded-dashboard-exists?)+ (analytics.db/embedded-card-exists?)))}{:name :public-sharing:available true:enabled (and(setting/get :enable-public-sharing)(or- (t2/exists? :model/Dashboard :public_uuid [:not= nil])- (t2/exists? :model/Card :public_uuid [:not= nil])))}+ (analytics.db/public-dashboard-exists?)+ (analytics.db/public-card-exists?)))}{:name :whitelabel:available (premium-features/enable-whitelabeling?):enabled (whitelabeling-in-use?)}@@ -852,10 +729,10 @@:available (premium-features/enable-custom-viz?):enabled (and config/ee-available?(premium-features/enable-custom-viz?)- (t2/exists? :model/CustomVizPlugin))}+ (analytics.db/custom-viz-plugin-exists?))}{:name :csv-upload:available (csv-upload-available?)- :enabled (t2/exists? :model/Database :uploads_enabled true)}+ :enabled (analytics.db/uploads-database-exists?)}{:name :mb-analytics:available (premium-features/enable-audit-app?):enabled (premium-features/enable-audit-app?)}@@ -867,10 +744,10 @@:enabled (premium-features/enable-serialization?)}{:name :official-collections:available (premium-features/enable-official-collections?)- :enabled (t2/exists? :model/Collection :authority_level "official")}+ :enabled (analytics.db/official-collection-exists?)}{:name :cache-granular-controls:available (premium-features/enable-cache-granular-controls?)- :enabled (t2/exists? :model/CacheConfig)}+ :enabled (analytics.db/cache-config-exists?)}{:name :attached-dwh:available (premium-features/has-attached-dwh?):enabled (premium-features/has-attached-dwh?)}@@ -880,7 +757,7 @@{:name :database-routing:available (premium-features/enable-database-routing?):enabled (if (premium-features/enable-database-routing?)- (t2/exists? :model/DatabaseRouter)+ (analytics.db/database-router-exists?)false)}{:name :config-text-file:available (premium-features/enable-config-text-file?)@@ -890,10 +767,10 @@:enabled (premium-features/enable-content-translation?)}{:name :content-verification:available (premium-features/enable-content-verification?)- :enabled (t2/exists? :model/ModerationReview)}+ :enabled (analytics.db/moderation-review-exists?)}{:name :dashboard-subscription-filters:available (premium-features/enable-content-verification?)- :enabled (t2/exists? :model/Pulse {:where [:not= :parameters "[]"]})}+ :enabled (analytics.db/filtered-pulse-exists?)}{:name :disable-password-login:available (premium-features/can-disable-password-login?):enabled (not (session.settings/enable-password-login))}@@ -902,13 +779,13 @@:enabled (not= (setting/get-value-of-type :keyword :user-visibility) :all)}{:name :upload-management:available (premium-features/enable-upload-management?)- :enabled (t2/exists? :model/Table :is_upload true)}+ :enabled (analytics.db/upload-table-exists?)}{:name :snippet-collections:available (premium-features/enable-snippet-collections?)- :enabled (t2/exists? :model/Collection :namespace "snippets")}+ :enabled (analytics.db/snippet-collection-exists?)}{:name :cache-preemptive:available (premium-features/enable-preemptive-caching?)- :enabled (t2/exists? :model/CacheConfig :refresh_automatically true)}+ :enabled (analytics.db/preemptive-cache-config-exists?)}{:name :remote-sync:available (premium-features/enable-remote-sync?):enabled (premium-features/enable-remote-sync?)}@@ -920,7 +797,8 @@:available (premium-features/enable-tenants?)}{:name :starburst-legacy-impersonation:available true- :enabled (->> (t2/select-fn-set (comp :impersonation :details) :model/Database :engine "starburst")+ :enabled (->> (analytics.db/starburst-database-details)+ (map :impersonation)(some identity)boolean)}{:name :table-data-editingdiff --git a/src/metabase/api/common.clj b/src/metabase/api/common.cljindex 9926d96f52d..6004728f7ce 100644--- a/src/metabase/api/common.clj+++ b/src/metabase/api/common.clj@@ -81,6 +81,7 @@(ns metabase.api.common"Dynamic variables and utility functions/macros for writing API functions."(:require+ [metabase.api.db :as api.db][metabase.api.open-api :as open-api][metabase.events.core :as events][metabase.models.interface :as mi]@@ -89,8 +90,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [potemkin :as p]- [toucan2.core :as t2]))+ [potemkin :as p]))(declare check-403 check-404)@@ -186,7 +186,7 @@([entity id](check-exists? entity :id id))([entity k v & more]- (check-404 (apply t2/exists? entity k v more))))+ (check-404 (apply api.db/entity-exists? entity k v more))))(defn check-superuser"Check that `*current-user*` is a superuser or throw a 403. This doesn't require a DB call."@@ -348,10 +348,10 @@obj)([entity id]- (read-check (t2/select-one entity :id id)))+ (read-check (api.db/entity-by-id entity id)))([entity id & other-conditions]- (read-check (apply t2/select-one entity :id id other-conditions))))+ (read-check (apply api.db/entity-by-id entity id other-conditions))))(defn write-check"Check whether we can write an existing `obj`, or `entity` with `id`. If the object doesn't exist, throw a 404; if we@@ -367,9 +367,9 @@(throw e)))obj)([entity id]- (write-check (t2/select-one entity :id id)))+ (write-check (api.db/entity-by-id entity id)))([entity id & other-conditions]- (write-check (apply t2/select-one entity :id id other-conditions))))+ (write-check (apply api.db/entity-by-id entity id other-conditions))))(defn query-check"Check whether we can query an existing `obj`, or `entity` with `id`. If the object doesn't exist, throw a 404; if we@@ -386,9 +386,9 @@(throw e)))obj)([entity id]- (query-check (t2/select-one entity :id id)))+ (query-check (api.db/entity-by-id entity id)))([entity id & other-conditions]- (query-check (apply t2/select-one entity :id id other-conditions))))+ (query-check (apply api.db/entity-by-id entity id other-conditions))))(defn create-check"NEW! Check whether the current user has permissions to CREATE a new instance of an object with properties in map `m`.@@ -460,25 +460,28 @@[collection-id :- [:maybe ms/PositiveInt]old-position :- [:maybe ms/PositiveInt]new-position :- [:maybe ms/PositiveInt]]- (let [update-fn! (fn [plus-or-minus position-update-clause]- (doseq [model '[Card Dashboard Pulse Document]]- (t2/update! model {:collection_id collection-id- :collection_position position-update-clause}- {:collection_position [plus-or-minus :collection_position 1]})))]- (when (not= new-position old-position)- (cond- (and (nil? new-position)- old-position)- (update-fn! :- [:> old-position])-- (and new-position (nil? old-position))- (update-fn! :+ [:>= new-position])-- (> new-position old-position)- (update-fn! :- [:between old-position new-position])-- (< new-position old-position)- (update-fn! :+ [:between new-position old-position])))))+ (when (not= new-position old-position)+ (cond+ (and (nil? new-position)+ old-position)+ (doseq [shift-after! [api.db/shift-card-positions-after! api.db/shift-dashboard-positions-after!+ api.db/shift-pulse-positions-after! api.db/shift-document-positions-after!]]+ (shift-after! collection-id old-position :-))++ (and new-position (nil? old-position))+ (doseq [shift-from! [api.db/shift-card-positions-from! api.db/shift-dashboard-positions-from!+ api.db/shift-pulse-positions-from! api.db/shift-document-positions-from!]]+ (shift-from! collection-id new-position :+))++ (> new-position old-position)+ (doseq [shift-between! [api.db/shift-card-positions-between! api.db/shift-dashboard-positions-between!+ api.db/shift-pulse-positions-between! api.db/shift-document-positions-between!]]+ (shift-between! collection-id old-position new-position :-))++ (< new-position old-position)+ (doseq [shift-between! [api.db/shift-card-positions-between! api.db/shift-dashboard-positions-between!+ api.db/shift-pulse-positions-between! api.db/shift-document-positions-between!]]+ (shift-between! collection-id new-position old-position :+)))))(def ^:private ModelWithPosition"Intended to cover Cards/Dashboards/Pulses, it only asserts collection id and position, allowing extra keys"diff --git a/src/metabase/api/db.clj b/src/metabase/api/db.cljnew file mode 100644index 00000000000..63d8252b712--- /dev/null+++ b/src/metabase/api/db.clj@@ -0,0 +1,105 @@+(ns metabase.api.db+ "Application database queries for the API module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn entity-exists?+ "Whether a row of `entity` matching the key-value `conditions` exists."+ [entity & conditions]+ (apply t2/exists? entity conditions))++(defn entity-by-id+ "The `entity` row with `id` also matching the key-value `conditions`, or nil."+ [entity id & conditions]+ (apply t2/select-one entity :id id conditions))++(defn- shift-positions-after!+ [entity collection-id position plus-or-minus]+ (t2/update! entity {:collection_id collection-id+ :collection_position [:> position]}+ {:collection_position [plus-or-minus :collection_position 1]}))++(defn- shift-positions-from!+ [entity collection-id position plus-or-minus]+ (t2/update! entity {:collection_id collection-id+ :collection_position [:>= position]}+ {:collection_position [plus-or-minus :collection_position 1]}))++(defn- shift-positions-between!+ [entity collection-id lower upper plus-or-minus]+ (t2/update! entity {:collection_id collection-id+ :collection_position [:between lower upper]}+ {:collection_position [plus-or-minus :collection_position 1]}))++(defn shift-card-positions-after!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Cards in the Collection with+ `collection-id` positioned after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-after! 'Card collection-id position plus-or-minus))++(defn shift-dashboard-positions-after!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Dashboards in the Collection with+ `collection-id` positioned after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-after! 'Dashboard collection-id position plus-or-minus))++(defn shift-pulse-positions-after!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Pulses in the Collection with+ `collection-id` positioned after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-after! 'Pulse collection-id position plus-or-minus))++(defn shift-document-positions-after!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Documents in the Collection with+ `collection-id` positioned after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-after! 'Document collection-id position plus-or-minus))++(defn shift-card-positions-from!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Cards in the Collection with+ `collection-id` positioned at or after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-from! 'Card collection-id position plus-or-minus))++(defn shift-dashboard-positions-from!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Dashboards in the Collection with+ `collection-id` positioned at or after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-from! 'Dashboard collection-id position plus-or-minus))++(defn shift-pulse-positions-from!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Pulses in the Collection with+ `collection-id` positioned at or after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-from! 'Pulse collection-id position plus-or-minus))++(defn shift-document-positions-from!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Documents in the Collection with+ `collection-id` positioned at or after `position`."+ [collection-id position plus-or-minus]+ (shift-positions-from! 'Document collection-id position plus-or-minus))++(defn shift-card-positions-between!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Cards in the Collection with+ `collection-id` positioned between `lower` and `upper` inclusive."+ [collection-id lower upper plus-or-minus]+ (shift-positions-between! 'Card collection-id lower upper plus-or-minus))++(defn shift-dashboard-positions-between!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Dashboards in the Collection with+ `collection-id` positioned between `lower` and `upper` inclusive."+ [collection-id lower upper plus-or-minus]+ (shift-positions-between! 'Dashboard collection-id lower upper plus-or-minus))++(defn shift-pulse-positions-between!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Pulses in the Collection with+ `collection-id` positioned between `lower` and `upper` inclusive."+ [collection-id lower upper plus-or-minus]+ (shift-positions-between! 'Pulse collection-id lower upper plus-or-minus))++(defn shift-document-positions-between!+ "Add or subtract (`plus-or-minus`) one from the collection position of the Documents in the Collection with+ `collection-id` positioned between `lower` and `upper` inclusive."+ [collection-id lower upper plus-or-minus]+ (shift-positions-between! 'Document collection-id lower upper plus-or-minus))diff --git a/src/metabase/api_keys/api.clj b/src/metabase/api_keys/api.cljindex c4297e49cac..f591904a622 100644--- a/src/metabase/api_keys/api.clj+++ b/src/metabase/api_keys/api.clj@@ -3,6 +3,7 @@(:require[medley.core :as m][metabase.api-keys.core :as-alias api-keys]+ [metabase.api-keys.db :as api-keys.db][metabase.api-keys.models.api-key :as api-key][metabase.api-keys.schema :as api-keys.schema][metabase.api.common :as api]@@ -55,7 +56,7 @@"Get the count of API keys in the DB with the default scope."[](api/check-superuser)- (t2/count :model/ApiKey :scope nil))+ (api-keys.db/unscoped-api-key-count));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -70,10 +71,10 @@[:group_id {:optional true} [:maybe ms/PositiveInt]][:name {:optional true} [:maybe ::api-keys.schema/name]]]](api/check-superuser)- (api/let-404 [api-key-before (t2/select-one :model/ApiKey id)]+ (api/let-404 [api-key-before (api-keys.db/api-key id)](-> api-key-before(m/assoc-some ::api-keys/group-id group-id, :name key-name)- t2/save!+ api-keys.db/save-api-key!present-api-key)))(api.macros/defendpoint :put "/:id/regenerate" :- [:map@@ -85,7 +86,7 @@[{:keys [id]} :- [:map[:id ::api-keys.schema/id]]](api/check-superuser)- (api/check-404 (t2/exists? :model/ApiKey id))+ (api/check-404 (api-keys.db/api-key-exists? id))(let [regenerated (api-key/regenerate! id)]{:id id:unmasked_key (u.secret/expose (:unmasked-key regenerated))@@ -100,7 +101,7 @@"Get a list of API keys with the default scope. Non-paginated."[](api/check-superuser)- (let [api-keys (t2/hydrate (t2/select :model/ApiKey :scope nil) :group :updated_by)]+ (let [api-keys (t2/hydrate (api-keys.db/unscoped-api-keys) :group :updated_by)](map present-api-key api-keys)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -112,8 +113,8 @@[{:keys [id]} :- [:map[:id ::api-keys.schema/id]]](api/check-superuser)- (api/check-404 (t2/exists? :model/ApiKey id))- (t2/delete! :model/ApiKey id)+ (api/check-404 (api-keys.db/api-key-exists? id))+ (api-keys.db/delete-api-key! id)api/generic-204-no-content)(commentdiff --git a/src/metabase/api_keys/db.clj b/src/metabase/api_keys/db.cljnew file mode 100644index 00000000000..d1fa611140f--- /dev/null+++ b/src/metabase/api_keys/db.clj@@ -0,0 +1,86 @@+(ns metabase.api-keys.db+ "Application database queries for the API keys module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn unscoped-api-key-count+ "The number of ApiKeys without a scope."+ []+ (t2/count :model/ApiKey :scope nil))++(defn unscoped-api-keys+ "The ApiKeys without a scope."+ []+ (t2/select :model/ApiKey :scope nil))++(defn api-key+ "The ApiKey with `id`, or nil."+ [id]+ (t2/select-one :model/ApiKey id))++(defn save-api-key!+ "Save the changes made to the ApiKey instance `api-key`."+ [api-key]+ (t2/save! api-key))++(defn api-key-exists?+ "Whether an ApiKey with `id` exists."+ [id]+ (t2/exists? :model/ApiKey id))++(defn delete-api-key!+ "Delete the ApiKey with `id`."+ [id]+ (t2/delete! :model/ApiKey id))++(defn api-key-groups+ "The group name, group id, and api key id of the PermissionsGroups of the ApiKeys with `api-key-ids`."+ [api-key-ids]+ (t2/query {:select [[:pg.name :group-name]+ [:pg.id :group-id]+ [:api_key.id :api-key-id]]+ :from [[:permissions_group :pg]]+ :join [[:permissions_group_membership :pgm] [:= :pgm.group_id :pg.id]+ :api_key [:= :api_key.user_id :pgm.user_id]]+ :where [:in :api_key.id api-key-ids]}))++(defn rename-api-key-user!+ "Set the first name (and clear the last name) of the api-key User with `user-id`."+ [user-id first-name]+ (t2/update! :model/User :id user-id, :type :api-key, {:first_name first-name, :last_name ""}))++(defn user-type+ "The `:type` of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one-fn :type :model/User :id user-id))++(defn deactivate-api-key-user!+ "Deactivate the api-key User with `user-id`."+ [user-id]+ (t2/update! :model/User user-id, :type :api-key, {:is_active false}))++(defn api-key-prefix-exists?+ "Whether an ApiKey with `prefix` exists."+ [prefix]+ (t2/exists? :model/ApiKey :key_prefix prefix))++(defn api-key-name-exists?+ "Whether an ApiKey named `key-name` exists."+ [key-name]+ (t2/exists? :model/ApiKey :name key-name))++(defn insert-user!+ "Insert the User `row` and return its id."+ [row]+ (t2/insert-returning-pk! :model/User row))++(defn insert-api-key!+ "Insert the ApiKey `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/ApiKey row))++(defn update-api-key!+ "Apply `changes` to the ApiKey with `id`."+ [id changes]+ (t2/update! :model/ApiKey :id id changes))diff --git a/src/metabase/api_keys/models/api_key.clj b/src/metabase/api_keys/models/api_key.cljindex 8366b92d324..076d68e47a3 100644--- a/src/metabase/api_keys/models/api_key.clj+++ b/src/metabase/api_keys/models/api_key.clj@@ -6,6 +6,7 @@[java-time.api :as t][malli.error :as me][metabase.api-keys.core :as-alias api-keys]+ [metabase.api-keys.db :as api-keys.db][metabase.api-keys.schema :as api-keys.schema][metabase.api.common :as api][metabase.app-db.core :as mdb]@@ -35,13 +36,7 @@(when (seq api-keys)(let [api-key-id->permissions-groups(group-by :api-key-id- (t2/query {:select [[:pg.name :group-name]- [:pg.id :group-id]- [:api_key.id :api-key-id]]- :from [[:permissions_group :pg]]- :join [[:permissions_group_membership :pgm] [:= :pgm.group_id :pg.id]- :api_key [:= :api_key.user_id :pgm.user_id]]- :where [:in :api_key.id (map u/the-id api-keys)]}))+ (api-keys.db/api-key-groups (map u/the-id api-keys)))api-key-id->group(fn [api-key-id](let [{name :group-name@@ -138,10 +133,10 @@(let [key-before (t2/hydrate (t2/instance :model/ApiKey (t2/original api-key)) :user :group :updated_by)];; update the user name associated with this API key if it was created just for this API key.(when-let [new-name (:name (t2/changes api-key))]- (t2/update! :model/User :id user-id, :type :api-key, {:first_name new-name, :last_name ""}))+ (api-keys.db/rename-api-key-user! user-id new-name));; update user group as well.(when-let [new-group-id (::api-keys/group-id (t2/changes api-key))]- (assert (= (t2/select-one-fn :type :model/User :id user-id) :api-key)+ (assert (= (api-keys.db/user-type user-id) :api-key)"Cannot change the Permissions Group for the user associated with an API key that was not created alongside it")(user/set-permissions-groups! user-id [(perms/all-users-group) {:id new-group-id}]))(u/prog1 (-> api-key@@ -166,7 +161,7 @@(t2/hydrate :group)):user-id api/*current-user-id*});; if we created a user along with the key (type = :api-key), mark it inactive.- (t2/update! :model/User user-id, :type :api-key, {:is_active false})))+ (api-keys.db/deactivate-api-key-user! user-id)))(defn- add-masked-key [api-key](if-let [prefix (:key_prefix api-key)]@@ -185,7 +180,7 @@[(mdb/unique-identifier) user-id])}(fn is-api-key-user?*[user-id]- (= :api-key (t2/select-one-fn :type :model/User user-id)))+ (= :api-key (api-keys.db/user-type user-id)));; cache the results for 60 minutes; TTL is here only to eventually clear out old entries/keep it from growing too;; large:ttl/threshold (* 60 60 1000)))@@ -198,7 +193,7 @@prefix (prefix (u.secret/expose api-key))];; we could make this more efficient by generating 5 API keys up front and doing one select to remove any;; duplicates. But a duplicate should be rare enough to just do multiple queries for now.- (if-not (t2/exists? :model/ApiKey :key_prefix prefix)+ (if-not (api-keys.db/api-key-prefix-exists? prefix)api-key(throw (ex-info (tru "could not generate key with unique prefix") {}))))))@@ -208,24 +203,24 @@:- [:map {:closed true}[:key-name ::api-keys.schema/name][:group-id {:optional true} pos-int?]]]- (api/checkp (not (t2/exists? :model/ApiKey :name key-name))+ (api/checkp (not (api-keys.db/api-key-name-exists? key-name))"name" "An API key with this name already exists.")(let [unhashed-key (key-with-unique-prefix)email (format "api-key-user-%[email protected]" (random-uuid))](t2/with-transaction [_conn]- (let [user-id (t2/insert-returning-pk! :model/User- {:email email- :first_name key-name- :last_name ""- :type :api-key})]+ (let [user-id (api-keys.db/insert-user!+ {:email email+ :first_name key-name+ :last_name ""+ :type :api-key})](when group-id(user/set-permissions-groups! user-id [(perms/all-users-group) group-id]))- (-> (t2/insert-returning-instance! :model/ApiKey- {:user_id user-id- :name key-name- ::api-keys/unhashed-key unhashed-key- :updated_by_id api/*current-user-id*- :creator_id api/*current-user-id*})+ (-> (api-keys.db/insert-api-key!+ {:user_id user-id+ :name key-name+ ::api-keys/unhashed-key unhashed-key+ :updated_by_id api/*current-user-id*+ :creator_id api/*current-user-id*})(assoc :unmasked_key unhashed-key))))))(mu/defn regenerate! :- [:map@@ -234,13 +229,13 @@[:prefix ::api-keys.schema/prefix]]"Generate a new API key for an existing key with `id`."[id :- ::api-keys.schema/id]- (let [api-key-before (t2/select-one :model/ApiKey id)+ (let [api-key-before (api-keys.db/api-key id)new-key (key-with-unique-prefix)new-prefix (prefix new-key)](t2/with-transaction [_conn]- (t2/update! :model/ApiKey :id id {:key (hash-bcrypt new-key)- :key_prefix new-prefix- :updated_by_id api/*current-user-id*})+ (api-keys.db/update-api-key! id {:key (hash-bcrypt new-key)+ :key_prefix new-prefix+ :updated_by_id api/*current-user-id*})(events/publish-event! :event/api-key-regenerate(let [key-before (-> api-key-before(t2/hydrate :group))]diff --git a/src/metabase/appearance/db.clj b/src/metabase/appearance/db.cljnew file mode 100644index 00000000000..e6fdcd99ac4--- /dev/null+++ b/src/metabase/appearance/db.clj@@ -0,0 +1,10 @@+(ns metabase.appearance.db+ "Application database queries for the appearance module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn unarchived-dashboard-exists?+ "Whether an unarchived Dashboard with `dashboard-id` exists."+ [dashboard-id]+ (t2/exists? :model/Dashboard :id dashboard-id :archived false))diff --git a/src/metabase/appearance/settings.clj b/src/metabase/appearance/settings.cljindex ee8dfe36002..b4b7416350b 100644--- a/src/metabase/appearance/settings.clj+++ b/src/metabase/appearance/settings.clj@@ -2,11 +2,11 @@(:require[clojure.java.io :as io][clojure.string :as str]+ [metabase.appearance.db :as appearance.db][metabase.settings.core :as setting :refer [defsetting]][metabase.util :as u][metabase.util.fonts :as u.fonts]- [metabase.util.i18n :refer [deferred-tru tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [deferred-tru tru]]))(set! *warn-on-reflection* true)@@ -402,7 +402,7 @@ See [fonts](../configuring-metabase/fonts.md)."):setter :none:getter (fn [](let [id (setting/get-value-of-type :integer :example-dashboard-id)]- (when (and id (t2/exists? :model/Dashboard :id id :archived false))+ (when (and id (appearance.db/unarchived-dashboard-exists? id))id))):doc false)diff --git a/src/metabase/audit_app/db.clj b/src/metabase/audit_app/db.cljnew file mode 100644index 00000000000..da1cf1dd0c6--- /dev/null+++ b/src/metabase/audit_app/db.clj@@ -0,0 +1,64 @@+(ns metabase.audit-app.db+ "Application database queries for the audit app module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn cards+ "The Cards with `card-ids`."+ [card-ids]+ (t2/select :model/Card :id [:in card-ids]))++(defn audit-log-topic-exists?+ "Whether an AuditLog entry with `topic` exists."+ [topic]+ (t2/exists? :model/AuditLog :topic topic))++(defn collection-with-entity-id+ "The Collection with `entity-id`, or nil."+ [entity-id]+ (t2/select-one :model/Collection :entity_id entity-id))++(defn dashboard-with-entity-id+ "The Dashboard with `entity-id`, or nil."+ [entity-id]+ (t2/select-one :model/Dashboard :entity_id entity-id))++(defn card-name-and-description+ "The name and description of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :name :description :card_schema], :id card-id))++(defn table-database-id+ "The Database id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id :model/Table, :id table-id))++(defn insert-audit-log!+ "Insert an AuditLog entry."+ [topic details model-name model-id user-id]+ (t2/insert! :model/AuditLog+ :topic topic+ :details details+ :model model-name+ :model_id model-id+ :user_id user-id))++(defn delete-oldest-by-id-subquery!+ "Delete up to `batch-size` of the `table` rows whose `time-column` is at or before `cutoff`, lowest ids first."+ [table time-column cutoff batch-size]+ (t2/query-one {:delete-from table+ :where [:in+ :id+ ^:allow-subquery {:select [:id]+ :from table+ :where [:<= time-column cutoff]+ :order-by [[:id :asc]]+ :limit batch-size}]}))++(defn delete-oldest-with-limit!+ "Delete up to `batch-size` of the `table` rows whose `time-column` is at or before `cutoff`."+ [table time-column cutoff batch-size]+ (t2/query-one {:delete-from table+ :where [:<= time-column cutoff]+ :limit batch-size}))diff --git a/src/metabase/audit_app/events/audit_log.clj b/src/metabase/audit_app/events/audit_log.cljindex 1d43ad84622..10ae61f4e1a 100644--- a/src/metabase/audit_app/events/audit_log.clj+++ b/src/metabase/audit_app/events/audit_log.clj@@ -1,11 +1,11 @@(ns metabase.audit-app.events.audit-log"This namespace is responsible for publishing events to the audit log. "(:require+ [metabase.audit-app.db :as audit-app.db][metabase.audit-app.models.audit-log :as audit-log][metabase.events.core :as events][metabase.util :as u]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(events/derive! ::event :metabase/event)@@ -35,9 +35,9 @@;; we expect that the object has just a dashboard :id at the top level;; plus a `:dashcards` attribute which is a vector of the cards added/removed(let [cards (when (seq dashcards)- (t2/select-fn->fn :id #(select-keys % [:name :description])- :model/Card- :id [:in (map :card_id dashcards)]))+ (into {}+ (map (juxt :id #(select-keys % [:name :description])))+ (audit-app.db/cards (map :card_id dashcards))))details (-> (select-keys object [:description :name :id])(assoc :dashcards (for [{:keys [id card_id]} dashcards](-> (cards card_id)@@ -212,7 +212,7 @@(methodical/defmethod events/publish-event! ::install-event[topic _event]- (when-not (t2/exists? :model/AuditLog :topic "install")+ (when-not (audit-app.db/audit-log-topic-exists? "install")(audit-log/record-event! topic {})))(events/derive! ::database-event ::event)diff --git a/src/metabase/audit_app/impl.clj b/src/metabase/audit_app/impl.cljindex 733ef03d4c9..71d706e2c94 100644--- a/src/metabase/audit_app/impl.clj+++ b/src/metabase/audit_app/impl.clj@@ -3,8 +3,8 @@OSS product. EE-only code is located in `metabase-enterprise.audit-app.audit`."(:require[metabase.app-db.core :as mdb]- [metabase.audit-app.settings :as audit.settings]- [toucan2.core :as t2]))+ [metabase.audit-app.db :as audit-app.db]+ [metabase.audit-app.settings :as audit.settings]));; NOTE: Constants like `audit-db-id` and the entity IDs of audit collections are placed in OSS code because audit;; content may be loaded on an OSS build in the case of an EE->OSS downgrade. In these situations, we still need@@ -27,7 +27,9 @@(mdb/memoize-for-application-db(fn [checksum model entity-id](when checksum- (t2/select-one model :entity_id entity-id)))))+ (case model+ :model/Collection (audit-app.db/collection-with-entity-id entity-id)+ :model/Dashboard (audit-app.db/dashboard-with-entity-id entity-id))))))(defn memoized-select-audit-entity"Returns the object from entity id and model. Memoizes from entity id.diff --git a/src/metabase/audit_app/models/audit_log.clj b/src/metabase/audit_app/models/audit_log.cljindex d417daad083..d0b4dacdfc3 100644--- a/src/metabase/audit_app/models/audit_log.clj+++ b/src/metabase/audit_app/models/audit_log.clj@@ -6,6 +6,7 @@[clojure.data :as data][clojure.set :as set][metabase.api.common :as api]+ [metabase.audit-app.db :as audit-app.db][metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.util :as u]@@ -62,7 +63,7 @@(-> (select-keys dashboard [:description :name :parameters :dashcards])(update :dashcards (fn [dashcards](for [{:keys [id card_id]} dashcards]- (-> (t2/select-one [:model/Card :name :description :card_schema], :id card_id)+ (-> (audit-app.db/card-name-and-description card_id)(assoc :id id)(assoc :card_id card_id))))))@@ -115,7 +116,7 @@[metric _event-type](let [table-id (:table_id metric)db-id (when table-id- (t2/select-one-fn :db_id :model/Table, :id table-id))]+ (audit-app.db/table-database-id table-id))](assoc(select-keys metric [:name :description :revision_message]):table_id table-id@@ -242,12 +243,7 @@(:model params) (assoc :model/name (u/lower-case-en (:model params))))}(let [{:keys [user-id model-name model-id details unqualified-topic]}(construct-event topic params api/*current-user-id*)]- (t2/insert! :model/AuditLog- :topic unqualified-topic- :details details- :model model-name- :model_id model-id- :user_id user-id)))))+ (audit-app.db/insert-audit-log! unqualified-topic details model-name model-id user-id)))))(t2/define-before-insert :model/AuditLog[activity]diff --git a/src/metabase/audit_app/task/truncate_audit_tables.clj b/src/metabase/audit_app/task/truncate_audit_tables.cljindex 09b7448c66c..8a0844c5adb 100644--- a/src/metabase/audit_app/task/truncate_audit_tables.clj+++ b/src/metabase/audit_app/task/truncate_audit_tables.clj@@ -7,6 +7,7 @@[clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t][metabase.app-db.core :as mdb]+ [metabase.audit-app.db :as audit-app.db][metabase.audit-app.settings :as audit-app.settings][metabase.premium-features.core :refer [defenterprise]][metabase.task-history.core :as task-history]@@ -19,26 +20,14 @@(defn- truncate-table-batched![table-name time-column]- (t2/query-one- (case (mdb/db-type)- (:postgres :h2)- {:delete-from (keyword table-name)- :where [:in- :id- ^:allow-subquery {:select [:id]- :from (keyword table-name)- :where [:<=- (keyword time-column)- (t/minus (t/offset-date-time) (t/days (audit-app.settings/audit-max-retention-days)))]- :order-by [[:id :asc]]- :limit (audit-app.settings/audit-table-truncation-batch-size)}]}+ (let [cutoff (t/minus (t/offset-date-time) (t/days (audit-app.settings/audit-max-retention-days)))+ batch-size (audit-app.settings/audit-table-truncation-batch-size)]+ (case (mdb/db-type)+ (:postgres :h2)+ (audit-app.db/delete-oldest-by-id-subquery! (keyword table-name) (keyword time-column) cutoff batch-size)- (:mysql :mariadb)- {:delete-from (keyword table-name)- :where [:<=- (keyword time-column)- (t/minus (t/offset-date-time) (t/days (audit-app.settings/audit-max-retention-days)))]- :limit (audit-app.settings/audit-table-truncation-batch-size)})))+ (:mysql :mariadb)+ (audit-app.db/delete-oldest-with-limit! (keyword table-name) (keyword time-column) cutoff batch-size))))(defn- truncate-table!"Given a model, deletes all rows older than the configured threshold"diff --git a/src/metabase/auth_identity/db.clj b/src/metabase/auth_identity/db.cljnew file mode 100644index 00000000000..e08a3d53ae8--- /dev/null+++ b/src/metabase/auth_identity/db.clj@@ -0,0 +1,103 @@+(ns metabase.auth-identity.db+ "Application database queries for the auth identity module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn auth-identity+ "The AuthIdentity of the User with `user-id` at `provider`, or nil."+ [user-id provider]+ (t2/select-one :model/AuthIdentity :user_id user-id :provider provider))++(defn auth-identity-id+ "The id of the AuthIdentity of the User with `user-id` at `provider`, or nil."+ [user-id provider]+ (t2/select-one-pk :model/AuthIdentity :user_id user-id :provider provider))++(defn auth-identity-expiry+ "The id and expiry of the AuthIdentity of the User with `user-id` at `provider`, or nil."+ [user-id provider]+ (t2/select-one [:model/AuthIdentity :id :expires_at] :user_id user-id :provider provider))++(defn auth-identity-exists?+ "Whether the User with `user-id` has an AuthIdentity at `provider`."+ [user-id provider]+ (t2/exists? :model/AuthIdentity :user_id user-id :provider provider))++(defn insert-auth-identity!+ "Insert the AuthIdentity `row`."+ [row]+ (t2/insert! :model/AuthIdentity row))++(defn update-auth-identity!+ "Apply `changes` to the AuthIdentity with `id`."+ [id changes]+ (t2/update! :model/AuthIdentity id changes))++(defn touch-auth-identity!+ "Set `last_used_at` of the AuthIdentity with `id` to now."+ [id]+ (t2/update! :model/AuthIdentity id {:last_used_at :%now}))++(defn delete-auth-identities!+ "Delete the AuthIdentities of the User with `user-id` at `provider`."+ [user-id provider]+ (t2/delete! :model/AuthIdentity :user_id user-id :provider provider))++(defn delete-sessions-for-user!+ "Delete every Session of the User with `user-id`."+ [user-id]+ (t2/delete! :model/Session :user_id user-id))++(defn user+ "The User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User user-id))++(defn user-by-email+ "The User whose email matches `email` case-insensitively, or nil."+ [email]+ (t2/select-one :model/User :%lower.email (u/lower-case-en email)))++(defn user-login-columns+ "The id, active flag, last login, and tenant id of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id))++(defn user-login-columns-by-email+ "The id, active flag, last login, and tenant id of the User whose email matches `email` case-insensitively, or+ nil."+ [email]+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :%lower.email (u/lower-case-en email)))++(defn user-login-status+ "The id, active flag, and last login of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :id :is_active :last_login] user-id))++(defn user-active?+ "Whether the User with `user-id` is active."+ [user-id]+ (t2/select-one-fn :is_active :model/User :id user-id))++(defn update-user!+ "Apply `changes` to the User with `user-id`."+ [user-id changes]+ (t2/update! :model/User user-id changes))++(defn insert-user-returning-login-columns!+ "Insert the User `row` and return its id, last login, active flag, and tenant id."+ [row]+ (t2/insert-returning-instance! [:model/User :id :last_login :is_active :tenant_id] row))++(defn insert-session!+ "Insert a Session and return the inserted instance."+ [session-id user-id auth-identity-id session-key expires-at]+ (t2/insert-returning-instance! :model/Session+ ;; Without setting the ID here we can't return an instance on MySQL+ :id session-id+ :user_id user-id+ :auth_identity_id auth-identity-id+ :session_key session-key+ :expires_at expires-at))diff --git a/src/metabase/auth_identity/models/auth_identity.clj b/src/metabase/auth_identity/models/auth_identity.cljindex 91360b4b135..c7d2cadd8da 100644--- a/src/metabase/auth_identity/models/auth_identity.clj+++ b/src/metabase/auth_identity/models/auth_identity.clj@@ -3,6 +3,7 @@for a User - a User can have multiple AuthIdentities (e.g., password + SSO)."(:require[java-time.api :as t]+ [metabase.auth-identity.db :as auth-identity.db][metabase.auth-identity.provider :as provider][metabase.models.interface :as mi][metabase.util :as u]@@ -119,16 +120,16 @@(t2/with-transaction [_](let [attrs {:credentials {:plaintext_password password}:expires_at (:expires-at opts)}]- (if-let [pw-auth-identity (t2/select-one :model/AuthIdentity :user_id user-id :provider "password")]- (t2/update! :model/AuthIdentity (u/the-id pw-auth-identity) attrs)- (t2/insert! :model/AuthIdentity (merge {:user_id user-id, :provider "password"} attrs))))- (t2/delete! :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset")- (t2/delete! :model/Session :user_id user-id))))+ (if-let [pw-auth-identity (auth-identity.db/auth-identity user-id "password")]+ (auth-identity.db/update-auth-identity! (u/the-id pw-auth-identity) attrs)+ (auth-identity.db/insert-auth-identity! (merge {:user_id user-id, :provider "password"} attrs))))+ (auth-identity.db/delete-auth-identities! user-id "emailed-secret-password-reset")+ (auth-identity.db/delete-sessions-for-user! user-id))))(mu/defn reset-token-hash :- [:maybe :string]"The bcrypt hash of `user-id`'s current password-reset token, taken from their `emailed-secret-password-reset`AuthIdentity (the authoritative store), or nil if they have none. Lets callers include the token in audit eventswithout reading the legacy `core_user.reset_token` column."[user-id :- ms/PositiveInt]- (get-in (t2/select-one :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset")+ (get-in (auth-identity.db/auth-identity user-id "emailed-secret-password-reset")[:credentials :token_hash]))diff --git a/src/metabase/auth_identity/provider.clj b/src/metabase/auth_identity/provider.cljindex 6051bb4d0e2..9aa63410fcd 100644--- a/src/metabase/auth_identity/provider.clj+++ b/src/metabase/auth_identity/provider.clj@@ -52,6 +52,7 @@- metabase-enterprise.sso.providers.saml (Enterprise)"(:require[java-time.api :as t]+ [metabase.auth-identity.db :as auth-identity.db][metabase.auth-identity.session :as auth-session][metabase.events.core :as events][metabase.notification.core :as notification]@@ -307,11 +308,11 @@(assoc :user(or (when-let [user-id (:user-id $)](if (pos-int? user-id)- (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id)+ (auth-identity.db/user-login-columns user-id)(log/errorf "Provider %s returned a non-positive-int :user-id (type %s); refusing to resolve a user."provider (some-> user-id class .getName))))(when-let [email (get-in $ [:user-data :email])]- (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :%lower.email (u/lower-case-en email))))))+ (auth-identity.db/user-login-columns-by-email email)))))(cond-> $(and (:provider-id $) (:user-data $))(assoc-in [:user-data :provider-id] (:provider-id $)))@@ -348,14 +349,14 @@provider :- :keyword](t2/with-transaction [_](let [reactivating? (and (:is_active user-data)- (not (t2/select-one-fn :is_active :model/User :id user-id)))]- (t2/update! :model/User user-id- (cond-> (select-keys user-data (conj (sso-user-fields) :is_active))- reactivating? (assoc :is_superuser false))))- (when-not (t2/exists? :model/AuthIdentity :user_id user-id :provider (name provider))- (t2/insert! :model/AuthIdentity (cond-> {:user_id user-id :provider (name provider)}- (:provider-id user-data) (assoc :provider_id (:provider-id user-data)))))- (t2/select-one [:model/User :id :is_active :last_login] user-id)))+ (not (auth-identity.db/user-active? user-id)))]+ (auth-identity.db/update-user! user-id+ (cond-> (select-keys user-data (conj (sso-user-fields) :is_active))+ reactivating? (assoc :is_superuser false))))+ (when-not (auth-identity.db/auth-identity-exists? user-id (name provider))+ (auth-identity.db/insert-auth-identity! (cond-> {:user_id user-id :provider (name provider)}+ (:provider-id user-data) (assoc :provider_id (:provider-id user-data)))))+ (auth-identity.db/user-login-status user-id)))(mu/defn- create-user!"Create a user from user-data in the request "@@ -380,12 +381,11 @@{:status-code 500})))(t2/with-transaction [_](u/prog1- (t2/insert-returning-instance! [:model/User :id :last_login :is_active :tenant_id]- (select-keys user-data insert-fields))- (t2/insert! :model/AuthIdentity (cond-> {:user_id (:id <>) :provider (name provider)}- (:provider-id user-data) (assoc :provider_id (:provider-id user-data))))+ (auth-identity.db/insert-user-returning-login-columns! (select-keys user-data insert-fields))+ (auth-identity.db/insert-auth-identity! (cond-> {:user_id (:id <>) :provider (name provider)}+ (:provider-id user-data) (assoc :provider_id (:provider-id user-data))))(notification/with-skip-sending-notification true- (events/publish-event! :event/user-invited {:object (assoc (t2/select-one :model/User (:id <>))+ (events/publish-event! :event/user-invited {:object (assoc (auth-identity.db/user (:id <>)):sso_source (name provider))}))))))(methodical/defmethod login! ::create-user-if-not-existsdiff --git a/src/metabase/auth_identity/providers/emailed_secret.clj b/src/metabase/auth_identity/providers/emailed_secret.cljindex 39676ae040d..2f53cada7e9 100644--- a/src/metabase/auth_identity/providers/emailed_secret.clj+++ b/src/metabase/auth_identity/providers/emailed_secret.clj@@ -2,6 +2,7 @@"Provider for emailed secret tokens (password reset, email verification, magic links)."(:require[java-time.api :as t]+ [metabase.auth-identity.db :as auth-identity.db][metabase.auth-identity.models.auth-identity :as auth-identity][metabase.auth-identity.provider :as provider][metabase.channel.email.messages :as messages]@@ -105,15 +106,15 @@[user-id :- ms/PositiveInt](u/prog1 (generate-reset-token user-id)(t2/with-transaction [_]- (let [user (t2/select-one :model/User user-id)+ (let [user (auth-identity.db/user user-id)auth-identity {:user_id user-id:provider "emailed-secret-password-reset":provider_id (:email user):credentials (create-reset-token-credentials <>):metadata (create-reset-token-metadata (:email user))}]- (if-let [auth-identity-id (t2/select-one-pk :model/AuthIdentity :user_id user-id :provider "emailed-secret-password-reset")]- (t2/update! :model/AuthIdentity auth-identity-id auth-identity)- (t2/insert! :model/AuthIdentity auth-identity))))))+ (if-let [auth-identity-id (auth-identity.db/auth-identity-id user-id "emailed-secret-password-reset")]+ (auth-identity.db/update-auth-identity! auth-identity-id auth-identity)+ (auth-identity.db/insert-auth-identity! auth-identity))))));;; -------------------------------------------------- Provider Registration --------------------------------------------------@@ -143,9 +144,7 @@:else(try(if-let [user-id (parse-token-user-id token)]- (if-let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider (name provider))]+ (if-let [auth-identity (auth-identity.db/auth-identity user-id (name provider))](let [verification-result (verify-reset-token token (:credentials auth-identity))](case verification-result:valid@@ -189,6 +188,6 @@(when (:success? result)(if (:last_login user)(events/publish-event! :event/password-reset-successful {:object (assoc user :token (auth-identity/reset-token-hash (:id user)))})- (messages/send-user-joined-admin-notification-email! (t2/select-one :model/User (:id user))))+ (messages/send-user-joined-admin-notification-email! (auth-identity.db/user (:id user))))(auth-identity/set-password! (:id user) password))result)diff --git a/src/metabase/auth_identity/providers/password.clj b/src/metabase/auth_identity/providers/password.cljindex d569f82697e..1f1d78f5fd7 100644--- a/src/metabase/auth_identity/providers/password.clj+++ b/src/metabase/auth_identity/providers/password.clj@@ -1,14 +1,13 @@(ns metabase.auth-identity.providers.password"Password authentication provider implementation."(:require+ [metabase.auth-identity.db :as auth-identity.db][metabase.auth-identity.provider :as provider]- [metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][metabase.util.password :as u.password]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(set! *warn-on-reflection* true)@@ -40,10 +39,8 @@(mu/defn- find-auth-identity-by-email"Find an AuthIdentity record by email address."[email :- ms/NonBlankString]- (when-let [user (t2/select-one :model/User :%lower.email (u/lower-case-en email))]- (t2/select-one :model/AuthIdentity- :user_id (:id user)- :provider "password")))+ (when-let [user (auth-identity.db/user-by-email email)]+ (auth-identity.db/auth-identity (:id user) "password")))(methodical/defmethod provider/authenticate :provider/password"Authenticate a user with email and password.diff --git a/src/metabase/auth_identity/session.clj b/src/metabase/auth_identity/session.cljindex 3653da6abce..a91e08f8d2a 100644--- a/src/metabase/auth_identity/session.clj+++ b/src/metabase/auth_identity/session.clj@@ -2,6 +2,7 @@"Integration between AuthIdentity and Session systems. Provides wrappers aroundsession creation that track authentication provider usage."(:require+ [metabase.auth-identity.db :as auth-identity.db][metabase.login-history.core :as login-history][metabase.request.core :as request][metabase.util :as u]@@ -21,24 +22,15 @@[user device-info provider](let [user-id (u/the-id user)provider-str (name provider)- auth-identity (t2/select-one [:model/AuthIdentity :id :expires_at]- :user_id user-id- :provider provider-str)+ auth-identity (auth-identity.db/auth-identity-expiry user-id provider-str)auth-identity-id (:id auth-identity)session-key (str (random-uuid))session-id (string/random-string 12)session (t2/with-transaction [_]- (u/prog1 (t2/insert-returning-instance! :model/Session- ;; Without setting the ID here we can't return an instance- ;; on MySQL- :id session-id- :user_id user-id- :auth_identity_id auth-identity-id- :session_key session-key- :expires_at (:expires_at auth-identity))+ (u/prog1 (auth-identity.db/insert-session! session-id user-id auth-identity-id session-key (:expires_at auth-identity))(when provider-str(log/debugf "Updating last_used_at for user %s with provider %s" user-id provider-str)- (t2/update! :model/AuthIdentity auth-identity-id {:last_used_at :%now}))+ (auth-identity.db/touch-auth-identity! auth-identity-id))(when device-info(login-history/record-login-history! session-id user device-info))))](assoc sessiondiff --git a/src/metabase/bookmarks/api.clj b/src/metabase/bookmarks/api.cljindex 8311c22879c..ce8b7d28de3 100644--- a/src/metabase/bookmarks/api.clj+++ b/src/metabase/bookmarks/api.clj@@ -7,9 +7,9 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.bookmarks.db :as bookmarks.db][metabase.bookmarks.models.bookmark :as bookmark]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(def Models"Schema enumerating bookmarkable models."@@ -22,13 +22,37 @@[:type Models][:item_id ms/PositiveInt]]])-(def ^:private lookup- "Lookup map from model as a string to [model bookmark-model item-id-key]."- {"card" [:model/Card :model/CardBookmark :card_id]- "dashboard" [:model/Dashboard :model/DashboardBookmark :dashboard_id]- "collection" [:model/Collection :model/CollectionBookmark :collection_id]- "document" [:model/Document :model/DocumentBookmark :document_id]- "exploration" [:model/Exploration :model/ExplorationBookmark :exploration_id]})+(def ^:private item-model+ "Lookup map from model as a string to the underlying item model, for read-checks."+ {"card" :model/Card+ "dashboard" :model/Dashboard+ "collection" :model/Collection+ "document" :model/Document+ "exploration" :model/Exploration})++(defn- bookmark-exists? [model id user-id]+ (case model+ "card" (bookmarks.db/card-bookmark-exists? id user-id)+ "dashboard" (bookmarks.db/dashboard-bookmark-exists? id user-id)+ "collection" (bookmarks.db/collection-bookmark-exists? id user-id)+ "document" (bookmarks.db/document-bookmark-exists? id user-id)+ "exploration" (bookmarks.db/exploration-bookmark-exists? id user-id)))++(defn- insert-bookmark! [model id user-id]+ (case model+ "card" (bookmarks.db/insert-card-bookmark! id user-id)+ "dashboard" (bookmarks.db/insert-dashboard-bookmark! id user-id)+ "collection" (bookmarks.db/insert-collection-bookmark! id user-id)+ "document" (bookmarks.db/insert-document-bookmark! id user-id)+ "exploration" (bookmarks.db/insert-exploration-bookmark! id user-id)))++(defn- delete-bookmark! [model id user-id]+ (case model+ "card" (bookmarks.db/delete-card-bookmark! id user-id)+ "dashboard" (bookmarks.db/delete-dashboard-bookmark! id user-id)+ "collection" (bookmarks.db/delete-collection-bookmark! id user-id)+ "document" (bookmarks.db/delete-document-bookmark! id user-id)+ "exploration" (bookmarks.db/delete-exploration-bookmark! id user-id)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -50,12 +74,10 @@[{:keys [model id]} :- [:map[:model Models][:id ms/PositiveInt]]]- (let [[item-model bookmark-model item-key] (lookup model)]- (api/read-check item-model id)- (api/check (not (t2/exists? bookmark-model item-key id- :user_id api/*current-user-id*))- [400 "Bookmark already exists"])- (first (t2/insert-returning-instances! bookmark-model {item-key id :user_id api/*current-user-id*}))))+ (api/read-check (item-model model) id)+ (api/check (not (bookmark-exists? model id api/*current-user-id*))+ [400 "Bookmark already exists"])+ (insert-bookmark! model id api/*current-user-id*));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -67,11 +89,8 @@[:model Models][:id ms/PositiveInt]]];; todo: allow admins to include an optional user id to delete for so they can delete other's bookmarks.- (let [[_ bookmark-model item-key] (lookup model)]- (t2/delete! bookmark-model- :user_id api/*current-user-id*- item-key id)- api/generic-204-no-content))+ (delete-bookmark! model id api/*current-user-id*)+ api/generic-204-no-content);; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/bookmarks/db.clj b/src/metabase/bookmarks/db.cljnew file mode 100644index 00000000000..8e0d1a400a1--- /dev/null+++ b/src/metabase/bookmarks/db.clj@@ -0,0 +1,220 @@+(ns metabase.bookmarks.db+ "Application database queries for the bookmarks module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.collections.models.collection :as collection]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn card-bookmark-exists?+ "Whether the User with `user-id` has a CardBookmark for the Card with `card-id`."+ [card-id user-id]+ (t2/exists? :model/CardBookmark :card_id card-id :user_id user-id))++(defn dashboard-bookmark-exists?+ "Whether the User with `user-id` has a DashboardBookmark for the Dashboard with `dashboard-id`."+ [dashboard-id user-id]+ (t2/exists? :model/DashboardBookmark :dashboard_id dashboard-id :user_id user-id))++(defn collection-bookmark-exists?+ "Whether the User with `user-id` has a CollectionBookmark for the Collection with `collection-id`."+ [collection-id user-id]+ (t2/exists? :model/CollectionBookmark :collection_id collection-id :user_id user-id))++(defn document-bookmark-exists?+ "Whether the User with `user-id` has a DocumentBookmark for the Document with `document-id`."+ [document-id user-id]+ (t2/exists? :model/DocumentBookmark :document_id document-id :user_id user-id))++(defn exploration-bookmark-exists?+ "Whether the User with `user-id` has an ExplorationBookmark for the Exploration with `exploration-id`."+ [exploration-id user-id]+ (t2/exists? :model/ExplorationBookmark :exploration_id exploration-id :user_id user-id))++(defn insert-card-bookmark!+ "Insert a CardBookmark for the Card with `card-id` and the User with `user-id`, returning the inserted instance."+ [card-id user-id]+ (t2/insert-returning-instance! :model/CardBookmark {:card_id card-id :user_id user-id}))++(defn insert-dashboard-bookmark!+ "Insert a DashboardBookmark for the Dashboard with `dashboard-id` and the User with `user-id`, returning the+ inserted instance."+ [dashboard-id user-id]+ (t2/insert-returning-instance! :model/DashboardBookmark {:dashboard_id dashboard-id :user_id user-id}))++(defn insert-collection-bookmark!+ "Insert a CollectionBookmark for the Collection with `collection-id` and the User with `user-id`, returning the+ inserted instance."+ [collection-id user-id]+ (t2/insert-returning-instance! :model/CollectionBookmark {:collection_id collection-id :user_id user-id}))++(defn insert-document-bookmark!+ "Insert a DocumentBookmark for the Document with `document-id` and the User with `user-id`, returning the inserted+ instance."+ [document-id user-id]+ (t2/insert-returning-instance! :model/DocumentBookmark {:document_id document-id :user_id user-id}))++(defn insert-exploration-bookmark!+ "Insert an ExplorationBookmark for the Exploration with `exploration-id` and the User with `user-id`, returning the+ inserted instance."+ [exploration-id user-id]+ (t2/insert-returning-instance! :model/ExplorationBookmark {:exploration_id exploration-id :user_id user-id}))++(defn delete-card-bookmark!+ "Delete the CardBookmark of the User with `user-id` for the Card with `card-id`."+ [card-id user-id]+ (t2/delete! :model/CardBookmark :card_id card-id :user_id user-id))++(defn delete-dashboard-bookmark!+ "Delete the DashboardBookmark of the User with `user-id` for the Dashboard with `dashboard-id`."+ [dashboard-id user-id]+ (t2/delete! :model/DashboardBookmark :dashboard_id dashboard-id :user_id user-id))++(defn delete-collection-bookmark!+ "Delete the CollectionBookmark of the User with `user-id` for the Collection with `collection-id`."+ [collection-id user-id]+ (t2/delete! :model/CollectionBookmark :collection_id collection-id :user_id user-id))++(defn delete-document-bookmark!+ "Delete the DocumentBookmark of the User with `user-id` for the Document with `document-id`."+ [document-id user-id]+ (t2/delete! :model/DocumentBookmark :document_id document-id :user_id user-id))++(defn delete-exploration-bookmark!+ "Delete the ExplorationBookmark of the User with `user-id` for the Exploration with `exploration-id`."+ [exploration-id user-id]+ (t2/delete! :model/ExplorationBookmark :exploration_id exploration-id :user_id user-id))++(defn delete-bookmark-orderings-for-user!+ "Delete the BookmarkOrderings of the User with `user-id`."+ [user-id]+ (t2/delete! :model/BookmarkOrdering :user_id user-id))++(defn insert-bookmark-orderings!+ "Insert the BookmarkOrdering `rows`."+ [rows]+ (t2/insert! :model/BookmarkOrdering rows))++(defn- bookmarks-union-query+ [user-id]+ (let [as-null (when (= (mdb/db-type) :postgres) (h2x/->integer nil))+ base-queries [^:allow-subquery {:select [:card_id+ [as-null :dashboard_id]+ [as-null :collection_id]+ [as-null :document_id]+ [as-null :exploration_id]+ [:card_id :item_id]+ [(h2x/literal "card") :type]+ :created_at]+ :from [:card_bookmark]+ :where [:= :user_id user-id]}+ ^:allow-subquery {:select [[as-null :card_id]+ :dashboard_id+ [as-null :collection_id]+ [as-null :document_id]+ [as-null :exploration_id]+ [:dashboard_id :item_id]+ [(h2x/literal "dashboard") :type]+ :created_at]+ :from [:dashboard_bookmark]+ :where [:= :user_id user-id]}+ ^:allow-subquery {:select [[as-null :card_id]+ [as-null :dashboard_id]+ :collection_id+ [as-null :document_id]+ [as-null :exploration_id]+ [:collection_id :item_id]+ [(h2x/literal "collection") :type]+ :created_at]+ :from [:collection_bookmark]+ :where [:= :user_id user-id]}+ ^:allow-subquery {:select [[as-null :card_id]+ [as-null :dashboard_id]+ [as-null :collection_id]+ :document_id+ [as-null :exploration_id]+ [:document_id :item_id]+ [(h2x/literal "document") :type]+ :created_at]+ :from [:document_bookmark]+ :where [:= :user_id user-id]}]]+ {:union-all (conj base-queries+ ^:allow-subquery {:select [[as-null :card_id]+ [as-null :dashboard_id]+ [as-null :collection_id]+ [as-null :document_id]+ :exploration_id+ [:exploration_id :item_id]+ [(h2x/literal "exploration") :type]+ :created_at]+ :from [:exploration_bookmark]+ :where [:= :user_id user-id]})}))++(defn bookmark-rows-for-user+ "The bookmarks of the User with `user-id`, joined against the Card, Dashboard, Collection, Document, and Exploration+ tables, excluding archived items, and filtered to items the target `user-scope` (a map of `:current-user-id` and+ `:is-superuser?`) can still read (re-checked at read time rather than trusted from when the bookmark was created,+ see SEC-669). The `collection_id` join uses [[h2x/identifier]] to work around+ https://github.com/seancorfield/honeysql/issues/450."+ [user-id user-scope]+ (let [select-fields [[:bookmark.created_at :created_at]+ [:bookmark.type :type]+ [:bookmark.item_id :item_id]+ [:card.name :report_card.name]+ [:card.type :report_card.card_type]+ [:card.display :report_card.display]+ [:card.description :report_card.description]+ [:card.archived :report_card.archived]+ [:dashboard.name :report_dashboard.name]+ [:dashboard.description :report_dashboard.description]+ [:dashboard.archived :report_dashboard.archived]+ [:collection.name :collection.name]+ [:collection.authority_level :collection.authority_level]+ [:collection.is_remote_synced :collection.is_remote_synced]+ [:collection.description :collection.description]+ [:collection.archived :collection.archived]+ [:document.name :document.name]+ [:document.archived :document.archived]+ [:exploration.name :exploration.name]+ [:exploration.description :exploration.description]+ [:exploration.archived :exploration.archived]]+ left-joins [[:report_card :card] [:= :bookmark.card_id :card.id]+ [:report_dashboard :dashboard] [:= :bookmark.dashboard_id :dashboard.id]+ [:collection :collection] [:in :collection.id [(h2x/identifier :field :bookmark :collection_id)+ (h2x/identifier :field :dashboard :collection_id)]]+ [:bookmark_ordering :bookmark_ordering] [:and+ [:= :bookmark_ordering.user_id user-id]+ [:= :bookmark_ordering.type :bookmark.type]+ [:= :bookmark_ordering.item_id :bookmark.item_id]]+ [:document :document] [:= :bookmark.document_id :document.id]+ [:exploration :exploration] [:= :bookmark.exploration_id :exploration.id]]+ where-conditions (into [:and]+ (for [table [:card :dashboard :collection :document :exploration]+ :let [field (keyword (str (name table) "." "archived"))]]+ [:or [:= field false] [:= field nil]]))+ visible? (fn [collection-id-field]+ (collection/visible-collection-filter-clause collection-id-field+ {:cte-name :visible_collection_ids}+ user-scope))+ readable-conditions [:or+ [:and [:= :bookmark.type (h2x/literal "card")] (visible? :card.collection_id)]+ [:and [:= :bookmark.type (h2x/literal "dashboard")] (visible? :dashboard.collection_id)]+ [:and [:= :bookmark.type (h2x/literal "collection")] (visible? :collection.id)]+ [:and [:= :bookmark.type (h2x/literal "document")] (visible? :document.collection_id)]+ [:and [:= :bookmark.type (h2x/literal "exploration")] (visible? :exploration.collection_id)]]]+ (mdb/query+ {:with [[:visible_collection_ids (collection/visible-collection-query+ {:include-archived-items :all+ :permission-level :read}+ user-scope)]]+ :select select-fields+ :from [[(bookmarks-union-query user-id) :bookmark]]+ :left-join left-joins+ :where [:and where-conditions readable-conditions]+ :order-by [[:bookmark_ordering.ordering (case (mdb/db-type)+ ;; NULLS LAST is not supported by MySQL, but this is default+ ;; behavior for MySQL anyway+ (:postgres :h2) :asc-nulls-last+ :mysql :asc)]+ [:created_at :desc]]})))diff --git a/src/metabase/bookmarks/models/bookmark.clj b/src/metabase/bookmarks/models/bookmark.cljindex ffd035388a1..3bfef73dc6f 100644--- a/src/metabase/bookmarks/models/bookmark.clj+++ b/src/metabase/bookmarks/models/bookmark.clj@@ -1,11 +1,10 @@(ns metabase.bookmarks.models.bookmark(:require[clojure.string :as str]- [metabase.app-db.core :as mdb]+ [metabase.bookmarks.db :as bookmarks.db][metabase.collections.models.collection :as collection][metabase.permissions.core :as perms][metabase.queries.schema :as queries.schema]- [metabase.util.honey-sql-2 :as h2x][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][methodical.core :as methodical]@@ -70,61 +69,6 @@:authority_level :is_remote_synced])(assoc :id id-str))))-(defn- bookmarks-union-query- [user-id]- (let [as-null (when (= (mdb/db-type) :postgres) (h2x/->integer nil))- base-queries [^:allow-subquery {:select [:card_id- [as-null :dashboard_id]- [as-null :collection_id]- [as-null :document_id]- [as-null :exploration_id]- [:card_id :item_id]- [(h2x/literal "card") :type]- :created_at]- :from [:card_bookmark]- :where [:= :user_id user-id]}- ^:allow-subquery {:select [[as-null :card_id]- :dashboard_id- [as-null :collection_id]- [as-null :document_id]- [as-null :exploration_id]- [:dashboard_id :item_id]- [(h2x/literal "dashboard") :type]- :created_at]- :from [:dashboard_bookmark]- :where [:= :user_id user-id]}- ^:allow-subquery {:select [[as-null :card_id]- [as-null :dashboard_id]- :collection_id- [as-null :document_id]- [as-null :exploration_id]- [:collection_id :item_id]- [(h2x/literal "collection") :type]- :created_at]- :from [:collection_bookmark]- :where [:= :user_id user-id]}- ^:allow-subquery {:select [[as-null :card_id]- [as-null :dashboard_id]- [as-null :collection_id]- :document_id- [as-null :exploration_id]- [:document_id :item_id]- [(h2x/literal "document") :type]- :created_at]- :from [:document_bookmark]- :where [:= :user_id user-id]}]]- {:union-all (conj base-queries- ^:allow-subquery {:select [[as-null :card_id]- [as-null :dashboard_id]- [as-null :collection_id]- [as-null :document_id]- :exploration_id- [:exploration_id :item_id]- [(h2x/literal "exploration") :type]- :created_at]- :from [:exploration_bookmark]- :where [:= :user_id user-id]})}))-(mu/defn bookmarks-for-user :- [:sequential BookmarkResult]"Get all bookmarks for a user. Each bookmark will have a string id made of the model and model-id, a type, anditem_id, name, and description from the underlying bookmarked item.@@ -132,80 +76,18 @@Bookmarks whose target `user-id` can no longer read are filtered out."[user-id](let [user-scope {:current-user-id user-id- :is-superuser? (perms/is-superuser? user-id)}- select-fields [[:bookmark.created_at :created_at]- [:bookmark.type :type]- [:bookmark.item_id :item_id]- [:card.name (mdb/qualify :model/Card :name)]- [:card.type (mdb/qualify :model/Card :card_type)]- [:card.display (mdb/qualify :model/Card :display)]- [:card.description (mdb/qualify :model/Card :description)]- [:card.archived (mdb/qualify :model/Card :archived)]- [:dashboard.name (mdb/qualify :model/Dashboard :name)]- [:dashboard.description (mdb/qualify :model/Dashboard :description)]- [:dashboard.archived (mdb/qualify :model/Dashboard :archived)]- [:collection.name (mdb/qualify :model/Collection :name)]- [:collection.authority_level (mdb/qualify :model/Collection :authority_level)]- [:collection.is_remote_synced (mdb/qualify :model/Collection :is_remote_synced)]- [:collection.description (mdb/qualify :model/Collection :description)]- [:collection.archived (mdb/qualify :model/Collection :archived)]- [:document.name (mdb/qualify :model/Document :name)]- [:document.archived (mdb/qualify :model/Document :archived)]- [:exploration.name (mdb/qualify :model/Exploration :name)]- [:exploration.description (mdb/qualify :model/Exploration :description)]- [:exploration.archived (mdb/qualify :model/Exploration :archived)]]- left-joins [[:report_card :card] [:= :bookmark.card_id :card.id]- [:report_dashboard :dashboard] [:= :bookmark.dashboard_id :dashboard.id]- ;; use of [[h2x/identifier]] here is a workaround for https://github.com/seancorfield/honeysql/issues/450- [:collection :collection] [:in :collection.id [(h2x/identifier :field :bookmark :collection_id)- (h2x/identifier :field :dashboard :collection_id)]]- [:bookmark_ordering :bookmark_ordering] [:and- [:= :bookmark_ordering.user_id user-id]- [:= :bookmark_ordering.type :bookmark.type]- [:= :bookmark_ordering.item_id :bookmark.item_id]]- [:document :document] [:= :bookmark.document_id :document.id]- [:exploration :exploration] [:= :bookmark.exploration_id :exploration.id]]- where-conditions (into [:and]- (for [table [:card :dashboard :collection :document :exploration]- :let [field (keyword (str (name table) "." "archived"))]]- [:or [:= field false] [:= field nil]]))- ;; Re-check read permission at read time (SEC-669). The `:visible_collection_ids` CTE governs *permissions*- ;; only (`:include-archived-items :all`); the `where-conditions` above keep governing archived filtering.- visible? (fn [collection-id-field]- (collection/visible-collection-filter-clause collection-id-field- {:cte-name :visible_collection_ids}- user-scope))- readable-conditions [:or- [:and [:= :bookmark.type (h2x/literal "card")] (visible? :card.collection_id)]- [:and [:= :bookmark.type (h2x/literal "dashboard")] (visible? :dashboard.collection_id)]- [:and [:= :bookmark.type (h2x/literal "collection")] (visible? :collection.id)]- [:and [:= :bookmark.type (h2x/literal "document")] (visible? :document.collection_id)]- [:and [:= :bookmark.type (h2x/literal "exploration")] (visible? :exploration.collection_id)]]]- (->> (mdb/query- {:with [[:visible_collection_ids (collection/visible-collection-query- {:include-archived-items :all- :permission-level :read}- user-scope)]]- :select select-fields- :from [[(bookmarks-union-query user-id) :bookmark]]- :left-join left-joins- :where [:and where-conditions readable-conditions]- :order-by [[:bookmark_ordering.ordering (case (mdb/db-type)- ;; NULLS LAST is not supported by MySQL, but this is default- ;; behavior for MySQL anyway- (:postgres :h2) :asc-nulls-last- :mysql :asc)]- [:created_at :desc]]})+ :is-superuser? (perms/is-superuser? user-id)}]+ (->> (bookmarks.db/bookmark-rows-for-user user-id user-scope)(map normalize-bookmark-result))))(defn save-ordering!"Saves a bookmark ordering of shape `[{:type, :item_id}]`Deletes all existing orderings for user so should be given a total ordering."[user-id orderings]- (t2/delete! :model/BookmarkOrdering :user_id user-id)- (t2/insert! :model/BookmarkOrdering (->> orderings- (map #(select-keys % [:type :item_id]))- (map-indexed #(assoc %2 :user_id user-id :ordering %1)))))+ (bookmarks.db/delete-bookmark-orderings-for-user! user-id)+ (bookmarks.db/insert-bookmark-orderings! (->> orderings+ (map #(select-keys % [:type :item_id]))+ (map-indexed #(assoc %2 :user_id user-id :ordering %1)))))(t2/define-before-insert :model/CollectionBookmark [bookmark](collection/check-allowed-content :model/CollectionBookmark (:collection_id bookmark))diff --git a/src/metabase/bug_reporting/api.clj b/src/metabase/bug_reporting/api.cljindex ec05bca6828..68d0054eae8 100644--- a/src/metabase/bug_reporting/api.clj+++ b/src/metabase/bug_reporting/api.clj@@ -3,6 +3,7 @@[metabase.analytics.core :as analytics][metabase.api.macros :as api.macros][metabase.app-db.core :as mdb]+ [metabase.bug-reporting.db :as bug-reporting.db][metabase.config.core :as config][metabase.driver :as driver][metabase.permissions.core :as perms]@@ -17,7 +18,7 @@"Make it easy for the user to tell us what they're using"[](merge- {:databases (t2/select-fn-set :engine :model/Database)+ {:databases (bug-reporting.db/database-engines):run-mode (config/config-kw :mb-run-mode):plan-alias (or (premium-features/plan-alias) ""):version config/mb-version-infodiff --git a/src/metabase/bug_reporting/db.clj b/src/metabase/bug_reporting/db.cljnew file mode 100644index 00000000000..7eafaa29df0--- /dev/null+++ b/src/metabase/bug_reporting/db.clj@@ -0,0 +1,10 @@+(ns metabase.bug-reporting.db+ "Application database queries for the bug reporting module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn database-engines+ "The set of engines of all Databases."+ []+ (t2/select-fn-set :engine :model/Database))diff --git a/src/metabase/cache/api.clj b/src/metabase/cache/api.cljindex fe1cee18559..97a102e04de 100644--- a/src/metabase/cache/api.clj+++ b/src/metabase/cache/api.clj@@ -2,6 +2,7 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.cache.db :as cache.db][metabase.cache.models.cache-config :as cache-config][metabase.config.core :as config][metabase.lib.schema.common :as lib.schema.common]@@ -104,11 +105,10 @@(throw (premium-features/ee-feature-error (tru "Granular Caching"))):else- (api/check-404 (t2/select-one (case model- "database" :model/Database- "dashboard" :model/Dashboard- "question" :model/Card)- :id [:in ids]))))+ (api/check-404 (case model+ "database" (cache.db/database-with-ids ids)+ "dashboard" (cache.db/dashboard-with-ids ids)+ "question" (cache.db/card-with-ids ids)))))(mr/def ::cache-config-item[:mapdiff --git a/src/metabase/cache/db.clj b/src/metabase/cache/db.cljnew file mode 100644index 00000000000..6a71ee4bf1e--- /dev/null+++ b/src/metabase/cache/db.clj@@ -0,0 +1,142 @@+(ns metabase.cache.db+ "Application database queries for the cache module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn database-with-ids+ "A Database whose id is in `ids`, or nil."+ [ids]+ (t2/select-one :model/Database :id [:in ids]))++(defn dashboard-with-ids+ "A Dashboard whose id is in `ids`, or nil."+ [ids]+ (t2/select-one :model/Dashboard :id [:in ids]))++(defn card-with-ids+ "A Card whose id is in `ids`, or nil."+ [ids]+ (t2/select-one :model/Card :id [:in ids]))++(defn dashboard-collection-id+ "The `:collection_id` of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one [:model/Dashboard :collection_id] :id dashboard-id))++(defn card-collection-id+ "The `:collection_id` of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :collection_id] :id card-id))++(defn cache-config+ "The CacheConfig with primary key `pk`, or nil."+ [pk]+ (t2/select-one :model/CacheConfig pk))++(defn root-ttl-cache-config+ "The root TTL CacheConfig, or nil."+ []+ (t2/select-one :model/CacheConfig :model "root" :model_id 0 :strategy :ttl))++(defn- sort-column->order-by+ "Convert a sort column to the appropriate SQL order-by expression."+ [sort-column]+ (case sort-column+ :name [:coalesce :report_card.name :report_dashboard.name]+ :collection [:coalesce :report_card.collection_id :report_dashboard.collection_id]+ :policy :cache_config.strategy))++(defn- base-query+ "Build the base query for cache configs with JOINs for name/collection access."+ [models collection id]+ (if id+ {:select [:cache_config.*]+ :from [:cache_config]+ :where [:and [:in :model models] [:= :model_id id]]}+ {:select [:cache_config.*+ [[:coalesce :report_card.name :report_dashboard.name] :item_name]+ [[:coalesce :report_card.collection_id :report_dashboard.collection_id] :collection_id]+ [:collection.name :collection_name]+ [:collection.authority_level :collection_authority_level]+ [:collection.type :collection_type]]+ :from [:cache_config]+ :left-join [:report_card [:and+ [:= :model "question"]+ [:= :model_id :report_card.id]+ (when collection+ [:= :report_card.collection_id collection])]+ :report_dashboard [:and+ [:= :model "dashboard"]+ [:= :model_id :report_dashboard.id]+ (when collection+ [:= :report_dashboard.collection_id collection])]+ :collection [:= :collection.id+ [:coalesce :report_card.collection_id+ :report_dashboard.collection_id]]]+ :where [:and+ [:in :model models]+ [:case+ [:= :model "question"] [:!= :report_card.id nil]+ [:= :model "dashboard"] [:!= :report_dashboard.id nil]+ :else true]]}))++(defn cache-configs-page+ "The CacheConfigs of `models` in `collection` (or of the entity with `id`), with the name and Collection of the+ configured entity, sorted by `sort-column` in `sort-direction` when given and paged by `limit` and `offset`."+ [models collection id sort-column sort-direction limit offset]+ (t2/select :model/CacheConfig+ (cond-> (base-query models collection id)+ sort-column (assoc :order-by [[(sort-column->order-by sort-column) sort-direction]])+ limit (assoc :limit limit)+ offset (assoc :offset offset))))++(defn cache-config-count-row+ "The `:count` row of the CacheConfigs [[cache-configs-page]] pages through."+ [models collection id]+ (t2/query-one (-> (base-query models collection id)+ (dissoc :select)+ (assoc :select [[[:count :*] :count]]))))++(defn lock-cache-config+ "The CacheConfig for `model` and `model-id` locked for update, or nil."+ [model model-id]+ (t2/select-one :model/CacheConfig :model model :model_id model-id {:for :update}))++(defn cache-configs-for+ "The CacheConfigs for `model` and `model-ids`."+ [model model-ids]+ (t2/select :model/CacheConfig :model model :model_id [:in model-ids]))++(defn delete-cache-configs!+ "Delete the CacheConfigs for `model` and `model-ids`."+ [model model-ids]+ (t2/delete! :model/CacheConfig :model model :model_id [:in model-ids]))++(defn card-ids-for-databases+ "The ids of the Cards of the Databases with `database-ids`."+ [database-ids]+ (t2/select-fn-vec :id [:model/Card :id] :database_id [:in database-ids]))++(defn dashboard-card-ids+ "The Card ids of the DashboardCards of the Dashboards with `dashboard-ids`."+ [dashboard-ids]+ (t2/select-fn-vec :card_id [:model/DashboardCard :card_id] :dashboard_id [:in dashboard-ids]))++(defn invalidate-cards!+ "Set `cache_invalidated_at` of the Cards with `card-ids` to `invalidated-at`, returning the number updated."+ [card-ids invalidated-at]+ (t2/update! :model/Card :id [:in card-ids] {:cache_invalidated_at invalidated-at}))++(defn invalidate-cache-configs!+ "Set `invalidated_at` of the CacheConfigs identified by the `[model model-id]` pairs to `invalidated-at`."+ [model+ids invalidated-at]+ (t2/query-one {:update (t2/table-name :model/CacheConfig)+ :set {:invalidated_at invalidated-at}+ :where (into [:or] (for [[model model-id] model+ids]+ [:and [:= :model model] [:= :model_id model-id]]))}))++(defn cache-config-exists?+ "Whether any CacheConfig exists."+ []+ (t2/exists? :model/CacheConfig))diff --git a/src/metabase/cache/models/cache_config.clj b/src/metabase/cache/models/cache_config.cljindex 1d381c4d493..30d08e1dcab 100644--- a/src/metabase/cache/models/cache_config.clj+++ b/src/metabase/cache/models/cache_config.clj@@ -4,6 +4,7 @@[java-time.api :as t][medley.core :as m][metabase.app-db.core :as app-db]+ [metabase.cache.db :as cache.db][metabase.events.core :as events][metabase.models.interface :as mi][metabase.permissions.core :as perms]@@ -41,8 +42,8 @@"Get the collection_id for the target entity of a CacheConfig."[{:keys [model model_id]}](case model- "dashboard" (:collection_id (t2/select-one [:model/Dashboard :collection_id] :id model_id))- "question" (:collection_id (t2/select-one [:model/Card :collection_id] :id model_id))+ "dashboard" (:collection_id (cache.db/dashboard-collection-id model_id))+ "question" (:collection_id (cache.db/card-collection-id model_id))nil))(defmethod mi/can-write? :model/CacheConfig@@ -56,7 +57,7 @@{:collection_id (target-collection-id instance)}:write))))([_model pk]- (mi/can-write? (t2/select-one :model/CacheConfig pk))))+ (mi/can-write? (cache.db/cache-config pk))))(defmethod mi/can-read? :model/CacheConfig([instance]@@ -66,7 +67,7 @@"dashboard" (mi/can-read? :model/Dashboard (:model_id instance))"question" (mi/can-read? :model/Card (:model_id instance))))([_model pk]- (mi/can-read? (t2/select-one :model/CacheConfig pk))))+ (mi/can-read? (cache.db/cache-config pk))))(defn- can-set-cache-policy?"Check if the current user can set a cache policy for an entity.@@ -103,7 +104,7 @@(defn root-strategy"Returns root strategy, if it's defined."[]- (t2/select-one :model/CacheConfig :model "root" :model_id 0 :strategy :ttl))+ (cache.db/root-ttl-cache-config))(defn row->config"Transform from how cache config is stored to how it's used/exposed in the API."@@ -142,48 +143,6 @@:config (dissoc strategy :type :refresh_automatically):refresh_automatically (:refresh_automatically strategy)})-(defn- sort-column->order-by- "Convert a sort column to the appropriate SQL order-by expression."- [sort-column]- (case sort-column- :name [:coalesce :report_card.name :report_dashboard.name]- :collection [:coalesce :report_card.collection_id :report_dashboard.collection_id]- :policy :cache_config.strategy))--(defn- base-query- "Build the base query for cache configs with JOINs for name/collection access."- [models collection id]- (if id- {:select [:cache_config.*]- :from [:cache_config]- :where [:and [:in :model models] [:= :model_id id]]}- {:select [:cache_config.*- [[:coalesce :report_card.name :report_dashboard.name] :item_name]- [[:coalesce :report_card.collection_id :report_dashboard.collection_id] :collection_id]- [:collection.name :collection_name]- [:collection.authority_level :collection_authority_level]- [:collection.type :collection_type]]- :from [:cache_config]- :left-join [:report_card [:and- [:= :model "question"]- [:= :model_id :report_card.id]- (when collection- [:= :report_card.collection_id collection])]- :report_dashboard [:and- [:= :model "dashboard"]- [:= :model_id :report_dashboard.id]- (when collection- [:= :report_dashboard.collection_id collection])]- :collection [:= :collection.id- [:coalesce :report_card.collection_id- :report_dashboard.collection_id]]]- :where [:and- [:in :model models]- [:case- [:= :model "question"] [:!= :report_card.id nil]- [:= :model "dashboard"] [:!= :report_dashboard.id nil]- :else true]]}))-(mu/defn get-list"Get a list of cache configurations for given `models` and a `collection`.Supports pagination via `limit` and `offset`, and sorting via `sort-params`."@@ -194,28 +153,21 @@(let [{:keys [sort_column sort_direction]:or {sort_column :name sort_direction :asc}} sort-params;; Only apply sorting when paginating (limit provided) and not querying by id- apply-sorting? (and limit (nil? id))- query (cond-> (base-query models collection id)- apply-sorting? (assoc :order-by [[(sort-column->order-by sort_column) sort_direction]])- limit (assoc :limit limit)- offset (assoc :offset offset))]- (->> (t2/select :model/CacheConfig query)+ apply-sorting? (and limit (nil? id))]+ (->> (cache.db/cache-configs-page models collection id (when apply-sorting? sort_column) sort_direction limit offset)(mapv row->config))))(mu/defn get-list-total"Get the total count of cache configurations for given `models` and a `collection`."[models collection id]- (let [query (-> (base-query models collection id)- (dissoc :select)- (assoc :select [[[:count :*] :count]]))]- (:count (t2/query-one query))))+ (:count (cache.db/cache-config-count-row models collection id)))(defn store!"Store cache configuration in DB."[user-id {:keys [model model_id] :as config}](t2/with-transaction [_tx](let [data (config->row config)- current (t2/select-one :model/CacheConfig :model model :model_id model_id {:for :update})]+ current (cache.db/lock-cache-config model model_id)](u/prog1 (app-db/update-or-insert! :model/CacheConfig {:model model :model_id model_id}(constantly data))(audit-caching-change! user-id <> current data)))))@@ -223,8 +175,8 @@(defn delete!"Delete cache configuration (possibly multiple), identified by a `model` and a vector of `model-ids`."[user-id model model-ids]- (when-let [current (seq (t2/select :model/CacheConfig :model model :model_id [:in model-ids]))]- (t2/delete! :model/CacheConfig :model model :model_id [:in model-ids])+ (when-let [current (seq (cache.db/cache-configs-for model model-ids))]+ (cache.db/delete-cache-configs! model model-ids)(doseq [item current](audit-caching-change! user-id(:id item)@@ -237,26 +189,23 @@(let [card-ids (concatquestions(when (seq databases)- (t2/select-fn-vec :id [:model/Card :id] :database_id [:in databases]))+ (cache.db/card-ids-for-databases databases))(when (seq dashboards)- (t2/select-fn-vec :card_id [:model/DashboardCard :card_id] :dashboard_id [:in dashboards])))]+ (cache.db/dashboard-card-ids dashboards)))](if (empty? card-ids)-1- (t2/update! :model/Card :id [:in card-ids]- {:cache_invalidated_at (t/offset-date-time)}))))+ (cache.db/invalidate-cards! card-ids (t/offset-date-time)))))(defn- invalidate-cache-configs [databases dashboards questions]- (let [conditions (for [[k vs] [[:database databases]- [:dashboard dashboards]- [:question questions]]- v vs]- [:and [:= :model (name k)] [:= :model_id v]])]- (if (empty? conditions)+ (let [model+ids (for [[k vs] [[:database databases]+ [:dashboard dashboards]+ [:question questions]]+ v vs]+ [(name k) v])]+ (if (empty? model+ids)-1;; using JVM date rather than DB time since it's what are used in cache tasks- (t2/query-one {:update (t2/table-name :model/CacheConfig)- :set {:invalidated_at (t/offset-date-time)}- :where (into [:or] conditions)}))))+ (cache.db/invalidate-cache-configs! model+ids (t/offset-date-time)))))(defn invalidate!"Invalidate cache configuration. Accepts lists of ids for different types of models. If `with-overrides?` is passed,diff --git a/src/metabase/cache/settings.clj b/src/metabase/cache/settings.cljindex 10b20763b92..c76a9b61a3c 100644--- a/src/metabase/cache/settings.clj+++ b/src/metabase/cache/settings.clj@@ -1,9 +1,9 @@(ns metabase.cache.settings(:require+ [metabase.cache.db :as cache.db][metabase.settings.core :as setting :refer [defsetting]][metabase.util :as u]- [metabase.util.i18n :refer [deferred-tru tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [deferred-tru tru]]))(defsetting enable-query-caching(deferred-tru "Allow caching results of queries that take a long time to run.")@@ -11,7 +11,7 @@:default true:visibility :authenticated:audit :getter- :getter #(t2/exists? :model/CacheConfig)+ :getter cache.db/cache-config-exists?:setter :none)(def ^:private ^:const global-max-caching-kbdiff --git a/src/metabase/channel/api/channel.clj b/src/metabase/channel/api/channel.cljindex eb199494954..d4650fb3420 100644--- a/src/metabase/channel/api/channel.clj+++ b/src/metabase/channel/api/channel.clj@@ -6,6 +6,7 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.channel.core :as channel]+ [metabase.channel.db :as channel.db][metabase.channel.impl.email :as channel.email][metabase.channel.impl.http :as channel.http][metabase.channel.impl.slack :as channel.slack]@@ -18,8 +19,7 @@[metabase.util.i18n :refer [deferred-tru tru]][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(defn- remove-details-if-needed"Remove the details field if the current user does not have write permissions for the channel."@@ -39,8 +39,8 @@{:keys [include_inactive]} :- [:map[:include_inactive {:optional true} [:maybe {:default false} :boolean]]]](->> (if include_inactive- (t2/select :model/Channel)- (t2/select :model/Channel :active true))+ (channel.db/channels)+ (channel.db/active-channels))(filter mi/can-read?)(map remove-details-if-needed)))@@ -106,10 +106,10 @@[:type ChannelType][:active {:optional true} [:maybe {:default true} :boolean]]])](perms/check-has-application-permission :setting)- (when (t2/exists? :model/Channel :name channel-name)+ (when (channel.db/channel-name-exists? channel-name)(throw (ex-info "Channel with that name already exists" {:status-code 409:errors {:name "Channel with that name already exists"}})))- (u/prog1 (t2/insert-returning-instance! :model/Channel body)+ (u/prog1 (channel.db/insert-channel! body)(events/publish-event! :event/channel-create {:object <> :user-id api/*current-user-id*})));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -120,7 +120,7 @@"Get a channel"[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (-> (t2/select-one :model/Channel id) api/read-check remove-details-if-needed))+ (-> (channel.db/channel id) api/read-check remove-details-if-needed));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -137,13 +137,13 @@[:type {:optional true} [:maybe ChannelType]][:active {:optional true} [:maybe :boolean]]]:details-optional? true)]- (let [channel-before-update (api/write-check (t2/select-one :model/Channel id))]+ (let [channel-before-update (api/write-check (channel.db/channel id))](when (and (:details body) (nil? (:type body)))(when-let [schema (details-schema-for-type (:type channel-before-update))](when-not (mr/validate schema (:details body))(throw (ex-info (tru "Invalid channel details") {:status-code 400})))))- (t2/update! :model/Channel id body)- (u/prog1 (t2/select-one :model/Channel id)+ (channel.db/update-channel! id body)+ (u/prog1 (channel.db/channel id)(events/publish-event! :event/channel-update {:object <>:user-id api/*current-user-id*:previous-object channel-before-update}))))diff --git a/src/metabase/channel/db.clj b/src/metabase/channel/db.cljnew file mode 100644index 00000000000..59af45f697a--- /dev/null+++ b/src/metabase/channel/db.clj@@ -0,0 +1,92 @@+(ns metabase.channel.db+ "Application database queries for the channel module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn channels+ "Every Channel."+ []+ (t2/select :model/Channel))++(defn active-channels+ "The active Channels."+ []+ (t2/select :model/Channel :active true))++(defn channel-name-exists?+ "Whether a Channel named `channel-name` exists."+ [channel-name]+ (t2/exists? :model/Channel :name channel-name))++(defn insert-channel!+ "Insert the Channel `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Channel row))++(defn channel+ "The Channel with `id`, or nil."+ [id]+ (t2/select-one :model/Channel id))++(defn update-channel!+ "Apply `changes` to the Channel with `id`."+ [id changes]+ (t2/update! :model/Channel id changes))++(defn accepted-admin-emails+ "The emails of the active personal superusers who have logged in at least once, in id order."+ []+ (t2/select-fn-set :email :model/User+ :is_superuser true+ :is_active true+ :last_login [:not= nil]+ :type "personal"+ {:order-by [[:id :asc]]}))++(defn user-contact-info+ "The name, email, and locale of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :last_name :first_name :email :locale] :id user-id))++(defn active-user-emails+ "The emails of the active Users with `user-ids`."+ [user-ids]+ (t2/select-fn-set :email :model/User {:where [:and+ [:= :is_active true]+ [:in :id user-ids]]}))++(defn delete-pulse-channels-for-channel!+ "Delete the PulseChannels of the Channel with `channel-id`."+ [channel-id]+ (t2/delete! :model/PulseChannel :channel_id channel-id))++(defn channel-by-name+ "The Channel named `channel-name`, or nil."+ [channel-name]+ (t2/select-one :model/Channel :name channel-name))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn dashboard-tabs+ "The DashboardTabs of the Dashboard with `dashboard-id`, in position order."+ [dashboard-id]+ (t2/select :model/DashboardTab :dashboard_id dashboard-id {:order-by [[:position :asc]]}))++(defn dashcards+ "The DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id))++(defn any-user+ "Some User, or nil."+ []+ (t2/select-one :model/User))diff --git a/src/metabase/channel/email/messages.clj b/src/metabase/channel/email/messages.cljindex 3c61fff5279..7e0500758a3 100644--- a/src/metabase/channel/email/messages.clj+++ b/src/metabase/channel/email/messages.clj@@ -10,6 +10,7 @@[medley.core :as m][metabase.app-db.core :as app-db][metabase.appearance.core :as appearance]+ [metabase.channel.db :as channel.db][metabase.channel.email :as email][metabase.channel.email.logo :as email.logo][metabase.channel.render.core :as channel.render]@@ -27,8 +28,7 @@[metabase.util.i18n :as i18n :refer [trs tru]][metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -166,12 +166,7 @@[](concat (when-let [admin-email (system/admin-email)][admin-email])- (t2/select-fn-set :email 'User- :is_superuser true- :is_active true- :last_login [:not= nil]- :type "personal"- {:order-by [[:id :asc]]})))+ (channel.db/accepted-admin-emails)))(defn send-user-joined-admin-notification-email!"Send an email to the `invitor` (the Admin who invited `new-user`) letting them know `new-user` has joined."@@ -224,7 +219,7 @@"Format and send an email informing the user that this is the first time we've seen a login from this device. Expectslogin history information as returned by [[metabase.login-history.models.login-history/human-friendly-infos]]."[{user-id :user_id, :keys [timestamp], :as login-history} :- [:map [:user_id pos-int?]]]- (let [user-info (or (t2/select-one [:model/User :last_name :first_name :email :locale] :id user-id)+ (let [user-info (or (channel.db/user-contact-info user-id)(throw (ex-info (tru "User {0} does not exist" user-id){:user-id user-id, :status-code 404})))user-locale (or (:locale user-info) (i18n/site-locale))@@ -276,9 +271,7 @@(concat(all-admin-recipients)(when (seq user-ids)- (t2/select-fn-set :email :model/User {:where [:and- [:= :is_active true]- [:in :id user-ids]]}))))))+ (channel.db/active-user-emails user-ids))))))(defn send-persistent-model-error-email!"Format and send an email informing the user about errors in the persistent model refresh task.diff --git a/src/metabase/channel/models/channel.clj b/src/metabase/channel/models/channel.cljindex d6dc7c023b8..dd04253aa23 100644--- a/src/metabase/channel/models/channel.clj+++ b/src/metabase/channel/models/channel.clj@@ -4,6 +4,7 @@[metabase.analytics-interface.core :as analytics][metabase.analytics.core :as analytics.core][metabase.api.common :as api]+ [metabase.channel.db :as channel.db][metabase.channel.template.handlebars :as handlebars][metabase.lib.schema.common :as lib.schema.common][metabase.models.interface :as mi]@@ -71,7 +72,7 @@[instance](let [deactivation? (false? (:active (t2/changes instance)))](when deactivation?- (t2/delete! :model/PulseChannel :channel_id (:id instance)))+ (channel.db/delete-pulse-channels-for-channel! (:id instance)))(cond-> instancedeactivation?;; Channel.name has an unique constraint and it's a useful property for serialization@@ -83,7 +84,7 @@(defmethod serdes/load-find-local "Channel"[path]- (t2/select-one :model/Channel :name (:id (last path))))+ (channel.db/channel-by-name (:id (last path))))(defmethod serdes/generate-path "Channel" [_ channel][(serdes/infer-self-path "Channel" channel)])diff --git a/src/metabase/channel/render/card.clj b/src/metabase/channel/render/card.cljindex 8bfd6d2288b..10c92200f5b 100644--- a/src/metabase/channel/render/card.clj+++ b/src/metabase/channel/render/card.clj@@ -1,6 +1,7 @@(ns metabase.channel.render.card(:require[hiccup.core :refer [h]]+ [metabase.channel.db :as channel.db][metabase.channel.render.body :as body][metabase.channel.render.image-bundle :as image-bundle][metabase.channel.render.png :as png]@@ -15,8 +16,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.markdown :as markdown]- [toucan2.core :as t2]))+ [metabase.util.markdown :as markdown]));;; I gave these keys below namespaces to make them easier to find usages for but didn't use `metabase.channel.render` so;;; we can keep this as an internal namespace you don't need to know about outside of the module.@@ -367,5 +367,5 @@(mu/defn defaulted-timezone :- :string"Returns the timezone ID for the given `card`. Either the report timezone (if applicable) or the JVM timezone."[card]- (or (some->> card :database_id (t2/select-one :model/Database :id) qp.timezone/results-timezone-id)+ (or (some->> card :database_id channel.db/database qp.timezone/results-timezone-id)(qp.timezone/system-timezone-id)))diff --git a/src/metabase/channel/render/pdf.clj b/src/metabase/channel/render/pdf.cljindex b1824603709..547b3ba45a1 100644--- a/src/metabase/channel/render/pdf.clj+++ b/src/metabase/channel/render/pdf.clj@@ -39,6 +39,7 @@[clojure.string :as str][clojure.walk :as walk][medley.core :as m]+ [metabase.channel.db :as channel.db][metabase.channel.render.body :as body][metabase.channel.render.card :as render.card][metabase.channel.render.js.svg :as js.svg]@@ -1468,9 +1469,9 @@(map (juxt #(-> % :dashcard :id) identity)))parts)dims (paper-dims paper-key)- dash (t2/select-one :model/Dashboard :id dashboard-id)- tabs (t2/select :model/DashboardTab :dashboard_id dashboard-id {:order-by [[:position :asc]]})- dcs (t2/hydrate (t2/select :model/DashboardCard :dashboard_id dashboard-id) :card)+ dash (channel.db/dashboard dashboard-id)+ tabs (channel.db/dashboard-tabs dashboard-id)+ dcs (t2/hydrate (channel.db/dashcards dashboard-id) :card);; only treat a dashboard as tabbed when there's more than one tab -- a lone tab isn't shown as a tab in;; the UI, so the PDF shouldn't draw (or reserve space for) its title eithertabbed? (> (count tabs) 1)diff --git a/src/metabase/channel/render/preview.clj b/src/metabase/channel/render/preview.cljindex 2dad430847d..01684e60ec5 100644--- a/src/metabase/channel/render/preview.clj+++ b/src/metabase/channel/render/preview.clj@@ -9,6 +9,7 @@[hickory.render :as hik.r][hickory.zip :as hik.z][metabase.api.common :as api]+ [metabase.channel.db :as channel.db][metabase.channel.email.result-attachment :as email.result-attachment][metabase.channel.render.card :as render.card][metabase.channel.render.image-bundle :as img]@@ -17,8 +18,7 @@[metabase.notification.payload.core :as notification.payload][metabase.system.core :as system][metabase.util :as u]- [metabase.util.markdown :as markdown]- [toucan2.core :as t2]))+ [metabase.util.markdown :as markdown]))(set! *warn-on-reflection* true)@@ -82,8 +82,8 @@(defn- render-dashboard-to-hiccup"Given a dashboard ID, renders all of the dashcards to hiccup datastructure."[dashboard-id]- (let [user (t2/select-one :model/User)- dashboard (t2/select-one :model/Dashboard :id dashboard-id)+ (let [user (channel.db/any-user)+ dashboard (channel.db/dashboard dashboard-id)dashboard-results (notification.payload/execute-dashboard (:id dashboard) (:id user) nil)render (->> (map render-one-dashcard (map #(assoc % :dashboard-id dashboard-id) dashboard-results))(into [[:trdiff --git a/src/metabase/cloud_migration/api.clj b/src/metabase/cloud_migration/api.cljindex ac8ba5fad9b..fa343b3e9c4 100644--- a/src/metabase/cloud_migration/api.clj+++ b/src/metabase/cloud_migration/api.clj@@ -6,10 +6,10 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.cloud-migration.db :as cloud-migration.db][metabase.cloud-migration.models.cloud-migration :as cloud-migration][metabase.cloud-migration.settings :as cloud-migration.settings]- [metabase.premium-features.core :as premium-features]- [toucan2.core :as t2]))+ [metabase.premium-features.core :as premium-features]));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -23,13 +23,12 @@(premium-features/is-hosted?){:status 400 :body "Cannot migrate a hosted instance."}- (t2/select-one :model/CloudMigration :state [:not-in cloud-migration/terminal-states])+ (cloud-migration.db/cloud-migration-not-in-states cloud-migration/terminal-states){:status 409 :body "There's an ongoing migration already."}:else(try- (let [cloud-migration (t2/insert-returning-instance! :model/CloudMigration- (cloud-migration/get-store-migration))]+ (let [cloud-migration (cloud-migration.db/insert-cloud-migration! (cloud-migration/get-store-migration))](future (cloud-migration/migrate! cloud-migration))cloud-migration)(catch Exception e@@ -46,7 +45,7 @@"Get the latest cloud migration, if any."[](api/check-superuser)- (t2/select-one :model/CloudMigration {:order-by [[:created_at :desc]]}))+ (cloud-migration.db/latest-cloud-migration));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -57,4 +56,4 @@[](api/check-superuser)(cloud-migration.settings/read-only-mode! false)- (t2/update! :model/CloudMigration {:state [:not-in cloud-migration/terminal-states]} {:state :cancelled}))+ (cloud-migration.db/cancel-cloud-migrations-not-in-states! cloud-migration/terminal-states))diff --git a/src/metabase/cloud_migration/db.clj b/src/metabase/cloud_migration/db.cljnew file mode 100644index 00000000000..498bbf023d4--- /dev/null+++ b/src/metabase/cloud_migration/db.clj@@ -0,0 +1,44 @@+(ns metabase.cloud-migration.db+ "Application database queries for the cloud migration module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.app-db.core :as mdb]+ [toucan2.core :as t2]))++(defn cloud-migration-not-in-states+ "A CloudMigration whose state is not one of `states`, or nil."+ [states]+ (t2/select-one :model/CloudMigration :state [:not-in states]))++(defn insert-cloud-migration!+ "Insert the CloudMigration `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/CloudMigration row))++(defn latest-cloud-migration+ "The most recently created CloudMigration, or nil."+ []+ (t2/select-one :model/CloudMigration {:order-by [[:created_at :desc]]}))++(defn cancel-cloud-migrations-not-in-states!+ "Cancel every CloudMigration whose state is not one of `states`."+ [states]+ (t2/update! :model/CloudMigration {:state [:not-in states]} {:state :cancelled}))++(defn quartz-node-count+ "The number of Quartz scheduler nodes recorded in the app DB."+ []+ (t2/count (if (= (mdb/db-type) :postgres)+ "qrtz_scheduler_state"+ "QRTZ_SCHEDULER_STATE")))++(defn set-cloud-migration-progress-if-not-in-states!+ "Set the state and progress of the CloudMigration with `id` unless its state is one of `states`, returning the+ number of rows updated."+ [id states state progress]+ (t2/update! :model/CloudMigration :id id :state [:not-in states] {:state state :progress progress}))++(defn set-cloud-migration-state!+ "Set the state of the CloudMigration with `id`."+ [id state]+ (t2/update! :model/CloudMigration :id id {:state state}))diff --git a/src/metabase/cloud_migration/models/cloud_migration.clj b/src/metabase/cloud_migration/models/cloud_migration.cljindex 85bab77128c..44eebca7c8e 100644--- a/src/metabase/cloud_migration/models/cloud_migration.clj+++ b/src/metabase/cloud_migration/models/cloud_migration.clj@@ -5,6 +5,7 @@[clojure.java.io :as io][clojure.set :as set][metabase.app-db.core :as mdb]+ [metabase.cloud-migration.db :as cloud-migration.db][metabase.cloud-migration.settings :as cloud-migration.settings][metabase.cmd.copy :as copy][metabase.cmd.dump-to-h2 :as dump-to-h2]@@ -90,10 +91,7 @@Works by checking how many Quartz nodes there are.See https://github.com/quartz-scheduler/quartz/issues/733"[]- (>= (t2/count (if (= (mdb/db-type) :postgres)- "qrtz_scheduler_state"- "QRTZ_SCHEDULER_STATE"))- 2))+ (>= (cloud-migration.db/quartz-node-count) 2))(defn- progress-file-input-stream"File input stream that calls on-percent-progress with current read progress as int from 0 to 100."@@ -125,8 +123,7 @@This is the main cluster coordination mechanism for migrations, since any instancecan cancel the migration, not just the one that initiated it."[id state progress]- (when (= 0 (t2/update! :model/CloudMigration :id id :state [:not-in terminal-states]- {:state state :progress progress}))+ (when (= 0 (cloud-migration.db/set-cloud-migration-progress-if-not-in-states! id terminal-states state progress))(throw (ex-info "Cannot update migration in terminal state" {:terminal true}))))(defn abs-progress@@ -221,7 +218,7 @@(str "cloud_migration_dump_" (random-uuid) ".mv.db"))](try(when retry?- (t2/update! :model/CloudMigration :id id {:state :init}))+ (cloud-migration.db/set-cloud-migration-state! id :init))(log/info "Setting read-only mode")(set-progress id :setup 1)(cloud-migration.settings/read-only-mode! true)@@ -254,7 +251,7 @@(if (-> e ex-data :terminal)(log/info "Migration interrupted due to terminal state")(do- (t2/update! :model/CloudMigration id {:state :error})+ (cloud-migration.db/set-cloud-migration-state! id :error)(log/info "Migration failed")(throw (ex-info "Error performing migration" {} e)))))(finally@@ -290,10 +287,10 @@#_(def ^:private part-size 6e6);; add new- (t2/insert-returning-instance! :model/CloudMigration (get-store-migration))+ (cloud-migration.db/insert-cloud-migration! (get-store-migration));; get migration- @(def mig (t2/select-one :model/CloudMigration {:order-by [[:created_at :desc]]}))+ @(def mig (cloud-migration.db/latest-cloud-migration));; migrate(migrate! mig)@@ -302,4 +299,4 @@(migrate! mig :retry? true);; cancel all- (t2/update! :model/CloudMigration {:state [:not-in terminal-states]} {:state :cancelled}))+ (cloud-migration.db/cancel-cloud-migrations-not-in-states! terminal-states))diff --git a/src/metabase/cmd/db.clj b/src/metabase/cmd/db.cljnew file mode 100644index 00000000000..bc56ba95672--- /dev/null+++ b/src/metabase/cmd/db.clj@@ -0,0 +1,11 @@+(ns metabase.cmd.db+ "Application database queries for the command-line module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn user-id-and-active-by-email+ "The `:id` and `:is_active` of the User whose email matches `email` case-insensitively, or nil."+ [email]+ (t2/select-one [:model/User :id :is_active] :%lower.email (u/lower-case-en email)))diff --git a/src/metabase/cmd/reset_password.clj b/src/metabase/cmd/reset_password.cljindex 3d46044c32c..716ff39149d 100644--- a/src/metabase/cmd/reset_password.clj+++ b/src/metabase/cmd/reset_password.clj@@ -2,9 +2,8 @@(:require[metabase.app-db.core :as mdb][metabase.auth-identity.core :as auth-identity]- [metabase.util :as u]- [metabase.util.i18n :refer [deferred-trs trs]]- [toucan2.core :as t2]))+ [metabase.cmd.db :as cmd.db]+ [metabase.util.i18n :refer [deferred-trs trs]]))(set! *warn-on-reflection* true)@@ -12,7 +11,7 @@"Set and return a new `reset_token` for the user with EMAIL-ADDRESS."[email-address](let [{user-id :id, active? :is_active}- (or (t2/select-one [:model/User :id :is_active], :%lower.email (u/lower-case-en email-address))+ (or (cmd.db/user-id-and-active-by-email email-address)(throw (Exception. (str (deferred-trs "No user found with email address ''{0}''. " email-address)(deferred-trs "Please check the spelling and try again.")))))](when-not active?diff --git a/src/metabase/collections/create.clj b/src/metabase/collections/create.cljindex f371c4428eb..2d6106c151b 100644--- a/src/metabase/collections/create.clj+++ b/src/metabase/collections/create.clj@@ -6,20 +6,20 @@(:require[malli.util][metabase.api.common :as api]+ [metabase.collections.db :as collections.db][metabase.collections.models.collection :as collection][metabase.events.core :as events][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(defn- parent-or-root"From a create request return either the parent collection or the root collection."[{collection-id :parent_id collection-namespace :namespace}](if collection-id- (t2/select-one :model/Collection :id collection-id)+ (collections.db/collection collection-id)(collection/root-collection-with-ui-details collection-namespace)))(defn- write-check-authority-level@@ -89,8 +89,7 @@create and touch events. The single source of truth for collection creation; REST and agentcallers both go through here."[coll-data]- (u/prog1 (t2/insert-returning-instance!- :model/Collection+ (u/prog1 (collections.db/insert-collection!(-> (apply-defaults-to-collection coll-data)write-check-authority-levelvalidate-new-tenant-collection!))diff --git a/src/metabase/collections/db.clj b/src/metabase/collections/db.cljnew file mode 100644index 00000000000..1aecfce4fe0--- /dev/null+++ b/src/metabase/collections/db.clj@@ -0,0 +1,465 @@+(ns metabase.collections.db+ "Application database queries for the collections module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods,+ and transactions."+ (:require+ [metabase.models.serialization :as serdes]+ [toucan2.core :as t2]))++;;; ---------------------------------------------- Single Collections ----------------------------------------------++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn collection-id-and-namespace+ "The ID and namespace of the Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one [:model/Collection :id :namespace] :id collection-id))++(defn collection-of-type+ "The Collection of `type`, or nil."+ [type]+ (t2/select-one :model/Collection :type type))++(defn root-remote-synced-collection+ "The top-level remote-synced Collection, or nil."+ []+ (t2/select-one :model/Collection :is_remote_synced true :location "/"))++(defn personal-collection-of-user+ "The personal Collection of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/Collection :personal_owner_id user-id))++(defn collection-exists?+ "Whether a Collection with `collection-id` exists."+ [collection-id]+ (t2/exists? :model/Collection :id collection-id))++(defn unarchived-collection-exists?+ "Whether an unarchived Collection with `collection-id` exists."+ [collection-id]+ (t2/exists? :model/Collection :id collection-id :archived false))++(defn remote-synced-collection-exists?+ "Whether a remote-synced Collection with `collection-id` exists."+ [collection-id]+ (t2/exists? :model/Collection :id collection-id :is_remote_synced true))++(defn personal-collection?+ "Whether the Collection with `collection-id` is a personal Collection."+ [collection-id]+ (t2/exists? :model/Collection :id collection-id :personal_owner_id [:not= nil]))++(defn collection-remote-synced?+ "Whether the Collection with `collection-id` is remote-synced."+ [collection-id]+ (t2/select-one-fn :is_remote_synced :model/Collection :id collection-id))++(defn collection-namespace+ "The namespace of the Collection with `collection-id`."+ [collection-id]+ (t2/select-one-fn :namespace :model/Collection :id collection-id))++(defn collection-location+ "The location of the Collection with `collection-id`."+ [collection-id]+ (t2/select-one-fn :location :model/Collection :id collection-id))++(defn root-collection-type-by-id+ "The type of the top-level Collection with `collection-id`, or nil if it is not top-level."+ [collection-id]+ (t2/select-one-fn :type :model/Collection :id collection-id :location "/"))++;;; ---------------------------------------------- Collection sets ----------------------------------------------++(defn collections-by-id+ "A map of ID to Collection for `collection-ids`."+ [collection-ids]+ (t2/select-pk->fn identity :model/Collection :id [:in collection-ids]))++(defn collection-columns-by-id+ "A map of ID to the `columns` of the Collections with `collection-ids`."+ [columns collection-ids]+ (t2/select-pk->fn identity (into [:model/Collection] columns) :id [:in collection-ids]))++(defn collection-archived-flags+ "A map of ID to `:archived` for `collection-ids`."+ [collection-ids]+ (t2/select-pk->fn :archived :model/Collection :id [:in collection-ids]))++(defn collections-in-namespace+ "The Collections in the namespace named `namespace-name`."+ [namespace-name]+ (t2/select :model/Collection :namespace namespace-name))++(defn archived-collections-in-operations+ "The archived Collections belonging to the archive operations with `archive-operation-ids`."+ [archive-operation-ids]+ (t2/select :model/Collection :archive_operation_id [:in archive-operation-ids] :archived true))++(defn ancestor-summaries+ "The name, ID, and owner of the Collections with `collection-ids`, ordered by location."+ [collection-ids]+ (t2/select [:model/Collection :name :id :personal_owner_id] :id [:in collection-ids] {:order-by [:location]}))++(defn descendant-summaries-where+ "The name, ID, location, and description of the Collections matching the Honey SQL `where`."+ [where]+ (t2/select [:model/Collection :name :id :location :description] {:where where}))++(defn descendant-summaries-with-type+ "The name, ID, location, description, and type of the Collections directly under any of `location-prefixes`+ (compared with SQL `LIKE`), excluding personal Collections that don't belong to `current-user-id`."+ [location-prefixes current-user-id]+ (t2/select [:model/Collection :name :id :location :description :type]+ {:where [:and+ (into [:or] (map (fn [prefix] [:like :location prefix])) location-prefixes)+ [:or [:= :personal_owner_id nil] [:= :personal_owner_id current-user-id]]]}))++(defn effective-children-where+ "The ID, name, description, and type of the Collections matching the Honey SQL `where`."+ [where]+ (t2/select [:model/Collection :id :name :description :type] {:where where}))++(defn collections-for-serdes-reducible+ "Reducible Collections matching the Honey SQL `where` in stable storage order."+ [where]+ (t2/reducible-select :model/Collection {:where where, :order-by serdes/stable-storage-order}))++(defn collection-count-by-ids+ "The number of Collections among `collection-ids`."+ [collection-ids]+ (t2/count :model/Collection :id [:in collection-ids]))++(defn collection-count-of-types+ "The number of Collections with `collection-id` whose type is one of `types`."+ [collection-id types]+ (t2/count :model/Collection :id collection-id :type [:in types]))++(defn remote-synced-collection-count+ "The number of remote-synced Collections."+ []+ (t2/count :model/Collection :is_remote_synced true))++(defn collection-ids-with-location-like+ "The IDs of the Collections whose location matches the SQL `pattern`."+ [pattern]+ (t2/select-pks-set :model/Collection :location [:like pattern]))++(defn unarchived-collection-ids-with-location-like+ "The IDs of the unarchived Collections whose location matches the SQL `pattern`."+ [pattern]+ (t2/select-pks-set :model/Collection :location [:like pattern] :archived false))++(defn not-yet-archived-collection-ids-with-location-like+ "The IDs of the Collections whose location matches the SQL `pattern` and that are not marked archived."+ [pattern]+ (t2/select-pks-set :model/Collection :location [:like pattern] :archived [:not= true]))++(defn archived-collection-ids-in-operation-with-location-like+ "The IDs of the archived Collections of the archive operation with `archive-operation-id` whose location matches+ the SQL `pattern`."+ [pattern archive-operation-id]+ (t2/select-pks-set :model/Collection+ :location [:like pattern]+ :archive_operation_id [:= archive-operation-id]+ :archived [:= true]))++(defn collection-ids-of-type+ "The IDs of the Collections among `collection-ids` of `type`."+ [collection-ids type]+ (t2/select-pks-set :model/Collection :id [:in collection-ids] :type type))++(defn child-collection-ids+ "The IDs of the non-trash Collections directly at `location`, excluding archived ones when `skip-archived?`."+ [location trash-type skip-archived?]+ (t2/select-pks-set :model/Collection+ {:where [:and+ [:= :location location]+ (when skip-archived? [:not :archived])+ [:or+ [:not= :type trash-type]+ [:= :type nil]]]}))++(defn remote-synced-root-collection-ids+ "The IDs of the top-level remote-synced Collections."+ []+ (t2/select-pks-set :model/Collection {:where [:and+ [:= :is_remote_synced true]+ [:= :location "/"]]}))++(defn personal-collection-ids+ "The IDs of every personal Collection."+ []+ (t2/select-pks-set :model/Collection :personal_owner_id [:not= nil]))++(defn personal-collection-ids-by-owner+ "A map of owner User ID to personal Collection ID for `user-ids`."+ [user-ids]+ (t2/select-fn->pk :personal_owner_id :model/Collection :personal_owner_id [:in user-ids]))++;;; ---------------------------------------------- Collection writes ----------------------------------------------++(defn insert-collection!+ "Insert `collection` and return the new instance."+ [collection]+ (t2/insert-returning-instance! :model/Collection collection))++(defn update-collection!+ "Apply `changes` to the Collection with `collection-id`."+ [collection-id changes]+ (t2/update! :model/Collection collection-id changes))++(defn clear-remote-synced-flags!+ "Mark every remote-synced Collection as not remote-synced."+ []+ (t2/update! :model/Collection :is_remote_synced true {:is_remote_synced false}))++(defn archive-descendant-collections!+ "Archive, as part of the archive operation with `archive-operation-id`, the unarchived Collections whose location+ matches the SQL `pattern`."+ [pattern archive-operation-id]+ (t2/query-one {:update :collection+ :set {:archive_operation_id archive-operation-id+ :archived_directly false+ :archived true}+ :where [:and+ [:like :location pattern]+ [:not :archived]]}))++(defn unarchive-descendant-collections!+ "Unarchive the Collections of the archive operation with `archive-operation-id` that were not archived directly,+ moving them from `orig-children-location` to `new-children-location` and setting `remote-synced?`."+ [orig-children-location new-children-location remote-synced? archive-operation-id]+ (t2/query-one {:update :collection+ :set {:location [:replace :location orig-children-location new-children-location]+ :is_remote_synced remote-synced?+ :archive_operation_id nil+ :archived_directly nil+ :archived false}+ :where [:and+ [:like :location (str orig-children-location "%")]+ [:= :archive_operation_id archive-operation-id]+ [:not= :archived_directly true]]}))++(defn move-descendant-collections!+ "Move the Collections under `orig-children-location` to `new-children-location` and set `remote-synced?`."+ [orig-children-location new-children-location remote-synced?]+ (t2/query-one {:update :collection+ :set {:location [:replace :location orig-children-location new-children-location]+ :is_remote_synced remote-synced?}+ :where [:like :location (str orig-children-location "%")]}))++(defn delete-collections-at-location!+ "Delete the Collections directly at `location`."+ [location]+ (t2/delete! :model/Collection :location location))++;;; ---------------------------------------------- Collection contents ----------------------------------------------++(defn instances-with-columns+ "The `columns` of the instances with `ids`."+ [columns ids]+ (t2/select columns :id [:in ids]))++(defn instance-by-id+ "The instance of `model` with `id`, or nil."+ [model id]+ (t2/select-one model :id id))++(defn collection-namespaces-of+ "A map of ID to the namespace of the Collection holding each instance of `model` with `ids`."+ [model ids]+ (t2/select-pk->fn :namespace [model :id [:c.namespace :namespace]]+ {:where [:in (keyword (str (name (t2/table-name model)) ".id")) ids]+ :join [[:collection :c] [:= :collection_id :c.id]]}))++(defn set-pulse-archived-in-collections!+ "Set `archived?` on the Pulses in the Collections with `collection-ids`."+ [collection-ids archived?]+ (t2/update! :model/Pulse {:collection_id [:in collection-ids]} {:archived archived?}))++(defn set-native-query-snippet-archived-in-collections!+ "Set `archived?` on the NativeQuerySnippets in the Collections with `collection-ids`."+ [collection-ids archived?]+ (t2/update! :model/NativeQuerySnippet {:collection_id [:in collection-ids]} {:archived archived?}))++(defn set-timeline-archived-in-collections!+ "Set `archived?` on the Timelines in the Collections with `collection-ids`."+ [collection-ids archived?]+ (t2/update! :model/Timeline {:collection_id [:in collection-ids]} {:archived archived?}))++(defn set-card-archived-in-collections-not-directly!+ "Set `archived?` on the Cards in the Collections with `collection-ids` that were not archived directly."+ [collection-ids archived?]+ (t2/update! :model/Card {:collection_id [:in collection-ids], :archived_directly false} {:archived archived?}))++(defn set-dashboard-archived-in-collections-not-directly!+ "Set `archived?` on the Dashboards in the Collections with `collection-ids` that were not archived directly."+ [collection-ids archived?]+ (t2/update! :model/Dashboard {:collection_id [:in collection-ids], :archived_directly false} {:archived archived?}))++(defn set-document-archived-in-collections-not-directly!+ "Set `archived?` on the Documents in the Collections with `collection-ids` that were not archived directly."+ [collection-ids archived?]+ (t2/update! :model/Document {:collection_id [:in collection-ids], :archived_directly false} {:archived archived?}))++(defn set-exploration-archived-in-collections-not-directly!+ "Set `archived?` on the Explorations in the Collections with `collection-ids` that were not archived directly."+ [collection-ids archived?]+ (t2/update! :model/Exploration {:collection_id [:in collection-ids], :archived_directly false} {:archived archived?}))++(defn delete-cards-in-collections!+ "Delete the Cards in the Collections with `collection-ids`."+ [collection-ids]+ (t2/delete! :model/Card :collection_id [:in collection-ids]))++(defn delete-dashboards-in-collections!+ "Delete the Dashboards in the Collections with `collection-ids`."+ [collection-ids]+ (t2/delete! :model/Dashboard :collection_id [:in collection-ids]))++(defn delete-native-query-snippets-in-collections!+ "Delete the NativeQuerySnippets in the Collections with `collection-ids`."+ [collection-ids]+ (t2/delete! :model/NativeQuerySnippet :collection_id [:in collection-ids]))++(defn delete-pulses-in-collections!+ "Delete the Pulses in the Collections with `collection-ids`."+ [collection-ids]+ (t2/delete! :model/Pulse :collection_id [:in collection-ids]))++(defn delete-timelines-in-collections!+ "Delete the Timelines in the Collections with `collection-ids`."+ [collection-ids]+ (t2/delete! :model/Timeline :collection_id [:in collection-ids]))++(defn dashboard-ids-in-collection+ "The IDs of the Dashboards in the Collection with `collection-id`, excluding archived ones when `skip-archived?`."+ [collection-id skip-archived?]+ (t2/select-pks-set :model/Dashboard+ {:where [:and [:= :collection_id collection-id] (when skip-archived? [:not :archived])]}))++(defn card-ids-in-collection+ "The IDs of the Cards in the Collection with `collection-id`, excluding archived ones when `skip-archived?` and+ excluding Cards materialized by an exploration Summary."+ [collection-id skip-archived?]+ (t2/select-pks-set :model/Card {:where [:and+ [:= :collection_id collection-id]+ (when skip-archived? [:not :archived])+ [:or+ [:= :document_id nil]+ [:in :document_id+ ^:allow-subquery {:select [:id]+ :from [:document]+ :where [:= :exploration_id nil]}]]]}))++(defn document-ids-in-collection+ "The IDs of the non-exploration Documents in the Collection with `collection-id`, excluding archived ones when+ `skip-archived?`."+ [collection-id skip-archived?]+ (t2/select-pks-set :model/Document {:where [:and+ [:= :collection_id collection-id]+ [:= :exploration_id nil]+ (when skip-archived? [:not :archived])]}))++(defn timeline-ids-in-collection+ "The IDs of the Timelines in the Collection with `collection-id`, excluding archived ones when `skip-archived?`."+ [collection-id skip-archived?]+ (t2/select-pks-set :model/Timeline+ {:where [:and [:= :collection_id collection-id] (when skip-archived? [:not :archived])]}))++(defn published-table-ids-in-collection+ "The IDs of the published Tables in the Collection with `collection-id`, excluding archived ones when+ `skip-archived?`."+ [collection-id skip-archived?]+ (t2/select-pks-set :model/Table {:where [:and+ [:= :collection_id collection-id]+ [:= :is_published true]+ (when skip-archived? [:= :archived_at nil])]}))++(defn transform-ids-in-collection+ "The IDs of the Transforms in the Collection with `collection-id`."+ [collection-id]+ (t2/select-pks-set :model/Transform {:where [:= :collection_id collection-id]}))++(defn published-table-ids-in-collections+ "The IDs of the published Tables in the Collections with `collection-ids`."+ [collection-ids]+ (t2/select-pks-set :model/Table :collection_id [:in collection-ids] :is_published true))++(defn unpublish-tables-in-collections!+ "Unpublish the Tables in the Collections with `collection-ids` and detach them from their Collection."+ [collection-ids]+ (t2/update! :model/Table {:collection_id [:in collection-ids]} {:collection_id nil, :is_published false}))++(defn dashboard-ids-with-cards+ "The `:dashboard_id` rows of the Dashboards among `dashboard-ids` holding an unarchived dashboard question."+ [dashboard-ids]+ (t2/query {:select-distinct [:dashboard_id]+ :from :report_card+ :where [:and+ [:= :archived false]+ [:in :dashboard_id dashboard-ids]+ [:exists ^:allow-subquery {:select 1+ :from :report_dashboardcard+ :where [:and+ [:= :report_dashboardcard.card_id :report_card.id]+ [:= :report_dashboardcard.dashboard_id :report_card.dashboard_id]]}]]}))++;;; ------------------------------------------------ Permissions ------------------------------------------------++(defn user-has-root-collection-permission?+ "Whether the User with `user-id` belongs to a group holding a Permissions row for one of the root collection+ `objects`."+ [user-id objects]+ (t2/exists? :model/Permissions {:select [:p.*]+ :from [[:permissions :p]]+ :join [[:permissions_group :pg] [:= :pg.id :p.group_id]+ [:permissions_group_membership :pgm] [:= :pgm.group_id :pg.id]]+ :where [:and+ [:= :pgm.user_id user-id]+ [:in :p.object objects]]}))++(defn group-ids-with-permission-object+ "The set of group IDs holding a Permissions row for `object`."+ [object]+ (t2/select-fn-set :group_id :model/Permissions :object object))++(defn insert-permissions!+ "Insert the Permissions `rows`."+ [rows]+ (t2/insert! :model/Permissions rows))++(defn delete-permissions-for-collection!+ "Delete the Permissions rows attached to the Collection with `collection-id`."+ [collection-id]+ (t2/delete! :model/Permissions :collection_id collection-id))++(defn delete-permissions-with-objects!+ "Delete the Permissions rows for `objects`."+ [objects]+ (t2/query-one {:delete-from :permissions+ :where [:in :object objects]}))++;;; ---------------------------------------------------- Users ----------------------------------------------------++(defn user-type+ "The type of the User with `user-id`."+ [user-id]+ (t2/select-one-fn :type :model/User user-id))++(defn user-name-parts-by-id+ "A map of ID to the first name, last name, and email of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :first_name :last_name :email :id] :id [:in user-ids]))++(defn non-api-key-user-ids+ "The IDs of the Users among `user-ids` that are not API key users."+ [user-ids]+ (t2/select-pks-set :model/User :id [:in user-ids] :type [:not= :api-key]))++;;; -------------------------------------------------- Hydration --------------------------------------------------diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex a8c90c0b89c..eaee77b83a1 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -10,6 +10,7 @@[metabase.api.common :as api][metabase.app-db.core :as mdb][metabase.audit-app.core :as audit]+ [metabase.collections.db :as collections.db][metabase.collections.models.collection.root :as collection.root][metabase.config.core :as config :refer [*request-id*]][metabase.events.core :as events]@@ -93,7 +94,7 @@:snippets)(defn- trash-collection* []- (t2/select-one :model/Collection :type trash-collection-type))+ (collections.db/collection-of-type trash-collection-type))(let [get-trash (mdb/memoize-for-application-db(fn []@@ -149,7 +150,7 @@(cond(nil? collection-or-id) false ;; the root collection is never remote-synced(map? collection-or-id) (boolean (get collection-or-id :is_remote_synced))- :else (t2/select-one-fn :is_remote_synced :model/Collection :id (u/the-id collection-or-id))))+ :else (collections.db/collection-remote-synced? (u/the-id collection-or-id))))(defn- is-library?"Is this the Library collection?"@@ -169,7 +170,7 @@(defn remote-synced-collection"Get the remote-synced collection if it exists."[]- (t2/select-one :model/Collection :is_remote_synced true :location "/"))+ (collections.db/root-remote-synced-collection))(defonce ^:dynamic ^:private *clearing-remote-sync* false)@@ -177,17 +178,17 @@"Marks any remote-synced-collection as non-remote-synced"[](binding [*clearing-remote-sync* true]- (t2/update! :model/Collection :is_remote_synced true {:is_remote_synced false})))+ (collections.db/clear-remote-synced-flags!)))(defn has-remote-synced-collection?"Return true if any collections are marked remote-sync"[]- (pos-int? (t2/count :model/Collection :is_remote_synced true)))+ (pos-int? (collections.db/remote-synced-collection-count)))(defn library-collection"Get the 'library' collection, if it exists."[]- (t2/select-one :model/Collection :type library-collection-type))+ (collections.db/collection-of-type library-collection-type))(def ^{:arglists '([id])} root-collection-type-by-id"Return the `:type` of the top-level (root) collection with the given `id`, or `nil` if no@@ -200,7 +201,7 @@^{::memoize/args-fn (fn [[id]] [(mdb/unique-identifier) id])}(fn [id](when id- (t2/select-one-fn :type :model/Collection :id id :location "/")))+ (collections.db/root-collection-type-by-id id))):ttl/threshold (* 60 60 1000)))(defn root-collection-type@@ -251,21 +252,21 @@[](when-not (nil? (library-collection))(throw (ex-info "Library already exists" {})))- (let [library (t2/insert-returning-instance! :model/Collection {:name "Library"- :type library-collection-type- :location "/"- :entity_id library-entity-id})+ (let [library (collections.db/insert-collection! {:name "Library"+ :type library-collection-type+ :location "/"+ :entity_id library-entity-id})base-location (str "/" (:id library) "/")- data (t2/insert-returning-instance! :model/Collection {:name "Data"- :type library-data-collection-type- :location base-location- :entity_id library-data-entity-id})- metrics (t2/insert-returning-instance! :model/Collection {:name "Metrics"- :type library-metrics-collection-type- :location base-location- :entity_id library-metrics-entity-id})]+ data (collections.db/insert-collection! {:name "Data"+ :type library-data-collection-type+ :location base-location+ :entity_id library-data-entity-id})+ metrics (collections.db/insert-collection! {:name "Metrics"+ :type library-metrics-collection-type+ :location base-location+ :entity_id library-metrics-entity-id})](doseq [col [library data metrics]]- (t2/delete! :model/Permissions :collection_id (:id col))+ (collections.db/delete-permissions-for-collection! (:id col))(perms/grant-collection-read-permissions! (perms/all-users-group) col)(perms/grant-collection-readwrite-permissions! (perms/data-analyst-group) col))library))@@ -326,7 +327,7 @@(mi/current-user-has-full-permissions? :write instance)(remote-sync/collection-editable? instance)))([_model pk]- (mi/can-write? (t2/select-one :model/Collection pk))))+ (mi/can-write? (collections.db/collection pk))))(mu/defmethod mi/can-read? :model/Collection([instance]@@ -334,7 +335,7 @@(perms/can-read-audit-helper :model/Collection instance)))([_model pk :- pos-int?](or (is-trash? pk)- (mi/can-read? (t2/select-one :model/Collection :id pk)))))+ (mi/can-read? (collections.db/collection pk)))))(def AuthorityLevel"Malli Schema for valid collection authority levels."@@ -429,7 +430,7 @@;; of IDs(let [ids (location-path->ids location-path)](= (count ids)- (t2/count :model/Collection :id [:in ids])))))+ (collections.db/collection-count-by-ids ids)))))(defn- assert-valid-location"Assert that the `location` property of a `collection`, if specified, is valid. This checks that it is valid both from@@ -461,7 +462,7 @@(throw (ex-info "Can't create a tenant collection without tenants enabled." {:type (:type collection)})))(when location(when-let [parent-id (location-path->parent-id location)]- (let [parent-namespace (t2/select-one-fn :namespace :model/Collection :id parent-id)]+ (let [parent-namespace (collections.db/collection-namespace parent-id)](when-not (= (keyword collection-namespace) (keyword parent-namespace))(let [msg (tru "Collection must be in the same namespace as its parent")](throw (ex-info msg {:status-code 400, :errors {:location msg}})))))))@@ -476,7 +477,7 @@If a collection's parent is remote-synced, it must also be remote-synced."[{:keys [location is_remote_synced]}](when-let [parent-id (and location (location-path->parent-id location))]- (let [parent-is-remote-synced? (t2/select-one-fn :is_remote_synced :model/Collection :id parent-id)]+ (let [parent-is-remote-synced? (collections.db/collection-remote-synced? parent-id)](when (and (or parent-is-remote-synced? is_remote_synced)(not= parent-is-remote-synced? is_remote_synced))(let [msg (if is_remote_synced@@ -519,7 +520,7 @@*from*."[collection :- CollectionWithLocationOrRoot](if-let [new-parent-id (location-path->parent-id (:location collection))]- (t2/select-one :model/Collection :id new-parent-id)+ (collections.db/collection new-parent-id)root-collection))(mu/defn children-location :- LocationPath@@ -538,7 +539,7 @@(mu/defn descendant-ids :- [:maybe [:set ms/PositiveInt]]"Return a set of IDs of all descendant Collections of a `collection`."[collection :- CollectionWithLocationAndIDOrRoot]- (t2/select-pks-set :model/Collection :location [:like (str (children-location collection) \%)]))+ (collections.db/collection-ids-with-location-like (str (children-location collection) \%)));;; +----------------------------------------------------------------------------------------------------------------+;;; | Personal Collections |@@ -566,9 +567,8 @@Returns a map of user-id -> name"[user-or-ids user-or-site](into {} (when-let [ids (seq (filter some? (map u/the-id user-or-ids)))]- (t2/select-pk->fn #(format-personal-collection-name (:first_name %) (:last_name %) (:email %) user-or-site)- [:model/User :first_name :last_name :email :id]- :id [:in ids]))))+ (update-vals (collections.db/user-name-parts-by-id ids)+ #(format-personal-collection-name (:first_name %) (:last_name %) (:email %) user-or-site)))))(mu/defn user->personal-collection-name :- ms/NonBlankString"Calls `user->personal-collection-names` for a single user-id and returns the name"@@ -633,9 +633,7 @@;; Try to get the ID of its highest-level ancestor, e.g. if `location` is `/1/2/3/` we would get `1`. Then see if;; the root-level ancestor is a Personal Collection (Personal Collections can only exist in the Root Collection.)(when-let [id (first (location-path->ids (:location collection)))]- (t2/exists? :model/Collection- :id id- :personal_owner_id [:not= nil])))))+ (collections.db/personal-collection? id)))))(def ^:private CollectionWithNamespace"Schema for a Collection instance that has a valid `:location`, and a `:namespace` key *present* (but not@@ -654,7 +652,7 @@Use [[metabase.collections.models.collection/user->personal-collection]] to fetch their personal Collection *and*create it if needed."[user-or-id]- (t2/select-one :model/Collection :personal_owner_id (u/the-id user-or-id)))+ (collections.db/personal-collection-of-user (u/the-id user-or-id)))(mu/defn user->personal-collection :- [:maybe (ms/InstanceOf :model/Collection)]"Return the Personal Collection for `user-or-id`, if it already exists; if not, create it and return it.@@ -664,9 +662,8 @@(when-not (api-key/is-api-key-user? (u/the-id user-or-id))(or (user->existing-personal-collection user-or-id)(try- (first (t2/insert-returning-instances! :model/Collection- {:name (user->personal-collection-name user-or-id :site)- :personal_owner_id (u/the-id user-or-id)}))+ (collections.db/insert-collection! {:name (user->personal-collection-name user-or-id :site)+ :personal_owner_id (u/the-id user-or-id)});; if an Exception was thrown why trying to create the Personal Collection, we can assume it was a race;; condition where some other thread created it in the meantime; try one last time to fetch it(catch Throwable e@@ -714,12 +711,9 @@[users](when (seq users);; efficiently create a map of user ID -> personal collection ID- (let [non-api-user-ids (t2/select-pks-set :model/User- :id [:in (set (map u/the-id users))]- :type [:not= :api-key])+ (let [non-api-user-ids (collections.db/non-api-key-user-ids (set (map u/the-id users)))user-id->collection-id (when (seq non-api-user-ids)- (t2/select-fn->pk :personal_owner_id :model/Collection- :personal_owner_id [:in non-api-user-ids]))]+ (collections.db/personal-collection-ids-by-owner non-api-user-ids))];; now for each User, try to find the corresponding ID out of that map. If it's not present (the personal;; Collection hasn't been created yet), then instead call `user->personal-collection-id`, which will create it;; as a side-effect. This will ensure this property never comes back as `nil`@@ -745,7 +739,7 @@[(assoc collection :is_personal (is-personal-collection-or-descendant-of-one? collection))];; root collection is nil[collection]))- (let [personal-collection-ids (t2/select-pks-set :model/Collection :personal_owner_id [:not= nil])+ (let [personal-collection-ids (collections.db/personal-collection-ids);; Personal Collections only ever live in the Root Collection, so a Collection is inside one exactly when;; the first ID of its location path is a Personal Collection. Testing that ID against the set beats;; scanning every personal collection per row: instances with thousands of each made this quadratic.@@ -805,16 +799,10 @@(fn can-access-root-collection?*[{:keys [current-user-id is-superuser?]} read-or-write](or is-superuser?- (t2/exists? :model/Permissions {:select [:p.*]- :from [[:permissions :p]]- :join [[:permissions_group :pg] [:= :pg.id :p.group_id]- [:permissions_group_membership :pgm] [:= :pgm.group_id :pg.id]]- :where [:and- [:= :pgm.user_id current-user-id]- [:or- [:= :p.object "/collection/root/"]- (when (= :read read-or-write)- [:= :p.object "/collection/root/read/"])]]})))+ (collections.db/user-has-root-collection-permission?+ current-user-id+ (cond-> ["/collection/root/"]+ (= :read read-or-write) (conj "/collection/root/read/")))));; cache the results for 10 seconds. This is a bit arbitrary but should be long enough to cover ~all requests.:ttl/threshold (* 10 1000)))@@ -1044,9 +1032,7 @@(keep location-path->parent-id))id->parent-coll (merge {nil (effective-parent-root)}(when (seq parent-ids)- (t2/select-pk->fn identity :model/Collection- {:select effective-parent-fields- :where [:in :id parent-ids]})))]+ (collections.db/collection-columns-by-id effective-parent-fields parent-ids)))](map(fn [collection](let [parent-id (-> collection :effective_location location-path->parent-id)]@@ -1060,9 +1046,7 @@(mu/defn- ancestors* :- [:maybe [:sequential (ms/InstanceOf :model/Collection)]][{:keys [location]}](when-let [ancestor-ids (seq (location-path->ids location))]- (t2/select [:model/Collection :name :id :personal_owner_id]- :id [:in ancestor-ids]- {:order-by [:location]})))+ (collections.db/ancestor-summaries ancestor-ids)))(mi/define-simple-hydration-method ancestors:ancestors@@ -1107,7 +1091,7 @@[collections](let [all-ids (mapcat #(some-> % effective-location-path location-path->ids) collections)collection-id->collection (if (seq all-ids)- (t2/select-pk->fn identity :model/Collection :id [:in all-ids])+ (collections.db/collections-by-id all-ids){})](map (fn [collection](assoc collection@@ -1136,43 +1120,32 @@"Return all descendant collections of a `collection`, including children, grandchildren, and so forth."[collection :- CollectionWithLocationAndIDOrRoot, & additional-honeysql-where-clauses](or- (t2/select [:model/Collection :name :id :location :description]- {:where (apply- vector- :and- [:like :location (str (children-location collection) "%")]- ;; Only return the Personal Collection belonging to the Current- ;; User, regardless of whether we should actually be allowed to see- ;; it (e.g., admins have perms for all Collections). This is done- ;; to keep the Root Collection View for admins from getting crazily- ;; cluttered with Personal Collections belonging to other users- [:or- [:= :personal_owner_id nil]- [:= :personal_owner_id api/*current-user-id*]]- additional-honeysql-where-clauses)})+ (collections.db/descendant-summaries-where+ (apply+ vector+ :and+ [:like :location (str (children-location collection) "%")]+ ;; Only return the Personal Collection belonging to the Current+ ;; User, regardless of whether we should actually be allowed to see+ ;; it (e.g., admins have perms for all Collections). This is done+ ;; to keep the Root Collection View for admins from getting crazily+ ;; cluttered with Personal Collections belonging to other users+ [:or+ [:= :personal_owner_id nil]+ [:= :personal_owner_id api/*current-user-id*]]+ additional-honeysql-where-clauses))[]))(mu/defn descendants-flat-for :- [:sequential CollectionWithLocationAndIDOrRoot]"Like [[descendants-flat]], but returns the descendants of *any* of`collections` in a single query. Also selects `:type`, so callers canclassify descendants without another lookup."- [collections :- [:sequential CollectionWithLocationAndIDOrRoot]- & additional-honeysql-where-clauses]+ [collections :- [:sequential CollectionWithLocationAndIDOrRoot]](if (empty? collections)[]- (t2/select [:model/Collection :name :id :location :description :type]- {:where (apply- vector- :and- (into [:or]- (map (fn [collection]- [:like :location (str (children-location collection) "%")]))- collections)- ;; same personal-collection rule as descendants-flat- [:or- [:= :personal_owner_id nil]- [:= :personal_owner_id api/*current-user-id*]]- additional-honeysql-where-clauses)})))+ (collections.db/descendant-summaries-with-type+ (map #(str (children-location %) "%") collections)+ api/*current-user-id*)))(mu/defn descendants :- [:set Children]"Return all descendant Collections of a `collection`, including children, grandchildren, and so forth. This is done@@ -1250,12 +1223,11 @@(mu/defn- effective-children* :- [:set (ms/InstanceOf :model/Collection)][collection :- CollectionWithLocationAndIDOrRoot & additional-honeysql-where-clauses]- (set (t2/select [:model/Collection :id :name :description :type]- {:where (apply effective-children-where-clause- collection- (t2/table-name :model/Collection)- default-visibility-config- additional-honeysql-where-clauses)})))+ (set (collections.db/effective-children-where (apply effective-children-where-clause+ collection+ (t2/table-name :model/Collection)+ default-visibility-config+ additional-honeysql-where-clauses))))(mi/define-simple-hydration-method effective-children:effective_children@@ -1292,14 +1264,14 @@(case model-key:model/Collection;; Collections use their own :id for eligibility, plus namespace and is_remote_synced- (t2/select [model-key :id :namespace :is_remote_synced] :id [:in ids])+ (collections.db/instances-with-columns [model-key :id :namespace :is_remote_synced] ids):model/Table- (t2/select [model-key :id :collection_id :is_published] :id [:in ids])+ (collections.db/instances-with-columns [model-key :id :collection_id :is_published] ids);; DashboardCard and DashboardCardSeries are nested under Dashboard - skip separate eligibility check(:model/DashboardCard :model/DashboardCardSeries)nil;; Default - most models just need id and collection_id- (t2/select [model-key :id :collection_id] :id [:in ids]))))+ (collections.db/instances-with-columns [model-key :id :collection_id] ids))))(defn- filter-eligible-dependents"Filter a list of dependent info maps to only include those that are eligible for remote sync.@@ -1345,10 +1317,7 @@Returns a sequence of {model-name id} maps for dependents that are eligible for remote sync."[{:keys [id archived] :as model}](let [;; Get ALL top-level remote-synced collections- all-remote-synced-roots (t2/select-pks-set :model/Collection- {:where [:and- [:= :is_remote_synced true]- [:= :location "/"]]})+ all-remote-synced-roots (collections.db/remote-synced-root-collection-ids);; Traverse descendants of all remote-synced roots combinedall-remote-synced-descendants (reduce (fn [accum root-id](merge-with concat accum@@ -1384,7 +1353,7 @@It falls out of the traversal that [[non-remote-synced-dependencies]] already runs, so reporting itcosts no extra queries."[{:keys [id] :as model}]- (if (t2/exists? :model/Collection :id (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))+ (if (collections.db/collection-exists? (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))(let [descendants (u/group-by first second (keys (traverse-descendants [(name (t2/model model)) id] true)))](into [](for [m (collectable-models)@@ -1454,9 +1423,9 @@[old-collection-id new-collection-id](boolean(and (some? new-collection-id)- (t2/exists? :model/Collection :id new-collection-id :is_remote_synced true)+ (collections.db/remote-synced-collection-exists? new-collection-id)(or (nil? old-collection-id)- (not (t2/exists? :model/Collection :id old-collection-id :is_remote_synced true))))))+ (not (collections.db/remote-synced-collection-exists? old-collection-id))))))(defn moving-from-remote-synced?"Tests if a move means the object is leaving remote-synced collections entirely.@@ -1469,9 +1438,9 @@[old-collection-id new-collection-id](boolean(and (some? old-collection-id)- (t2/exists? :model/Collection :id old-collection-id :is_remote_synced true)+ (collections.db/remote-synced-collection-exists? old-collection-id)(or (nil? new-collection-id)- (not (t2/exists? :model/Collection :id new-collection-id :is_remote_synced true))))))+ (not (collections.db/remote-synced-collection-exists? new-collection-id))))))(defn check-for-remote-sync-update"Checks collection items for remote-sync integrity during an update transaction.@@ -1485,7 +1454,7 @@Throws an ex-info object if remote-sync integrity is violated."[{id :id collection-before-update :collection_id :as model-before-update}]- (u/prog1 (t2/select-one (t2/model model-before-update) :id id)+ (u/prog1 (collections.db/instance-by-id (t2/model model-before-update) id)(let [{collection-after-update :collection_id :as model-after-update} <>](when (remote-synced-collection? collection-after-update)(check-non-remote-synced-dependencies model-after-update)@@ -1511,11 +1480,7 @@[model k items](mi/instances-with-hydrated-data items k#(into {}- (t2/select-pk->fn :namespace [model :id [:c.namespace :namespace]]- {:where [:in (keyword (str (name (t2/table-name model)) ".id"))- (map :id items)]- :join [[:collection :c]- [:= :collection_id :c.id]]}))+ (collections.db/collection-namespaces-of model (map :id items))):id{:default nil}))@@ -1541,14 +1506,12 @@(when (= (audit/default-custom-reports-collection) collection)(throw (Exception. (tru "You cannot operate on the Custom Reports Collection."))));; also make sure we're not trying to operate on a PERSONAL Collection- (when (t2/exists? :model/Collection :id (u/the-id collection), :personal_owner_id [:not= nil])+ (when (collections.db/personal-collection? (u/the-id collection))(throw (Exception. (tru "You cannot operate on a Personal Collection."))))(set(for [collection-or-id (conscollection- (t2/select-pks-set :model/Collection- :location [:like (str (children-location collection) "%")]- :archived false))]+ (collections.db/unarchived-collection-ids-with-location-like (str (children-location collection) "%")))](perms/collection-readwrite-path collection-or-id))))(mu/defn perms-for-archiving :- [:set perms/PathSchema]@@ -1604,14 +1567,9 @@(mu/defn collection->descendant-ids :- [:maybe [:set ms/PositiveInt]]"Gets the IDs of all descendant collections for a given collection.- Takes collection (a collection with location and ID or root collection) and additional-conditions (optional- additional conditions to filter descendants).-Returns a set of positive integers representing descendant collection IDs, or nil if none exist."- [collection :- CollectionWithLocationAndIDOrRoot, & additional-conditions]- (apply t2/select-pks-set :model/Collection- :location [:like (str (children-location collection) "%")]- additional-conditions))+ [collection :- CollectionWithLocationAndIDOrRoot]+ (collections.db/collection-ids-with-location-like (str (children-location collection) "%")))(mu/defn perms-for-unarchiving :- [:set perms/PathSchema]"Return the set of Permissions needed to unarchive a `collection`. Since unarchiving is@@ -1619,9 +1577,9 @@permissions for the collection and all descendants being unarchived."[collection :- CollectionWithLocationAndIDOrRoot](let [archive-operation-id (:archive_operation_id collection)- descendant-ids (collection->descendant-ids collection- :archive_operation_id [:= archive-operation-id]- :archived [:= true])]+ descendant-ids (collections.db/archived-collection-ids-in-operation-with-location-like+ (str (children-location collection) "%")+ archive-operation-id)](set(cons (perms/collection-readwrite-path collection)(map perms/collection-readwrite-path descendant-ids)))))@@ -1657,39 +1615,26 @@(t2/with-transaction [_conn](let [archive-operation-id (str (random-uuid))affected-collection-ids (cons (u/the-id collection)- (collection->descendant-ids collection- :archived [:not= true]))]- (t2/update! :model/Collection (u/the-id collection)- {:archive_operation_id archive-operation-id- :archived_directly true- :archived true})- (t2/query-one- {:update :collection- :set {:archive_operation_id archive-operation-id- :archived_directly false- :archived true}- :where [:and- [:like :location (str (children-location collection) "%")]- [:not :archived]]})- (doseq [model (apply disj (collectable-models) (archived-directly-models))]- (t2/update! model {:collection_id [:in affected-collection-ids]}- {:archived true}))- (doseq [model (archived-directly-models)]- (t2/update! model {:collection_id [:in affected-collection-ids]- :archived_directly false}- {:archived true}))- (let [library-data-ids (t2/select-pks-set :model/Collection- :id [:in affected-collection-ids]- :type library-data-collection-type)]+ (collections.db/not-yet-archived-collection-ids-with-location-like+ (str (children-location collection) "%")))]+ (collections.db/update-collection! (u/the-id collection)+ {:archive_operation_id archive-operation-id+ :archived_directly true+ :archived true})+ (collections.db/archive-descendant-collections! (str (children-location collection) "%") archive-operation-id)+ (collections.db/set-pulse-archived-in-collections! affected-collection-ids true)+ (collections.db/set-native-query-snippet-archived-in-collections! affected-collection-ids true)+ (collections.db/set-timeline-archived-in-collections! affected-collection-ids true)+ (collections.db/set-card-archived-in-collections-not-directly! affected-collection-ids true)+ (collections.db/set-dashboard-archived-in-collections-not-directly! affected-collection-ids true)+ (collections.db/set-document-archived-in-collections-not-directly! affected-collection-ids true)+ (collections.db/set-exploration-archived-in-collections-not-directly! affected-collection-ids true)+ (let [library-data-ids (collections.db/collection-ids-of-type affected-collection-ids library-data-collection-type)](when (seq library-data-ids)- (let [published-table-ids (t2/select-pks-set :model/Table- :collection_id [:in library-data-ids]- :is_published true)]- (t2/update! :model/Table {:collection_id [:in library-data-ids]}- {:collection_id nil- :is_published false})+ (let [published-table-ids (collections.db/published-table-ids-in-collections library-data-ids)]+ (collections.db/unpublish-tables-in-collections! library-data-ids)(unpublish-downstream-fk-tables! published-table-ids)))))- (let [updated-collection (t2/select-one :model/Collection :id (:id collection))]+ (let [updated-collection (collections.db/collection (:id collection))](when (:is_remote_synced updated-collection)(check-remote-synced-dependents updated-collection)))))@@ -1706,16 +1651,16 @@(:parent_id updates)current-parent-id)new-parent (if new-parent-id- (t2/select-one :model/Collection :id new-parent-id)+ (collections.db/collection new-parent-id)root-collection)new-parent-is-remote-synced? (:is_remote_synced new-parent)new-location (children-location new-parent)orig-children-location (children-location collection)new-children-location (children-location (assoc collection :location new-location))affected-collection-ids (cons (u/the-id collection)- (collection->descendant-ids collection- :archive_operation_id [:= archive-operation-id]- :archived [:= true]))]+ (collections.db/archived-collection-ids-in-operation-with-location-like+ (str (children-location collection) "%")+ archive-operation-id))](api/check-400(and (some? new-parent) (not (:archived new-parent))))(if (contains? updates :parent_id)@@ -1728,30 +1673,23 @@(api/check-403(:can_restore (t2/hydrate collection :can_restore))))(t2/with-transaction [_conn]- (t2/update! :model/Collection (u/the-id collection)- {:location new-location- :is_remote_synced (boolean new-parent-is-remote-synced?)- :archive_operation_id nil- :archived_directly nil- :archived false})- (t2/query-one- {:update :collection- :set {:location [:replace :location orig-children-location new-children-location]- :is_remote_synced (boolean new-parent-is-remote-synced?)- :archive_operation_id nil- :archived_directly nil- :archived false}- :where [:and- [:like :location (str orig-children-location "%")]- [:= :archive_operation_id (:archive_operation_id collection)]- [:not= :archived_directly true]]})- (doseq [model (apply disj (collectable-models) (archived-directly-models))]- (t2/update! model {:collection_id [:in affected-collection-ids]}- {:archived false}))- (doseq [model (archived-directly-models)]- (t2/update! model {:collection_id [:in affected-collection-ids]- :archived_directly false}- {:archived false}))+ (collections.db/update-collection! (u/the-id collection)+ {:location new-location+ :is_remote_synced (boolean new-parent-is-remote-synced?)+ :archive_operation_id nil+ :archived_directly nil+ :archived false})+ (collections.db/unarchive-descendant-collections! orig-children-location+ new-children-location+ (boolean new-parent-is-remote-synced?)+ (:archive_operation_id collection))+ (collections.db/set-pulse-archived-in-collections! affected-collection-ids false)+ (collections.db/set-native-query-snippet-archived-in-collections! affected-collection-ids false)+ (collections.db/set-timeline-archived-in-collections! affected-collection-ids false)+ (collections.db/set-card-archived-in-collections-not-directly! affected-collection-ids false)+ (collections.db/set-dashboard-archived-in-collections-not-directly! affected-collection-ids false)+ (collections.db/set-document-archived-in-collections-not-directly! affected-collection-ids false)+ (collections.db/set-exploration-archived-in-collections-not-directly! affected-collection-ids false)(when (:is_remote_synced collection)(check-non-remote-synced-dependencies collection)))))@@ -1774,7 +1712,7 @@(let [orig-children-location (children-location collection)new-children-location (children-location (assoc collection :location new-location))will-be-in-trash? (str/starts-with? new-location (trash-path))- will-be-in-remote-synced? (t2/select-one-fn :is_remote_synced :model/Collection :id (parent-id* {:location new-location}))]+ will-be-in-remote-synced? (collections.db/collection-remote-synced? (parent-id* {:location new-location}))](when will-be-in-trash?(throw (ex-info "Cannot `move-collection!` into the Trash. Call `archive-collection!` instead."{:collection collection@@ -1786,15 +1724,13 @@(u/the-id collection) (:location collection) new-location)(events/publish-event! :event/collection-touch {:collection-id (:id collection) :user-id api/*current-user-id*})(t2/with-transaction [_conn]- (t2/update! :model/Collection (u/the-id collection)- {:location new-location- :is_remote_synced (boolean will-be-in-remote-synced?)})+ (collections.db/update-collection! (u/the-id collection)+ {:location new-location+ :is_remote_synced (boolean will-be-in-remote-synced?)});; we need to update all the descendant collections as well...- (u/prog1 (t2/query-one- {:update :collection- :set {:location [:replace :location orig-children-location new-children-location]- :is_remote_synced (boolean will-be-in-remote-synced?)}- :where [:like :location (str orig-children-location "%")]})+ (u/prog1 (collections.db/move-descendant-collections! orig-children-location+ new-children-location+ (boolean will-be-in-remote-synced?))(when into-remote-synced?(check-non-remote-synced-dependencies collection))(when (moving-from-remote-synced? (parent-id* collection) (parent-id* {:location new-location}))@@ -1809,7 +1745,7 @@(defn- assert-not-personal-collection-for-api-key [collection](when-not config/is-prod?(when-let [user-id (:personal_owner_id collection)]- (when (= :api-key (t2/select-one-fn :type :model/User user-id))+ (when (= :api-key (collections.db/user-type user-id))(throw (ex-info "Can't create a personal collection for an API key" {:user user-id}))))))(t2/define-before-insert :model/Collection@@ -1829,23 +1765,23 @@and write perms for every Group with write perms for the source Collection."[source-collection-or-id dest-collections-or-ids];; figure out who has permissions for the source Collection...- (let [group-ids-with-read-perms (t2/select-fn-set :group_id :model/Permissions- :object (perms/collection-read-path source-collection-or-id))- group-ids-with-write-perms (t2/select-fn-set :group_id :model/Permissions- :object (perms/collection-readwrite-path source-collection-or-id))]+ (let [group-ids-with-read-perms (collections.db/group-ids-with-permission-object+ (perms/collection-read-path source-collection-or-id))+ group-ids-with-write-perms (collections.db/group-ids-with-permission-object+ (perms/collection-readwrite-path source-collection-or-id))];; ...and insert corresponding rows for each destination Collection- (t2/insert! :model/Permissions- (concat- ;; insert all the new read-perms records- (for [dest dest-collections-or-ids- :let [read-path (perms/collection-read-path dest)]- group-id group-ids-with-read-perms]- {:group_id group-id, :object read-path})- ;; ...and all the new write-perms records- (for [dest dest-collections-or-ids- :let [readwrite-path (perms/collection-readwrite-path dest)]- group-id group-ids-with-write-perms]- {:group_id group-id, :object readwrite-path})))+ (collections.db/insert-permissions!+ (concat+ ;; insert all the new read-perms records+ (for [dest dest-collections-or-ids+ :let [read-path (perms/collection-read-path dest)]+ group-id group-ids-with-read-perms]+ {:group_id group-id, :object read-path})+ ;; ...and all the new write-perms records+ (for [dest dest-collections-or-ids+ :let [readwrite-path (perms/collection-readwrite-path dest)]+ group-id group-ids-with-write-perms]+ {:group_id group-id, :object readwrite-path})));; update the perms graph revision number so that editors of the permissions graph are forced to be aware;; of the new permissions/collections.(perms/increment-implicit-perms-revision! :model/CollectionPermissionGraphRevision@@ -1937,11 +1873,10 @@This needs to be done recursively for all descendants as well."[collection :- (ms/InstanceOf :model/Collection)]- (t2/query-one {:delete-from :permissions- :where [:in :object (for [collection (cons collection (descendants collection))- path-fn [perms/collection-read-path- perms/collection-readwrite-path]]- (path-fn collection))]}))+ (collections.db/delete-permissions-with-objects! (for [collection (cons collection (descendants collection))+ path-fn [perms/collection-read-path+ perms/collection-readwrite-path]]+ (path-fn collection))))(defn- update-perms-when-moving-across-personal-boundry!"If a Collection is moving 'across the boundry' and will become a descendant of a Personal Collection, or will cease@@ -2054,29 +1989,23 @@(when (= (u/the-id collection) (trash-collection-id))(throw (ex-info "Fatal error: the trash collection cannot be trashed" {})));; delete all collection children- (t2/delete! :model/Collection :location (children-location collection))+ (collections.db/delete-collections-at-location! (children-location collection))(let [affected-collection-ids (cons (u/the-id collection) (collection->descendant-ids collection))- published-table-ids (t2/select-pks-set :model/Table- :collection_id [:in affected-collection-ids]- :is_published true)]- (t2/update! :model/Table :collection_id [:in affected-collection-ids] {:collection_id nil- :is_published false})+ published-table-ids (collections.db/published-table-ids-in-collections affected-collection-ids)]+ (collections.db/unpublish-tables-in-collections! affected-collection-ids)(unpublish-downstream-fk-tables! published-table-ids)- (doseq [model [:model/Card- :model/Dashboard- :model/NativeQuerySnippet- :model/Pulse- :model/Timeline]]- (t2/delete! model :collection_id [:in affected-collection-ids])))+ (collections.db/delete-cards-in-collections! affected-collection-ids)+ (collections.db/delete-dashboards-in-collections! affected-collection-ids)+ (collections.db/delete-native-query-snippets-in-collections! affected-collection-ids)+ (collections.db/delete-pulses-in-collections! affected-collection-ids)+ (collections.db/delete-timelines-in-collections! affected-collection-ids));; You can't delete a Personal Collection! Unless we enable it because we are simultaneously deleting the User(when-not *allow-deleting-personal-collections*(when (:personal_owner_id collection)(throw (Exception. (tru "You cannot delete a Personal Collection!")))));; Delete permissions records for this Collection- (t2/query-one {:delete-from :permissions- :where [:or- [:= :object (perms/collection-readwrite-path collection)]- [:= :object (perms/collection-read-path collection)]]}))+ (collections.db/delete-permissions-with-objects! [(perms/collection-readwrite-path collection)+ (perms/collection-read-path collection)]));;; -------------------------------------------------- IModel Impl ---------------------------------------------------@@ -2084,7 +2013,7 @@(defmethod mi/perms-objects-set :model/Collection[collection-or-id read-or-write](let [collection (if (integer? collection-or-id)- (t2/select-one [:model/Collection :id :namespace] :id (collection-or-id))+ (collections.db/collection-id-and-namespace collection-or-id)collection-or-id)](if (and (= (u/qualified-name (:namespace collection)) "snippets")(not (premium-features/enable-snippet-collections?)))@@ -2116,26 +2045,21 @@[:= :type nil][:not= :type trash-collection-type]]](if (seq collection-set)- (t2/reducible-select :model/Collection- {:where- [:and- (when skip-archived [:not :archived])- [:or- [:in :id collection-set]- (when (some nil? collection-set) [:= :id nil])]- not-trash-clause- (or where true)]- ;; stable filename de-dup suffixes across exports, see GHY-3754- :order-by serdes/stable-storage-order})- (t2/reducible-select :model/Collection- {:where- [:and- (when skip-archived [:not :archived])- [:= :personal_owner_id nil]- not-trash-clause- (or where true)]- ;; stable filename de-dup suffixes across exports, see GHY-3754- :order-by serdes/stable-storage-order}))))+ ;; stable filename de-dup suffixes across exports, see GHY-3754+ (collections.db/collections-for-serdes-reducible+ [:and+ (when skip-archived [:not :archived])+ [:or+ [:in :id collection-set]+ (when (some nil? collection-set) [:= :id nil])]+ not-trash-clause+ (or where true)])+ (collections.db/collections-for-serdes-reducible+ [:and+ (when skip-archived [:not :archived])+ [:= :personal_owner_id nil]+ not-trash-clause+ (or where true)]))))(defmethod serdes/deserialization-dependencies "Collection"[{:keys [parent_id]}]@@ -2154,61 +2078,36 @@(defmethod serdes/required "Collection" [_ id](when id- (let [{:keys [location]} (t2/select-one :model/Collection :id id)+ (let [{:keys [location]} (collections.db/collection id)path (location-path->ids location)];; we'll recurse anyway, so just return immediate parent(when (seq path){["Collection" (u/last path)] {"Collection" id}}))))(defmethod serdes/descendants "Collection" [_model-name id {:keys [skip-archived]}]- (let [location (when id (t2/select-one-fn :location :model/Collection :id id))+ (let [location (when id (collections.db/collection-location id))child-colls (when id ; traversing root coll will return all (even personal) colls, do not do it- (into {} (for [child-id (t2/select-pks-set :model/Collection- {:where [:and- [:= :location (str location id "/")]- (when skip-archived [:not :archived])- [:or- [:not= :type trash-collection-type]- [:= :type nil]]]})]+ (into {} (for [child-id (collections.db/child-collection-ids (str location id "/")+ trash-collection-type+ skip-archived)]{["Collection" child-id] {"Collection" id}})))- dashboards (into {} (for [dash-id (t2/select-pks-set :model/Dashboard {:where [:and- [:= :collection_id id]- (when skip-archived [:not :archived])]})]+ dashboards (into {} (for [dash-id (collections.db/dashboard-ids-in-collection id skip-archived)]{["Dashboard" dash-id] {"Collection" id}}))- cards (into {} (for [card-id (t2/select-pks-set :model/Card {:where [:and- [:= :collection_id id]- (when skip-archived [:not :archived])- ;; Cards materialized by an exploration- ;; Summary ride with that Summary, which is- ;; excluded just below. Listing them here- ;; would make them export targets whose- ;; Document dependency is absent.- [:or- [:= :document_id nil]- [:in :document_id- ^:allow-subquery {:select [:id]- :from [:document]- :where [:= :exploration_id nil]}]]]})]+ ;; Cards materialized by an exploration Summary ride with that Summary, which is excluded just below. Listing+ ;; them here would make them export targets whose Document dependency is absent.+ cards (into {} (for [card-id (collections.db/card-ids-in-collection id skip-archived)]{["Card" card-id] {"Collection" id}}))documents (when config/ee-available?- (into {} (for [doc-id (t2/select-pks-set :model/Document {:where- [:and [:= :collection_id id]- ;; Exploration documents are user scratch space — exclude from serdes/remote-sync.- [:= :exploration_id nil]- (when skip-archived [:not :archived])]})]+ ;; Exploration documents are user scratch space — exclude from serdes/remote-sync.+ (into {} (for [doc-id (collections.db/document-ids-in-collection id skip-archived)]{["Document" doc-id] {"Collection" id}})))- timelines (into {} (for [timeline-id (t2/select-pks-set :model/Timeline {:where [:and- [:= :collection_id id]- (when skip-archived [:not :archived])]})]+ timelines (into {} (for [timeline-id (collections.db/timeline-ids-in-collection id skip-archived)]{["Timeline" timeline-id] {"Collection" id}}))- tables (into {} (for [table-id (t2/select-pks-set :model/Table {:where [:and- [:= :collection_id id]- [:= :is_published true]- (when skip-archived [:= :archived_at nil])]})]+ tables (into {} (for [table-id (collections.db/published-table-ids-in-collection id skip-archived)]{["Table" table-id] {"Collection" id}}));; Transforms don't have an archived column, so we don't filter by skip-archivedtransforms (when config/ee-available?- (into {} (for [transform-id (t2/select-pks-set :model/Transform {:where [:= :collection_id id]})]+ (into {} (for [transform-id (collections.db/transform-ids-in-collection id)]{["Transform" transform-id] {"Collection" id}})))](merge child-colls dashboards cards documents timelines tables transforms)))@@ -2225,7 +2124,7 @@(if-not parent-id"/";; It would be great to use a cache rather than a database call to fetch the parent.- (let [{:keys [id location]} (t2/select-one :model/Collection parent-id)]+ (let [{:keys [id location]} (collections.db/collection parent-id)](str location id "/"))))(defmethod serdes/make-spec "Collection" [_model-name _opts]@@ -2284,7 +2183,7 @@(api/write-check root-collection));; check that the new location is not archived. the root can't be archived.(when-let [collection-id (:collection_id object-updates)]- (api/check-400 (t2/exists? :model/Collection :id collection-id :archived false)))))+ (api/check-400 (collections.db/unarchived-collection-exists? collection-id)))))(defmulti allowed-namespaces"Set of Collection namespaces (as keywords) that instances of this model are allowed to go in. By default, only the@@ -2304,7 +2203,7 @@(check-collection-namespace Card new-collection-id)"[model collection-id](when collection-id- (let [collection (or (t2/select-one [:model/Collection :namespace] :id collection-id)+ (let [collection (or (collections.db/collection-id-and-namespace collection-id)(let [msg (tru "Collection does not exist.")](throw (ex-info msg {:status-code 404:errors {:collection_id msg}}))))@@ -2437,13 +2336,11 @@(t2/hydrate archived-colls :parent_id)))parent-ids (keep val coll-id->parent-id)parent-id->archived? (when (seq parent-ids)- (t2/select-pk->fn :archived :model/Collection :id [:in parent-ids]))+ (collections.db/collection-archived-flags parent-ids));; Batch: get all descendants for all archive_operation_idsop-ids (keep :archive_operation_id archived-colls)all-descendants (when (seq op-ids)- (t2/select :model/Collection- :archive_operation_id [:in op-ids]- :archived true))+ (collections.db/archived-collections-in-operations op-ids))op-id->descendant-ids (update-vals (group-by :archive_operation_id all-descendants)#(map :id %))](for [coll colls@@ -2542,11 +2439,11 @@"Return true if the given collection ID corresponds to a collection in the library."[collection-id](when collection-id- (pos-int? (t2/count :model/Collection :id collection-id :type [:in [library-collection-type- library-data-collection-type- library-metrics-collection-type]]))))+ (pos-int? (collections.db/collection-count-of-types collection-id [library-collection-type+ library-data-collection-type+ library-metrics-collection-type]))))(defn collections-in-namespace"Return all collections in the given namespace."[namespace]- (t2/select :model/Collection :namespace (name namespace)))+ (collections.db/collections-in-namespace (name namespace)))diff --git a/src/metabase/collections/util.clj b/src/metabase/collections/util.cljindex 2dc226031c8..2ad380b0bbf 100644--- a/src/metabase/collections/util.clj+++ b/src/metabase/collections/util.clj@@ -1,22 +1,13 @@(ns metabase.collections.util(:require- [toucan2.core :as t2]))+ [metabase.collections.db :as collections.db]))(defn annotate-dashboards"Populates 'here' on dashboards (`below` is impossible since they can't contain collections)"[dashboards](let [dashboard-ids (into #{} (map :id dashboards))dashboards-containing-cards (->> (when (seq dashboard-ids)- (t2/query {:select-distinct [:dashboard_id]- :from :report_card- :where [:and- [:= :archived false]- [:in :dashboard_id dashboard-ids]- [:exists ^:allow-subquery {:select 1- :from :report_dashboardcard- :where [:and- [:= :report_dashboardcard.card_id :report_card.id]- [:= :report_dashboardcard.dashboard_id :report_card.dashboard_id]]}]]}))+ (collections.db/dashboard-ids-with-cards dashboard-ids))(map :dashboard_id)(into #{}))](for [dashboard dashboards]diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.cljindex def35ddf40d..6851258e24e 100644--- a/src/metabase/collections_rest/api.clj+++ b/src/metabase/collections_rest/api.clj@@ -13,6 +13,7 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.app-db.core :as mdb]+ [metabase.collections-rest.db :as collections-rest.db][metabase.collections.core :as collections][metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as collection.root]@@ -46,22 +47,9 @@(declare root-collection)-(defn- location-from-collection-id-clause- "Clause to restrict which collections are being selected based off collection-id. If collection-id is nil,- then restrict to the children and the grandchildren of the root collection. If collection-id is an an integer,- then restrict to that collection's parents and children."- [collection-id]- (if collection-id- [:and- [:like :location (str "%/" collection-id "/%")]- [:not [:like :location (str "%/" collection-id "/%/%/%")]]]- [:not [:like :location "/%/%/"]]))-(defn- remove-other-users-personal-subcollections[user-id collections]- (let [personal-ids (set (t2/select-fn-set :id :model/Collection- {:where- [:and [:!= :personal_owner_id nil] [:!= :personal_owner_id user-id]]}))+ (let [personal-ids (set (collections-rest.db/other-users-personal-collection-ids user-id))personal-descendant? (fn [collection](let [first-parent-collection-id (-> collection:location@@ -84,49 +72,8 @@To include library collections and their descendants, pass in `include-library?` as `true`.By default, library-type collections are excluded. "- [{:keys [archived exclude-other-user-collections namespaces shallow collection-id personal-only include-library?]}]- (cond->>- (t2/select :model/Collection- {:where [:and- (case archived- nil nil- false [:and- [:not= :id (collection/trash-collection-id)]- [:not :archived]]- true [:or- [:= :id (collection/trash-collection-id)]- :archived])- (when shallow- (location-from-collection-id-clause collection-id))- (when personal-only- [:!= :personal_owner_id nil])- (when exclude-other-user-collections- [:or [:= :personal_owner_id nil] [:= :personal_owner_id api/*current-user-id*]])- (when-not include-library?- [:or [:= nil :type]- [:not-in :type [collection/library-collection-type- collection/library-data-collection-type- collection/library-metrics-collection-type]]])- [:or- (when (contains? namespaces nil)- [:= :namespace nil])- (when (seq namespaces)- [:in :namespace namespaces])]- (collection/visible-collection-filter-clause- :id- {:include-archived-items (if archived- :only- :exclude)- :include-trash-collection? true- :permission-level :read- :archive-operation-id nil})]- ;; Order NULL collection types first so that audit collections are last- :order-by [[[[:case [:= :authority_level "official"] 0 :else 1]] :asc]- [[[:case- [:= :type nil] 0- [:= :type collection/trash-collection-type] 1- :else 2]] :asc]- [:%lower.name :asc]]})+ [{:keys [exclude-other-user-collections] :as options}]+ (cond->> (collections-rest.db/collections-for-listing options api/*current-user-id*)exclude-other-user-collections(remove-other-users-personal-subcollections api/*current-user-id*)))@@ -280,16 +227,10 @@{:dataset #{}:metric #{}:card #{}}- (t2/reducible-query {:select-distinct [:collection_id :type]- :from [:report_card]- :where [:= :archived false]}))+ (collections-rest.db/unarchived-card-collection-types-reducible));; Tables in collections are an EE feature (library)(when (premium-features/has-feature? :library)- {:table (->> (t2/query {:select-distinct [:collection_id]- :from :metabase_table- :where [:and- [:= :is_published true]- [:= :archived_at nil]]})+ {:table (->> (collections-rest.db/published-table-collection-ids)(map :collection_id)(into #{}))}))collections-with-details (map prep-collection-for-export collections)]@@ -436,8 +377,7 @@"/"))(dissoc :namespace)(update :archived api/bit->boolean)- (update :archived_directly api/bit->boolean)))- :can_write :can_restore :can_delete :is_remote_synced :collection_namespace))))+ (update :archived_directly api/bit->boolean))) :can_write :can_restore :can_delete :is_remote_synced :collection_namespace))))(defmethod collection-children-query :document[_ collection {:keys [archived? pinned-state show-exploration-documents?]}]@@ -483,8 +423,7 @@(collection/children-location collection))"/"))(update :archived api/bit->boolean)- (update :archived_directly api/bit->boolean)))- :can_write :can_restore :can_delete))+ (update :archived_directly api/bit->boolean))) :can_write :can_restore :can_delete))(def ^:private exploration-recent-edits-subquery;; Per-exploration latest edit, unioning the Exploration's own metadata revisions with@@ -916,24 +855,15 @@:metric #{}:card #{}}(when (seq descendant-collection-ids)- (t2/reducible-query {:select-distinct [:collection_id :type]- :from [:report_card]- :where [:and- (when-not show-dashboard-questions?- [:= :dashboard_id nil])- [:= :archived false]- [:in :collection_id descendant-collection-ids]]})))+ (collections-rest.db/unarchived-card-collection-types-in-reducible+ descendant-collection-ids+ (not show-dashboard-questions?))));; Tables in collections are an EE feature (library)collections-containing-tables(if (premium-features/has-feature? :library)(->> (when (seq descendant-collection-ids)- (t2/query {:select-distinct [:collection_id]- :from :metabase_table- :where [:and- [:= :is_published true]- [:= :archived_at nil]- [:in :collection_id descendant-collection-ids]]}))+ (collections-rest.db/published-table-collection-ids-in descendant-collection-ids))(map :collection_id)(into #{}))#{})@@ -941,22 +871,14 @@collections-containing-transforms(if (seq (transforms.gating/enabled-source-types))(->> (when (seq descendant-collection-ids)- (t2/query {:select-distinct [:collection_id]- :from :transform- :where [:and- [:in :collection_id descendant-collection-ids]- [:in :source_type (transforms.gating/enabled-source-types)]]}))+ (collections-rest.db/transform-collection-ids-in descendant-collection-ids (transforms.gating/enabled-source-types)))(map :collection_id)(into #{}))#{})collections-containing-dashboards(->> (when (seq descendant-collection-ids)- (t2/query {:select-distinct [:collection_id]- :from :report_dashboard- :where [:and- [:= :archived false]- [:in :collection_id descendant-collection-ids]]}))+ (collections-rest.db/unarchived-dashboard-collection-ids-in descendant-collection-ids))(map :collection_id)(into #{}))@@ -1315,13 +1237,7 @@[collection :- collection/CollectionWithLocationAndIDOrRoot](-> collectionprep-collection-for-export- (t2/hydrate :parent_id- :effective_location- [:effective_ancestors :can_write]- :can_write- :is_personal- :can_restore- :can_delete)))+ (t2/hydrate :parent_id :effective_location [:effective_ancestors :can_write] :can_write :is_personal :can_restore :can_delete)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -1352,11 +1268,7 @@"Implementation for the `dashboard-question-candidates` endpoints."[collection-id](api/check-403 api/*is-superuser?*)- (let [all-cards-in-collection (t2/hydrate (t2/select :model/Card {:where [:and- [:= :collection_id collection-id]- [:= :dashboard_id nil]]- :order-by [[:id :desc]]})- :in_dashboards)]+ (let [all-cards-in-collection (t2/hydrate (collections-rest.db/top-level-cards-in-collection collection-id) :in_dashboards)](filter(fn [card](and@@ -1582,7 +1494,7 @@users just as if they had be archived individually via the card API."[& {:keys [collection-before-update collection-updates actor]}](when (api/column-will-change? :archived collection-before-update collection-updates)- (doseq [card (t2/select :model/Card :collection_id (u/the-id collection-before-update))]+ (doseq [card (collections-rest.db/cards-in-collection (u/the-id collection-before-update))](notification/delete-card-notifications-and-notify! :event/card-update.notification-deleted.card-archived actor card))))(defn- move-collection!@@ -1594,7 +1506,7 @@(let [orig-location (:location collection-before-update)new-parent-id (:parent_id collection-updates)new-parent (if new-parent-id- (t2/select-one [:model/Collection :location :id :type] :id new-parent-id)+ (collections-rest.db/collection-location-columns new-parent-id)collection/root-collection)new-location (collection/children-location new-parent)];; check and make sure we're actually supposed to be moving something@@ -1761,14 +1673,14 @@;; that's not actually a property of Collection, and since we handle moving a Collection separately below.(let [updates (u/select-keys-when collection-updates :present [:name :description :authority_level])](when (seq updates)- (t2/update! :model/Collection id updates)))+ (collections-rest.db/update-collection! id updates)));; if we're trying to move or archive the Collection, go ahead and do that(move-or-archive-collection-if-needed! collection-before-update collection-updates)- (let [updated-collection (t2/select-one :model/Collection :id id)]+ (let [updated-collection (collections-rest.db/collection id)](events/publish-event! :event/collection-update {:object updated-collection :user-id api/*current-user-id*})(events/publish-event! :event/collection-touch {:collection-id id :user-id api/*current-user-id*})));; finally, return the updated object- (collection-detail (t2/select-one :model/Collection :id id)))+ (collection-detail (collections-rest.db/collection id)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -1779,7 +1691,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](api/check-403 api/*is-superuser?*)- (let [collection (t2/select-one :model/Collection id)+ (let [collection (collections-rest.db/collection id)old-children-location (collection/children-location collection)new-children-location (:location collection)](api/check-400 (:archived collection)@@ -1791,12 +1703,10 @@"Personal collections cannot be deleted.")(t2/with-transaction [_tx];; First, move all children (along with their children) that were archived directly OUT of this collection- (doseq [child (t2/select :model/Collection- :location [:like (str old-children-location "%")]- :archived_directly true)]+ (doseq [child (collections-rest.db/directly-archived-descendant-collections old-children-location)](collection/move-collection! child new-children-location));; Now we can safely delete this collection and anything left under it.- (t2/delete! :model/Collection :id id))))+ (collections-rest.db/delete-collection! id))));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST APIdiff --git a/src/metabase/collections_rest/db.clj b/src/metabase/collections_rest/db.cljnew file mode 100644index 00000000000..08112c56896--- /dev/null+++ b/src/metabase/collections_rest/db.clj@@ -0,0 +1,167 @@+(ns metabase.collections-rest.db+ "Application database queries for the collections REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.collections.models.collection :as collection]+ [toucan2.core :as t2]))++(defn other-users-personal-collection-ids+ "The ids of the personal Collections owned by Users other than `user-id`."+ [user-id]+ (t2/select-fn-set :id :model/Collection+ {:where [:and [:!= :personal_owner_id nil] [:!= :personal_owner_id user-id]]}))++(defn- location-from-collection-id-clause+ "Clause to restrict which collections are being selected based off collection-id. If collection-id is nil,+ then restrict to the children and the grandchildren of the root collection. If collection-id is an an integer,+ then restrict to that collection's parents and children."+ [collection-id]+ (if collection-id+ [:and+ [:like :location (str "%/" collection-id "/%")]+ [:not [:like :location (str "%/" collection-id "/%/%/%")]]]+ [:not [:like :location "/%/%/"]]))++(defn collections-for-listing+ "The Collections the User with `current-user-id` can read, for the listing endpoint: archived or unarchived ones+ (`archived`), only those around `collection-id` when `shallow`, only personal ones when `personal-only`, only the+ user's own personal ones when `exclude-other-user-collections`, library ones only when `include-library?`, and+ those in `namespaces`; official and non-trash Collections first, then by name."+ [{:keys [archived exclude-other-user-collections namespaces shallow collection-id personal-only include-library?]}+ current-user-id]+ (t2/select :model/Collection+ {:where [:and+ (case archived+ nil nil+ false [:and+ [:not= :id (collection/trash-collection-id)]+ [:not :archived]]+ true [:or+ [:= :id (collection/trash-collection-id)]+ :archived])+ (when shallow+ (location-from-collection-id-clause collection-id))+ (when personal-only+ [:!= :personal_owner_id nil])+ (when exclude-other-user-collections+ [:or [:= :personal_owner_id nil] [:= :personal_owner_id current-user-id]])+ (when-not include-library?+ [:or [:= nil :type]+ [:not-in :type [collection/library-collection-type+ collection/library-data-collection-type+ collection/library-metrics-collection-type]]])+ [:or+ (when (contains? namespaces nil)+ [:= :namespace nil])+ (when (seq namespaces)+ [:in :namespace namespaces])]+ (collection/visible-collection-filter-clause+ :id+ {:include-archived-items (if archived+ :only+ :exclude)+ :include-trash-collection? true+ :permission-level :read+ :archive-operation-id nil})]+ ;; Order NULL collection types first so that audit collections are last+ :order-by [[[[:case [:= :authority_level "official"] 0 :else 1]] :asc]+ [[[:case+ [:= :type nil] 0+ [:= :type collection/trash-collection-type] 1+ :else 2]] :asc]+ [:%lower.name :asc]]}))++(defn collection+ "The Collection with `id`, or nil."+ [id]+ (t2/select-one :model/Collection :id id))++(defn collection-location-columns+ "The location, id, and type of the Collection with `id`, or nil."+ [id]+ (t2/select-one [:model/Collection :location :id :type] :id id))++(defn directly-archived-descendant-collections+ "The directly archived Collections whose location starts with `location-prefix`."+ [location-prefix]+ (t2/select :model/Collection :location [:like (str location-prefix "%")] :archived_directly true))++(defn update-collection!+ "Apply `changes` to the Collection with `id`."+ [id changes]+ (t2/update! :model/Collection id changes))++(defn delete-collection!+ "Delete the Collection with `id`."+ [id]+ (t2/delete! :model/Collection :id id))++(defn unarchived-card-collection-types-reducible+ "A reducible of the distinct Collection id and type of the unarchived Cards."+ []+ (t2/reducible-query {:select-distinct [:collection_id :type]+ :from [:report_card]+ :where [:= :archived false]}))++(defn unarchived-card-collection-types-in-reducible+ "A reducible of the distinct Collection id and type of the unarchived Cards in the Collections with+ `collection-ids`, leaving out dashboard questions when `exclude-dashboard-questions?`."+ [collection-ids exclude-dashboard-questions?]+ (t2/reducible-query {:select-distinct [:collection_id :type]+ :from [:report_card]+ :where [:and+ (when exclude-dashboard-questions?+ [:= :dashboard_id nil])+ [:= :archived false]+ [:in :collection_id collection-ids]]}))++(defn published-table-collection-ids+ "The distinct `:collection_id`s of the published, unarchived Tables."+ []+ (t2/query {:select-distinct [:collection_id]+ :from :metabase_table+ :where [:and+ [:= :is_published true]+ [:= :archived_at nil]]}))++(defn published-table-collection-ids-in+ "The distinct `:collection_id`s of the published, unarchived Tables in the Collections with `collection-ids`."+ [collection-ids]+ (t2/query {:select-distinct [:collection_id]+ :from :metabase_table+ :where [:and+ [:= :is_published true]+ [:= :archived_at nil]+ [:in :collection_id collection-ids]]}))++(defn transform-collection-ids-in+ "The distinct `:collection_id`s of the Transforms with one of `source-types` in the Collections with+ `collection-ids`."+ [collection-ids source-types]+ (t2/query {:select-distinct [:collection_id]+ :from :transform+ :where [:and+ [:in :collection_id collection-ids]+ [:in :source_type source-types]]}))++(defn unarchived-dashboard-collection-ids-in+ "The distinct `:collection_id`s of the unarchived Dashboards in the Collections with `collection-ids`."+ [collection-ids]+ (t2/query {:select-distinct [:collection_id]+ :from :report_dashboard+ :where [:and+ [:= :archived false]+ [:in :collection_id collection-ids]]}))++(defn top-level-cards-in-collection+ "The Cards in the Collection with `collection-id` that belong to no Dashboard, newest first."+ [collection-id]+ (t2/select :model/Card {:where [:and+ [:= :collection_id collection-id]+ [:= :dashboard_id nil]]+ :order-by [[:id :desc]]}))++(defn cards-in-collection+ "The Cards in the Collection with `collection-id`."+ [collection-id]+ (t2/select :model/Card :collection_id collection-id))diff --git a/src/metabase/comments/api.clj b/src/metabase/comments/api.cljindex 6240be62368..d681c5d5316 100644--- a/src/metabase/comments/api.clj+++ b/src/metabase/comments/api.clj@@ -1,22 +1,19 @@(ns metabase.comments.api"`/api/comment/` routes"(:require- [honey.sql.helpers :as sql.helpers][metabase.analytics.core :as analytics][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.channel.render.core :as channel.render][metabase.channel.urls :as channel.urls]+ [metabase.comments.db :as comments.db][metabase.comments.models.comment :as comment][metabase.comments.models.comment-reaction :as comment-reaction][metabase.comments.render :as comments.render][metabase.events.core :as events][metabase.models.interface :as mi][metabase.request.core :as request]- [metabase.users.core :as users]- [metabase.users.models.user :as user]- [metabase.users.settings :as users.settings][metabase.util :as u][metabase.util.i18n :refer [deferred-tru]][metabase.util.malli :as mu]@@ -148,11 +145,7 @@{:disabled true:comments []}(let [_entity (api/read-check (type->model target_type) target_id)- comments (-> (t2/select :model/Comment- {:where [:and- [:= :target_type target_type]- [:= :target_id target_id]]- :order-by [[:created_at :asc]]})+ comments (-> (comments.db/comments-for-target target_type target_id)(t2/hydrate :creator :reactions))];; The read check above only proves the viewer may see the *target*, and for an exploration;; that is collection permissions alone; the gate is what adjudicates the warehouse values a@@ -163,7 +156,7 @@"Restrict mentioned user ids to active users who can themselves read `entity`."[entity mention-ids](when (seq mention-ids)- (->> (t2/select-pks-set :model/User :id [:in mention-ids] :is_active true)+ (->> (comments.db/active-user-ids mention-ids)(filterv (fn [user-id](request/with-current-user user-id(mi/can-read? entity)))))))@@ -173,22 +166,15 @@[{:keys [target_type target_id parent_comment_id] :as comment}& [{:keys [entity parent];; if you don't pass them we'll try to fetch them- :or {entity (t2/select-one (type->model target_type) :id target_id)+ :or {entity (case target_type+ "document" (comments.db/document target_id)+ "exploration" (comments.db/exploration target_id))parent (when parent_comment_id- (t2/select-one :model/Comment :id parent_comment_id))}}]]- (let [clause (if parent_comment_id- {:where [:in :id ^:allow-subquery {:from [:comment]- :select [:creator_id]- :where [:or- [:= :id parent_comment_id]- [:= :parent_comment_id parent_comment_id]]}]}- ;; TODO: when we expand to more entity types, add dispatch here if not everyone has `creator_id`- {:where [:= :id (:creator_id entity)]})- mentions (->> (comment/mentions (:content comment))+ (comments.db/comment-by-id parent_comment_id))}}]]+ (let [mentions (->> (comment/mentions (:content comment))(mentioned-ids-who-can-read entity))- recipients (-> (t2/select-fn-set :email [:model/User :email]- (cond-> clause- (seq mentions) (sql.helpers/where :or [:in :id mentions])))+ ;; TODO: when we expand to more entity types, add dispatch here if not everyone has `creator_id`+ recipients (-> (comments.db/comment-recipient-emails (:creator_id entity) parent_comment_id mentions)(disj (:email @api/*current-user*)))payload {:entity_type (friendly-entity-type-for entity):entity_title (:name entity)@@ -208,7 +194,7 @@(defn notify-comment-id!"Send a notification using only comment id"[comment-id]- (notify-comment! (-> (t2/select-one :model/Comment :id comment-id)+ (notify-comment! (-> (comments.db/comment-by-id comment-id)(t2/hydrate :creator :reactions))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -225,20 +211,19 @@"Cannot comment on archived entities")));; If this is a reply, validate the parent comment exists and belongs to same entityparent (when parent_comment_id- (-> (api/check-404 (t2/select-one :model/Comment :id parent_comment_id))+ (-> (api/check-404 (comments.db/comment-by-id parent_comment_id))(u/prog1 (api/check-400 (and (= (:target_type <>) target_type)(= (:target_id <>) target_id)(= (:child_target_id <>) child_target_id))"Parent comment doesn't belong to the same entity"))(t2/hydrate :creator)))- comment (-> (t2/insert-returning-instance! :model/Comment- {:target_type target_type- :target_id target_id- :child_target_id child_target_id- :context context- :parent_comment_id parent_comment_id- :content content- :creator_id api/*current-user-id*})+ comment (-> (comments.db/insert-comment! {:target_type target_type+ :target_id target_id+ :child_target_id child_target_id+ :context context+ :parent_comment_id parent_comment_id+ :content content+ :creator_id api/*current-user-id*})(t2/hydrate :creator);; New comments always have empty reactions map(assoc :reactions []))]@@ -257,7 +242,7 @@[{:keys [comment-id]} :- [:map [:comment-id ms/PositiveInt]]_query-params{:keys [content is_resolved]} :- UpdateComment]- (let [comment (api/check-404 (t2/select-one :model/Comment :id comment-id))+ (let [comment (api/check-404 (comments.db/comment-by-id comment-id))entity (-> (api/read-check (type->model (:target_type comment)) (:target_id comment))(u/prog1 (api/check-400 (not (entity-archived? <>))"Cannot edit comments on archived entities")))]@@ -274,8 +259,8 @@(when-let [updates (-> {:content content :is_resolved is_resolved}u/remove-nilsnot-empty)]- (t2/update! :model/Comment comment-id updates))- (let [updated-comment (-> (t2/select-one :model/Comment :id comment-id)+ (comments.db/update-comment! comment-id updates))+ (let [updated-comment (-> (comments.db/comment-by-id comment-id)(t2/hydrate :creator :reactions))](events/publish-event! :event/comment-update{:object updated-comment@@ -290,7 +275,7 @@"Soft delete a comment"[{:keys [comment-id]} :- [:map [:comment-id ms/PositiveInt]]_query-params]- (let [comment (api/check-404 (t2/select-one :model/Comment :id comment-id))]+ (let [comment (api/check-404 (comments.db/comment-by-id comment-id))](-> (api/read-check (type->model (:target_type comment)) (:target_id comment))(u/prog1 (api/check-400 (not (entity-archived? <>))"Cannot delete comments on archived entities")))@@ -299,7 +284,7 @@(:is_superuser @api/*current-user*)))(api/check-400 (not (:deleted_at comment)) "Comment is already deleted");; Soft delete the comment- (t2/update! :model/Comment comment-id {:deleted_at [:now]})+ (comments.db/soft-delete-comment! comment-id)(events/publish-event! :event/comment-delete{:object comment:user-id api/*current-user-id*})@@ -315,7 +300,7 @@[{:keys [comment-id]} :- [:map [:comment-id ms/PositiveInt]]_query-params{:keys [emoji]} :- [:map [:emoji [:string {:min 1 :max 10}]]]]- (let [comment (api/check-404 (t2/select-one :model/Comment :id comment-id))]+ (let [comment (api/check-404 (comments.db/comment-by-id comment-id))](api/check-400 (not (:deleted_at comment))"Cannot react to deleted comments")(-> (api/read-check (type->model (:target_type comment)) (:target_id comment))@@ -323,21 +308,6 @@"Cannot react to comments on archived entities")))(comment-reaction/toggle-reaction comment-id api/*current-user-id* emoji)))-(defn- restrict-to-visible-users- "Narrow user-listing `clauses` to the users the current user should see, matching the scoping used by- `GET /api/user/recipients`: superusers see everyone; everyone else is limited to their own tenant and- further narrowed by the `user-visibility` setting."- [clauses]- (if api/*is-superuser?*- clauses- (let [clauses (sql.helpers/where clauses [:= :tenant_id (:tenant_id @api/*current-user*)])]- (case (users.settings/user-visibility)- :all clauses- :group (sql.helpers/where clauses [:in :core_user.id (-> (user/same-groups-user-ids api/*current-user-id*)- (set)- (conj api/*current-user-id*))])- :none (sql.helpers/where clauses [:= :core_user.id api/*current-user-id*])))))-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;@@ -347,22 +317,11 @@[_route _query _body req];; no access in embedding context(api/check-404 (not (analytics/embedding-context? (get-in req [:headers "x-metabase-client"]))))- (let [clauses (->- (user/filter-clauses {:limit (request/limit)- :offset (request/offset)})- restrict-to-visible-users)]- {:data (->> (t2/select [:model/User :id :first_name :last_name :email]- (-> clauses- (sql.helpers/order-by [:%lower.first_name :asc]- [:%lower.last_name :asc]- [:id :asc])))- (mapv #(assoc % :model "user")))- :total (:count (t2/query-one- (merge {:select [[[:count [:distinct :core_user.id]] :count]]- :from :core_user}- (users/filter-clauses-without-paging clauses))))- :limit (request/limit)- :offset (request/offset)}))+ {:data (->> (comments.db/mentionable-users (request/limit) (request/offset))+ (mapv #(assoc % :model "user")))+ :total (:count (comments.db/mentionable-user-count))+ :limit (request/limit)+ :offset (request/offset)})(def ^{:arglists '([request respond raise])} routes"`/api/comment/` routes."diff --git a/src/metabase/comments/db.clj b/src/metabase/comments/db.cljnew file mode 100644index 00000000000..d497aa1d58d--- /dev/null+++ b/src/metabase/comments/db.clj@@ -0,0 +1,132 @@+(ns metabase.comments.db+ "Application database queries for the comments module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [metabase.api.common :as api]+ [metabase.users.core :as users]+ [metabase.users.models.user :as user]+ [metabase.users.settings :as users.settings]+ [toucan2.core :as t2]))++(defn comments-for-target+ "The Comments on the target with `target-type` and `target-id`, oldest first."+ [target-type target-id]+ (t2/select :model/Comment+ {:where [:and+ [:= :target_type target-type]+ [:= :target_id target-id]]+ :order-by [[:created_at :asc]]}))++(defn active-user-ids+ "The ids among `user-ids` of active Users, or nil."+ [user-ids]+ (t2/select-pks-set :model/User :id [:in user-ids] :is_active true))++(defn document+ "The Document with `id`, or nil."+ [id]+ (t2/select-one :model/Document :id id))++(defn exploration+ "The Exploration with `id`, or nil."+ [id]+ (t2/select-one :model/Exploration :id id))++(defn comment-by-id+ "The Comment with `id`, or nil."+ [id]+ (t2/select-one :model/Comment :id id))++(defn comment-recipient-emails+ "The emails of the Users to notify about a comment: the authors of the Comment with `parent-comment-id` and of its+ replies, or the User with `creator-id` for a top-level comment, plus the Users with `mention-ids`."+ [creator-id parent-comment-id mention-ids]+ (t2/select-fn-set :email [:model/User :email]+ {:where [:or+ (if parent-comment-id+ [:in :id ^:allow-subquery {:from [:comment]+ :select [:creator_id]+ :where [:or+ [:= :id parent-comment-id]+ [:= :parent_comment_id parent-comment-id]]}]+ [:= :id creator-id])+ (when (seq mention-ids)+ [:in :id mention-ids])]}))++(defn insert-comment!+ "Insert the Comment `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Comment row))++(defn update-comment!+ "Apply `changes` to the Comment with `id`."+ [id changes]+ (t2/update! :model/Comment id changes))++(defn soft-delete-comment!+ "Mark the Comment with `id` deleted now."+ [id]+ (t2/update! :model/Comment id {:deleted_at [:now]}))++(defn- restrict-to-visible-users+ "Narrow `clauses` (from `user/filter-clauses`) to the users the current user should see: superusers see+ everyone; everyone else is limited to their own tenant and further narrowed by the `user-visibility`+ setting."+ [clauses]+ (if api/*is-superuser?*+ clauses+ (let [clauses (sql.helpers/where clauses [:= :tenant_id (:tenant_id @api/*current-user*)])]+ (case (users.settings/user-visibility)+ :all clauses+ :group (sql.helpers/where clauses [:in :core_user.id (-> (user/same-groups-user-ids api/*current-user-id*)+ set+ (conj api/*current-user-id*))])+ :none (sql.helpers/where clauses [:= :core_user.id api/*current-user-id*])))))++(defn mentionable-users+ "The id, first name, last name, and email of the active Users the current user may @mention, ordered by name+ then id, limited to `limit` starting at `offset`."+ [limit offset]+ (t2/select [:model/User :id :first_name :last_name :email]+ (-> (user/filter-clauses {:limit limit :offset offset})+ restrict-to-visible-users+ (sql.helpers/order-by [:%lower.first_name :asc]+ [:%lower.last_name :asc]+ [:id :asc]))))++(defn mentionable-user-count+ "The `:count` of the active Users the current user may @mention."+ []+ (t2/query-one (merge {:select [[[:count [:distinct :core_user.id]] :count]]+ :from :core_user}+ (-> (user/filter-clauses {})+ restrict-to-visible-users+ users/filter-clauses-without-paging))))++(defn users-by-id+ "A map of User id to the id, email, and name of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))++(defn reaction-exists?+ "Whether the User with `user-id` has reacted to the Comment with `comment-id` with `emoji`."+ [comment-id user-id emoji]+ (t2/exists? :model/CommentReaction :comment_id comment-id :user_id user-id :emoji emoji))++(defn insert-reaction!+ "Insert a CommentReaction by the User with `user-id` on the Comment with `comment-id` with `emoji`."+ [comment-id user-id emoji]+ (t2/insert! :model/CommentReaction {:comment_id comment-id, :user_id user-id, :emoji emoji}))++(defn delete-reaction!+ "Delete the CommentReaction by the User with `user-id` on the Comment with `comment-id` with `emoji`."+ [comment-id user-id emoji]+ (t2/delete! :model/CommentReaction :comment_id comment-id :user_id user-id :emoji emoji))++(defn reactions-for-comments+ "The CommentReactions on the Comments with `comment-ids`, ordered by comment, time, and emoji."+ [comment-ids]+ (t2/select :model/CommentReaction+ {:where [:in :comment_id comment-ids]+ :order-by [[:comment_id :asc] [:created_at :asc] [:emoji :asc]]}))diff --git a/src/metabase/comments/models/comment.clj b/src/metabase/comments/models/comment.cljindex ee81cf04474..c451442d216 100644--- a/src/metabase/comments/models/comment.clj+++ b/src/metabase/comments/models/comment.clj@@ -3,6 +3,7 @@[clojure.string :as str][metabase.api.common :as api][metabase.channel.urls :as channel.urls]+ [metabase.comments.db :as comments.db][metabase.comments.models.comment-reaction :as comment-reaction][metabase.models.interface :as mi][methodical.core :as methodical]@@ -29,8 +30,8 @@[_model k comments](mi/instances-with-hydrated-datacomments k- #(t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id (keep :creator_id comments))+ #(when-let [creator-ids (seq (keep :creator_id comments))]+ (comments.db/users-by-id creator-ids)):creator_id{:default {}}))diff --git a/src/metabase/comments/models/comment_reaction.clj b/src/metabase/comments/models/comment_reaction.cljindex 5804d39dddf..2f5910202ba 100644--- a/src/metabase/comments/models/comment_reaction.clj+++ b/src/metabase/comments/models/comment_reaction.clj@@ -1,6 +1,7 @@(ns metabase.comments.models.comment-reaction"Model for comment reactions (emoji reactions on comments)"(:require+ [metabase.comments.db :as comments.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -14,8 +15,8 @@[_model k reactions](mi/instances-with-hydrated-datareactions k- #(t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id (map :user_id reactions))+ #(when-let [user-ids (seq (map :user_id reactions))]+ (comments.db/users-by-id user-ids)):user_id {:default {}}));;; Helpers@@ -23,26 +24,17 @@(defn reaction-exists?"Check if a reaction already exists for a given comment, user, and emoji"[comment-id user-id emoji]- (t2/exists? :model/CommentReaction- :comment_id comment-id- :user_id user-id- :emoji emoji))+ (comments.db/reaction-exists? comment-id user-id emoji))(defn create-reaction!"Create a new reaction"[comment-id user-id emoji]- (t2/insert! :model/CommentReaction- {:comment_id comment-id- :user_id user-id- :emoji emoji}))+ (comments.db/insert-reaction! comment-id user-id emoji))(defn delete-reaction!"Delete a specific reaction"[comment-id user-id emoji]- (t2/delete! :model/CommentReaction- :comment_id comment-id- :user_id user-id- :emoji emoji))+ (comments.db/delete-reaction! comment-id user-id emoji))(defn toggle-reaction"Toggle a reaction - add it if it doesn't exist, remove it if it does"@@ -67,9 +59,7 @@Returns a map of `{comment-id {emoji [user1 user2...]}}."[current-user-id comment-ids](when (seq comment-ids)- (let [reactions (-> (t2/select :model/CommentReaction- {:where [:in :comment_id comment-ids]- :order-by [[:comment_id :asc] [:created_at :asc] [:emoji :asc]]})+ (let [reactions (-> (comments.db/reactions-for-comments comment-ids)(t2/hydrate :user));; first user comes first if they reacteddiff --git a/src/metabase/content_translation/db.clj b/src/metabase/content_translation/db.cljnew file mode 100644index 00000000000..23145e0227c--- /dev/null+++ b/src/metabase/content_translation/db.clj@@ -0,0 +1,15 @@+(ns metabase.content-translation.db+ "Application database queries for the content translation module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn translations-for-locale+ "The ContentTranslations for `locale`, ordered by message id."+ [locale]+ (t2/select :model/ContentTranslation :locale locale {:order-by [:msgid]}))++(defn all-translations+ "Every ContentTranslation, ordered by locale and message id."+ []+ (t2/select :model/ContentTranslation {:order-by [:locale :msgid]}))diff --git a/src/metabase/content_translation/models.clj b/src/metabase/content_translation/models.cljindex 1ecfca2048e..4e9c1d97b2c 100644--- a/src/metabase/content_translation/models.clj+++ b/src/metabase/content_translation/models.clj@@ -1,6 +1,7 @@(ns metabase.content-translation.models"A model representing dictionary entries for translations."(:require+ [metabase.content-translation.db :as content-translation.db][metabase.premium-features.core :as premium-features][metabase.util.i18n :refer [tru]][methodical.core :as methodical]@@ -21,5 +22,5 @@([locale](premium-features/assert-has-feature :content-translation (tru "Content translation"))(if locale- (t2/select :model/ContentTranslation :locale locale {:order-by [:msgid]})- (t2/select :model/ContentTranslation {:order-by [:locale :msgid]}))))+ (content-translation.db/translations-for-locale locale)+ (content-translation.db/all-translations))))diff --git a/src/metabase/content_verification/db.clj b/src/metabase/content_verification/db.cljnew file mode 100644index 00000000000..ea3c42a9c36--- /dev/null+++ b/src/metabase/content_verification/db.clj@@ -0,0 +1,45 @@+(ns metabase.content-verification.db+ "Application database queries for the content verification module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn moderation-reviews-for-items+ "The ModerationReviews of the items with `item-types` and `item-ids`, newest first."+ [item-types item-ids]+ (t2/select :model/ModerationReview+ :moderated_item_type [:in item-types]+ :moderated_item_id [:in item-ids]+ {:order-by [[:id :desc]]}))++(defn users+ "The Users with `user-ids`."+ [user-ids]+ (t2/select :model/User :id [:in user-ids]))++(defn most-recent-moderation-review-statuses+ "The item id, item type, and status of the most recent ModerationReviews of the items with `item-types` and+ `item-ids`, newest first."+ [item-types item-ids]+ (t2/select [:model/ModerationReview :moderated_item_id :moderated_item_type :status]+ :moderated_item_type [:in item-types]+ :moderated_item_id [:in item-ids]+ :most_recent true+ {:order-by [[:id :desc]]}))++(defn delete-moderation-reviews!+ "Delete the ModerationReviews with `ids`."+ [ids]+ (t2/delete! :model/ModerationReview :id [:in ids]))++(defn unmark-most-recent-moderation-reviews!+ "Clear `most_recent` on the ModerationReviews of the item with `item-id` and `item-type`."+ [item-id item-type]+ (t2/update! :model/ModerationReview+ {:moderated_item_id item-id, :moderated_item_type item-type}+ {:most_recent false}))++(defn insert-moderation-review!+ "Insert the ModerationReview `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/ModerationReview row))diff --git a/src/metabase/content_verification/impl.clj b/src/metabase/content_verification/impl.cljindex 7c24b6da1c9..a35f02f2136 100644--- a/src/metabase/content_verification/impl.clj+++ b/src/metabase/content_verification/impl.clj@@ -1,6 +1,7 @@(ns metabase.content-verification.impl(:require[medley.core :as m]+ [metabase.content-verification.db :as content-verification.db][metabase.models.interface :as mi][metabase.util :as u][toucan2.core :as t2]))@@ -37,10 +38,7 @@item-types (not-empty (into #{} (map (comp keyword object->type)) items*))all-reviews (when item-ids(group-by (juxt :moderated_item_type :moderated_item_id)- (t2/select :model/ModerationReview- :moderated_item_type [:in item-types]- :moderated_item_id [:in item-ids]- {:order-by [[:id :desc]]})))]+ (content-verification.db/moderation-reviews-for-items item-types item-ids)))](for [item items](if (nil? item)nil@@ -53,7 +51,7 @@[moderation-reviews](when (seq moderation-reviews)(let [id->user (m/index-by :id- (t2/select 'User :id [:in (map :moderator_id moderation-reviews)]))]+ (content-verification.db/users (map :moderator_id moderation-reviews)))](for [mr moderation-reviews](assoc mr :user (get id->user (:moderator_id mr)))))))@@ -67,11 +65,7 @@;; constrain on `:moderated_item_type` too so the `(moderated_item_type, moderated_item_id)` index is useditem-types (not-empty (into #{} (map (comp keyword object->type)) items*))type+id->status (when item-ids- (->> (t2/select [:model/ModerationReview :moderated_item_id :moderated_item_type :status]- :moderated_item_type [:in item-types]- :moderated_item_id [:in item-ids]- :most_recent true- {:order-by [[:id :desc]]})+ (->> (content-verification.db/most-recent-moderation-review-statuses item-types item-ids)(group-by (juxt :moderated_item_type :moderated_item_id))(m/map-vals #(:status (first %)))))](for [item items]diff --git a/src/metabase/content_verification/models/moderation_review.clj b/src/metabase/content_verification/models/moderation_review.cljindex a07a2695195..9245dc32633 100644--- a/src/metabase/content_verification/models/moderation_review.clj+++ b/src/metabase/content_verification/models/moderation_review.clj@@ -1,6 +1,7 @@(ns metabase.content-verification.models.moderation-review(:require[metabase.app-db.core :as app-db]+ [metabase.content-verification.db :as content-verification.db][metabase.content-verification.impl :as moderation][metabase.models.interface :as mi][metabase.util.malli :as mu]@@ -61,7 +62,7 @@;; and insert a new one to arrive at 10 again, our invariant.:order-by [[:id :desc]]}))](when (seq ids)- (t2/delete! :model/ModerationReview :id [:in ids]))))+ (content-verification.db/delete-moderation-reviews! ids))))(mu/defn create-review!"Create a new ModerationReview"@@ -74,7 +75,6 @@[:text {:optional true} [:maybe :string]]]](t2/with-transaction [_conn](delete-extra-reviews! (:moderated_item_id params) (:moderated_item_type params))- (t2/update! :model/ModerationReview {:moderated_item_id (:moderated_item_id params)- :moderated_item_type (:moderated_item_type params)}- {:most_recent false})- (first (t2/insert-returning-instances! :model/ModerationReview (assoc params :most_recent true)))))+ (content-verification.db/unmark-most-recent-moderation-reviews! (:moderated_item_id params)+ (:moderated_item_type params))+ (content-verification.db/insert-moderation-review! (assoc params :most_recent true))))diff --git a/src/metabase/dashboards/db.clj b/src/metabase/dashboards/db.cljnew file mode 100644index 00000000000..0c0f47843a2--- /dev/null+++ b/src/metabase/dashboards/db.clj@@ -0,0 +1,294 @@+(ns metabase.dashboards.db+ "Application database queries for the dashboards module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [medley.core :as m]+ [metabase.app-db.core :as mdb]+ [metabase.models.serialization :as serdes]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn insert-dashboard!+ "Insert the Dashboard `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Dashboard row))++(defn update-dashboard!+ "Apply `changes` to the Dashboard with `dashboard-id`."+ [dashboard-id changes]+ (t2/update! :model/Dashboard dashboard-id changes))++(defn delete-dashboard-revisions!+ "Delete the Revisions of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/delete! :model/Revision :model "Dashboard" :model_id dashboard-id))++(defn delete-pulses-for-dashboard!+ "Delete the Pulses of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/delete! :model/Pulse :dashboard_id dashboard-id))++(defn dashboard-tabs-for-dashboards+ "The DashboardTabs of the Dashboards with `dashboard-ids`, in dashboard then position order."+ [dashboard-ids]+ (t2/select :model/DashboardTab+ :dashboard_id [:in dashboard-ids]+ {:order-by [[:dashboard_id :asc] [:position :asc] [:id :asc]]}))++(defn dashcards-with-visible-cards-for-dashboards+ "The DashboardCards of the Dashboards with `dashboard-ids` whose Card is visible (unarchived, a dashboard question+ not archived by itself, or absent), with their Card's Collection authority level, in dashboard then creation order."+ [dashboard-ids]+ (t2/select :model/DashboardCard+ {:select [:dashcard.* [:collection.authority_level :collection_authority_level]]+ :from [[:report_dashboardcard :dashcard]]+ :left-join [[:report_card :card] [:= :dashcard.card_id :card.id]+ [:collection :collection] [:= :collection.id :card.collection_id]]+ :where [:and+ [:in :dashcard.dashboard_id dashboard-ids]+ [:or+ ;; show it if:+ ;; - the card isn't archived+ [:= :card.archived false]+ ;; - the card is archived BUT it's a dashboard question that wasn't archived by itself+ [:and+ [:not= :card.dashboard_id nil]+ [:= :card.archived_directly false]]+ [:= :card.archived nil]]] ; e.g. DashCards with no corresponding Card, e.g. text Cards+ :order-by [[:dashcard.dashboard_id] [:dashcard.created_at :asc]]}))++(defn internal-dashboard-question-ids+ "The ids of the Cards internal to the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-pks-set :model/Card :dashboard_id dashboard-id))++(defn set-cards-archived!+ "Set the archived flags of the Cards with `card-ids`."+ [card-ids archived?]+ (t2/update! :model/Card :id [:in card-ids] {:archived archived? :archived_directly archived?}))++(defn archive-dashboard-questions!+ "Archive the unarchived Cards internal to the Dashboard with `dashboard-id`, not directly."+ [dashboard-id]+ (t2/update! :model/Card :dashboard_id dashboard-id :archived false {:archived true :archived_directly false}))++(defn unarchive-dashboard-questions!+ "Unarchive the Cards internal to the Dashboard with `dashboard-id` that were not archived directly."+ [dashboard-id]+ (t2/update! :model/Card :dashboard_id dashboard-id :archived true :archived_directly false {:archived false}))++(defn move-dashboard-questions!+ "Move the Cards internal to the Dashboard with `dashboard-id` to the Collection with `collection-id`."+ [dashboard-id collection-id]+ (t2/update! :model/Card :dashboard_id dashboard-id {:collection_id collection-id}))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn card-query-columns+ "The query and schema of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :dataset_query :card_schema] :id card-id))++(defn card-queries+ "A map of Card id to query for the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))++(defn document-cards-among+ "The Cards among `card-ids` that belong to a Document."+ [card-ids]+ (t2/select :model/Card :id [:in card-ids] :document_id [:<> nil]))++(defn insert-card!+ "Insert the Card `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Card row))++(defn dashcard-serdes-columns+ "The id, Card, Action, parameter mappings, and visualization settings of the DashboardCards of the Dashboard with+ `dashboard-id`."+ [dashboard-id]+ (t2/select [:model/DashboardCard :id :card_id :action_id :parameter_mappings :visualization_settings]+ :dashboard_id dashboard-id))++(defn dashcard-series-columns+ "The id, Card id, and DashboardCard id of the DashboardCardSeries of the DashboardCards with `dashcard-ids`."+ [dashcard-ids]+ (t2/select [:model/DashboardCardSeries :id :card_id :dashboardcard_id] :dashboardcard_id [:in dashcard-ids]))++(defn series-cards-for-dashcards+ "The series Cards of the DashboardCards with `dashcard-ids`, each with its `:dashboardcard_id`, in series order."+ [dashcard-ids]+ (t2/select [:model/Card :id :name :description :display :dataset_query :type :database_id+ :visualization_settings :collection_id :card_schema :series.dashboardcard_id]+ {:left-join [[:dashboardcard_series :series] [:= :report_card.id :series.card_id]]+ :where [:in :series.dashboardcard_id dashcard-ids]+ :order-by [[:series.position :asc]]}))++(defn dashcard+ "The DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one :model/DashboardCard :id dashcard-id))++(defn dashcards-by-ids+ "The DashboardCards with `dashcard-ids`."+ [dashcard-ids]+ (t2/select :model/DashboardCard :id [:in dashcard-ids]))++(defn dashcards-in-tabs+ "The DashboardCards of the Dashboard with `dashboard-id` on the DashboardTabs with `tab-ids`."+ [dashboard-id tab-ids]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id :dashboard_tab_id [:in tab-ids]))++(defn insert-dashcards!+ "Insert the DashboardCard `rows` and return their ids."+ [rows]+ (t2/insert-returning-pks! :model/DashboardCard rows))++(defn update-dashcard!+ "Apply `changes` to the DashboardCard with `dashcard-id`."+ [dashcard-id changes]+ (t2/update! :model/DashboardCard dashcard-id changes))++(defn delete-dashcards!+ "Delete the DashboardCards with `dashcard-ids`."+ [dashcard-ids]+ (t2/delete! :model/DashboardCard :id [:in dashcard-ids]))++(defn delete-pulse-cards-for-dashcards!+ "Delete the PulseCards of the DashboardCards with `dashcard-ids`."+ [dashcard-ids]+ (t2/delete! :model/PulseCard :dashboard_card_id [:in dashcard-ids]))++(defn delete-series-for-dashcards!+ "Delete the DashboardCardSeries of the DashboardCards with `dashcard-ids`."+ [dashcard-ids]+ (t2/delete! :model/DashboardCardSeries :dashboardcard_id [:in dashcard-ids]))++(defn insert-dashcard-series!+ "Insert the DashboardCardSeries `rows`."+ [rows]+ (t2/insert! :model/DashboardCardSeries rows))++;;; ----------------------------------------------- Link cards ----------------------------------------------------++(defn ensure-integer-link-card-id+ "Return `id` if it is an integer, else throw a 400."+ [id]+ (when-not (integer? id)+ (throw (ex-info "Link card entity id must be an integer"+ {:status-code 400, :id id})))+ id)++(def ^:private all-card-info-columns+ {:model :text+ :id :integer+ :name :text+ :description :text++ ;; for cards and datasets+ :collection_id :integer+ :display :text++ ;; for tables+ :db_id :integer})++(def ^:private link-card-columns-for-model+ {"database" [:id :name :description]+ "table" [:id [:display_name :name] :description :db_id]+ "dashboard" [:id :name :description :collection_id]+ "card" [:id :name :description :collection_id :display]+ "dataset" [:id :name :description :collection_id :display]+ "collection" [:id :name :description]})++(defn- ->column-alias+ "Returns the column name. If the column is aliased, i.e. [`:original_name` `:aliased_name`], return the aliased+ column name"+ [column-or-aliased]+ (if (sequential? column-or-aliased)+ (second column-or-aliased)+ column-or-aliased))++(defn- select-clause-for-link-card-model+ "The search query uses a `union-all` which requires that there be the same number of columns in each of the segments+ of the query. This function will take the columns for `model` and will inject constant `nil` values for any column+ missing from `entity-columns` but found in `all-card-info-columns`."+ [model]+ (let [model-cols (link-card-columns-for-model model)+ model-col-alias->honeysql-clause (m/index-by ->column-alias model-cols)]+ (for [[col col-type] all-card-info-columns+ :let [maybe-aliased-col (get model-col-alias->honeysql-clause col)]]+ (cond+ (= col :model)+ [(h2x/literal model) :model]++ maybe-aliased-col+ maybe-aliased-col++ ;; This entity is missing the column, project a null for that column value. For Postgres and H2, cast it to the+ ;; correct type, e.g.+ ;;+ ;; SELECT cast(NULL AS integer)+ ;;+ ;; For MySQL, this is not needed.+ :else+ [(when-not (= (mdb/db-type) :mysql)+ [:cast nil col-type])+ col]))))++(defn- link-card-info-query-for-model+ "Return a honeysql query that is used to fetch info for a linkcard."+ [model id-or-ids]+ ^:allow-subquery {:select (select-clause-for-link-card-model model)+ :from (t2/table-name (serdes/link-card-model->toucan-model model))+ :where (if (coll? id-or-ids)+ [:in :id (mapv ensure-integer-link-card-id id-or-ids)]+ [:= :id (ensure-integer-link-card-id id-or-ids)])})++(defn link-card-entity+ "The instance of the link-card `model` (a string like \"card\" or \"table\") with `id`, projected the same way as+ [[link-card-info-rows]], or nil."+ [model id]+ (t2/select-one (serdes/link-card-model->toucan-model model) (link-card-info-query-for-model model id)))++(defn- link-card-info-query+ [link-card-model->ids]+ (if (= 1 (count link-card-model->ids))+ (apply link-card-info-query-for-model (first link-card-model->ids))+ {:select [:*]+ :from [[^:allow-subquery {:union-all (map #(apply link-card-info-query-for-model %) link-card-model->ids)}+ :alias_is_required_by_sql_but_not_needed_here]]}))++(defn link-card-info-rows+ "The name, description, and related columns of the entities the link cards `link-card-model->ids`+ (`[[model #{ids}] ...]`) point at."+ [link-card-model->ids]+ (t2/query (link-card-info-query link-card-model->ids)))++(defn dashboard-tab+ "The DashboardTab with `tab-id`, or nil."+ [tab-id]+ (t2/select-one :model/DashboardTab :id tab-id))++(defn insert-dashboard-tabs!+ "Insert the DashboardTab `rows` and return their ids."+ [rows]+ (t2/insert-returning-pks! :model/DashboardTab rows))++(defn update-dashboard-tab!+ "Apply `changes` to the DashboardTab with `tab-id`."+ [tab-id changes]+ (t2/update! :model/DashboardTab tab-id changes))++(defn delete-dashboard-tabs!+ "Delete the DashboardTabs with `tab-ids`."+ [tab-ids]+ (t2/delete! :model/DashboardTab :id [:in tab-ids]))diff --git a/src/metabase/dashboards/models/dashboard.clj b/src/metabase/dashboards/models/dashboard.cljindex 2797b0f40fa..bda35299c77 100644--- a/src/metabase/dashboards/models/dashboard.clj+++ b/src/metabase/dashboards/models/dashboard.clj@@ -8,6 +8,7 @@[metabase.collections.core :as collections][metabase.collections.models.collection :as collection][metabase.config.core :as config]+ [metabase.dashboards.db :as dashboards.db][metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.dashboards.models.dashboard-tab :as dashboard-tab][metabase.dashboards.schema :as dashboards.schema]@@ -60,7 +61,7 @@(= (:collection_id instance) (:id (audit/default-audit-collection)))))(mi/current-user-has-full-permissions? (mi/perms-objects-set instance :write))))([_ pk]- (mi/can-write? (t2/select-one :model/Dashboard :id pk))))+ (mi/can-write? (dashboards.db/dashboard pk))))(perms/define-collection-based-visibility! :model/Dashboard)@@ -76,7 +77,7 @@[dashboard](let [dashboard-id (u/the-id dashboard)](queries/delete-all-parameter-cards-for-parameterized-object! "dashboard" dashboard-id)- (t2/delete! :model/Revision :model "Dashboard" :model_id dashboard-id)))+ (dashboards.db/delete-dashboard-revisions! dashboard-id)))(t2/define-before-insert :model/Dashboard[dashboard]@@ -106,7 +107,7 @@(queries/upsert-or-delete-parameter-cards-from-parameters! "dashboard" (:id dashboard) (:parameters dashboard)))(collection/check-collection-namespace :model/Dashboard (:collection_id dashboard))(when (:archived changes)- (t2/delete! :model/Pulse :dashboard_id (u/the-id dashboard))))))+ (dashboards.db/delete-pulses-for-dashboard! (u/the-id dashboard))))))(mu/defn- migrate-parameter [p :- ::parameters.schema/parameter](cond-> p@@ -143,9 +144,7 @@[_model k dashboards](mi/instances-with-hydrated-datadashboards k- #(group-by :dashboard_id (t2/select :model/DashboardTab- :dashboard_id [:in (map :id dashboards)]- {:order-by [[:dashboard_id :asc] [:position :asc] [:id :asc]]}))+ #(group-by :dashboard_id (dashboards.db/dashboard-tabs-for-dashboards (map :id dashboards))):id{:default []}))@@ -154,23 +153,7 @@(mi/instances-with-hydrated-datadashboards k#(group-by :dashboard_id- (t2/select :model/DashboardCard- {:select [:dashcard.* [:collection.authority_level :collection_authority_level]]- :from [[:report_dashboardcard :dashcard]]- :left-join [[:report_card :card] [:= :dashcard.card_id :card.id]- [:collection :collection] [:= :collection.id :card.collection_id]]- :where [:and- [:in :dashcard.dashboard_id (map :id dashboards)]- [:or- ;; show it if:- ;; - the card isn't archived- [:= :card.archived false]- ;; - the card is archived BUT it's a dashboard question that wasn't archived by itself- [:and- [:not= :card.dashboard_id nil]- [:= :card.archived_directly false]]- [:= :card.archived nil]]] ; e.g. DashCards with no corresponding Card, e.g. text Cards- :order-by [[:dashcard.dashboard_id] [:dashcard.created_at :asc]]}))+ (dashboards.db/dashcards-with-visible-cards-for-dashboards (map :id dashboards))):id{:default []}))@@ -196,7 +179,7 @@appear on the dashboard are archived."[dashboard-id new-cards](let [;; the set of ALL Dashboard Questions (internal to the dashboard) for this Dashboard- internal-dashboard-question-ids (t2/select-pks-set :model/Card :dashboard_id dashboard-id)+ internal-dashboard-question-ids (dashboards.db/internal-dashboard-question-ids dashboard-id);; the set of all card IDs that are present on the dashboardused-card-ids (into #{} (map :card_id new-cards));; DQs that aren't used get archived@@ -204,9 +187,9 @@;; DQs that ARE used get unarchivedinternal-dashboard-questions-to-unarchive (set/intersection internal-dashboard-question-ids used-card-ids)](when-let [ids (seq internal-dashboard-questions-to-archive)]- (t2/update! :model/Card :id [:in ids] {:archived true :archived_directly true}))+ (dashboards.db/set-cards-archived! ids true))(when-let [ids (seq internal-dashboard-questions-to-unarchive)]- (t2/update! :model/Card :id [:in ids] {:archived false :archived_directly false}))))+ (dashboards.db/set-cards-archived! ids false))))(defn cascade-card-state-from-dashboard-update!"Mirror dashboard-level state changes onto the dashboard's cards. Specifically:@@ -219,18 +202,10 @@(let [id (:id current-dash)](when (api/column-will-change? :archived current-dash updates)(if (:archived updates)- (t2/update! :model/Card- :dashboard_id id- :archived false- {:archived true :archived_directly false})- (t2/update! :model/Card- :dashboard_id id- :archived true- :archived_directly false- {:archived false})))+ (dashboards.db/archive-dashboard-questions! id)+ (dashboards.db/unarchive-dashboard-questions! id)))(when (api/column-will-change? :collection_id current-dash updates)- (t2/update! :model/Card :dashboard_id id- {:collection_id (:collection_id updates)}))))+ (dashboards.db/move-dashboard-questions! id (:collection_id updates)))));;; +----------------------------------------------------------------------------------------------------------------+;;; | OTHER CRUD FNS |@@ -239,7 +214,7 @@(defn- dashboard-id->param-field-ids"Get the set of Field IDs referenced by the parameters in this Dashboard."[dashboard-or-id]- (let [dash (-> (t2/select-one :model/Dashboard :id (u/the-id dashboard-or-id))+ (let [dash (-> (dashboards.db/dashboard (u/the-id dashboard-or-id))(t2/hydrate [:dashcards :card]))](params/dashcards->param-field-ids (:dashcards dash))))@@ -319,7 +294,7 @@[card](cond;; If this is a pre-existing card, just return it- (and (integer? (:id card)) (t2/select-one :model/Card :id (:id card)))+ (and (integer? (:id card)) (dashboards.db/card (:id card)))(do(api/read-check :model/Card (:id card))card)@@ -327,16 +302,15 @@;; Don't save text cards(-> card :dataset_query not-empty)(let [_ (query-perms/check-run-permissions-for-query (:dataset_query card))- card (first (t2/insert-returning-instances!- :model/Card- (-> card- (update :result_metadata #(or % (-> card- :dataset_query- legacy-result-metadata-for-query)))- (dissoc :id- :public_uuid :made_public_by_id- :enable_embedding :embedding_params)- (assoc :creator_id api/*current-user-id*))))]+ card (dashboards.db/insert-card!+ (-> card+ (update :result_metadata #(or % (-> card+ :dataset_query+ legacy-result-metadata-for-query)))+ (dissoc :id+ :public_uuid :made_public_by_id+ :enable_embedding :embedding_params)+ (assoc :creator_id api/*current-user-id*)))](events/publish-event! :event/card-create {:object card :user-id (:creator_id card)})(t2/hydrate card :creator :dashboard_count :can_write :collection))))@@ -347,7 +321,7 @@(assoc mapping ::card-id (or (:card_id mapping) card_id)))card-ids (into #{} (keep ::card-id) mappings)card-id->query (when (seq card-ids)- (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))+ (dashboards.db/card-queries card-ids))field-ids (into [](keep (fn [{:keys [target] ::keys [card-id]}](when target@@ -363,16 +337,15 @@(let [{dashcards :dashcardstabs :tabs:keys [description] :as dashboard} (i18n/localized-strings->strings dashboard)- dashboard (first (t2/insert-returning-instances!- :model/Dashboard- (-> dashboard- (dissoc :dashcards :tabs :rule :related- :transient_name :transient_filters :param_fields :more- :public_uuid :made_public_by_id- :enable_embedding :embedding_params)- (assoc :description description- :collection_id parent-collection-id- :creator_id api/*current-user-id*))))+ dashboard (dashboards.db/insert-dashboard!+ (-> dashboard+ (dissoc :dashcards :tabs :rule :related+ :transient_name :transient_filters :param_fields :more+ :public_uuid :made_public_by_id+ :enable_embedding :embedding_params)+ (assoc :description description+ :collection_id parent-collection-id+ :creator_id api/*current-user-id*))){:keys [old->new-tab-id]} (dashboard-tab/do-update-tabs! (:id dashboard) nil tabs)dashcards-to-add (for [dashcard dashcards](let [card (some-> dashcard :card@@ -501,9 +474,8 @@(dashboard-deps false dashboard))(defmethod serdes/descendants "Dashboard" [_model-name id _opts]- (let [dashcards (t2/select [:model/DashboardCard :id :card_id :action_id :parameter_mappings :visualization_settings]- :dashboard_id id)- dashboard (t2/select-one :model/Dashboard :id id)+ (let [dashcards (dashboards.db/dashcard-serdes-columns id)+ dashboard (dashboards.db/dashboard id)dash-id id](merge-withmerge@@ -516,8 +488,7 @@card_id (conj card_id))]{["Card" card-id] {"DashboardCard" id "Dashboard" dash-id}}))(when (not-empty dashcards)- (into {} (for [{:keys [id card_id dashboardcard_id]} (t2/select [:model/DashboardCardSeries :id :card_id :dashboardcard_id]- :dashboardcard_id [:in (map :id dashcards)])]+ (into {} (for [{:keys [id card_id dashboardcard_id]} (dashboards.db/dashcard-series-columns (map :id dashcards))]{["Card" card_id] {"DashboardCardSeries" id"DashboardCard" dashboardcard_id"Dashboard" dash-id}})))diff --git a/src/metabase/dashboards/models/dashboard_card.clj b/src/metabase/dashboards/models/dashboard_card.cljindex 75f5775454f..7cbf17bc87a 100644--- a/src/metabase/dashboards/models/dashboard_card.clj+++ b/src/metabase/dashboards/models/dashboard_card.clj@@ -3,11 +3,11 @@[clojure.set :as set][medley.core :as m][metabase.app-db.core :as mdb]+ [metabase.dashboards.db :as dashboards.db][metabase.models.interface :as mi][metabase.models.serialization :as serdes][metabase.parameters.core :as parameters][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][methodical.core :as methodical]@@ -29,19 +29,12 @@:visualization_settings mi/transform-visualization-settings:inline_parameters mi/transform-json})-(defn- ensure-integer-link-card-id- [id]- (when-not (integer? id)- (throw (ex-info "Link card entity id must be an integer"- {:status-code 400, :id id})))- id)-(defn- validate-link-card-entity-id"Require the link-card entity id to be an integer before it is stored. It is used as an id when the linkedentity is looked up on read, so validating on write keeps a malformed value from being persisted."[dashcard](when-let [id (get-in dashcard [:visualization_settings :link :entity :id])]- (ensure-integer-link-card-id id))+ (dashboards.db/ensure-integer-link-card-id id))dashcard)(defn- validate-click-behavior-target-ids@@ -90,7 +83,7 @@(defmethod mi/perms-objects-set :model/DashboardCard[dashcard read-or-write](let [card (or (:card dashcard)- (t2/select-one [:model/Card :dataset_query :card_schema] :id (u/the-id (:card_id dashcard))))+ (dashboards.db/card-query-columns (u/the-id (:card_id dashcard))))series (or (:series dashcard)(series dashcard))](apply set/union (mi/perms-objects-set card read-or-write) (for [series-card series]@@ -140,12 +133,7 @@(when (seq dashcards)(let [dashcard-ids (map :id dashcards)dashcard-id->series (when (seq dashcard-ids)- (as-> (t2/select- [:model/Card :id :name :description :display :dataset_query :type :database_id- :visualization_settings :collection_id :card_schema :series.dashboardcard_id]- {:left-join [[:dashboardcard_series :series] [:= :report_card.id :series.card_id]]- :where [:in :series.dashboardcard_id dashcard-ids]- :order-by [[:series.position :asc]]}) series+ (as-> (dashboards.db/series-cards-for-dashcards dashcard-ids) series(group-by :dashboardcard_id series)(update-vals series #(map (fn [card] (dissoc card :dashboardcard_id)) %))))](map (fn [dashcard]@@ -157,7 +145,7 @@(mu/defn retrieve-dashboard-card"Fetch a single DashboardCard by its ID value."[id :- ms/PositiveInt]- (-> (t2/select-one :model/DashboardCard :id id)+ (-> (dashboards.db/dashcard id)(t2/hydrate :series)))(defn dashcard->multi-cards@@ -192,12 +180,12 @@[dashcard-id->card-ids](when (seq dashcard-id->card-ids);; first off, just delete all series on the dashboard card (we add them again below)- (t2/delete! :model/DashboardCardSeries :dashboardcard_id [:in (keys dashcard-id->card-ids)])+ (dashboards.db/delete-series-for-dashcards! (keys dashcard-id->card-ids));; now just insert all of the series that were given to us(when-let [card-series (seq (for [[dashcard-id card-ids] dashcard-id->card-ids[i card-id] (map-indexed vector card-ids)]{:dashboardcard_id dashcard-id, :card_id card-id, :position i}))]- (t2/insert! :model/DashboardCardSeries card-series))))+ (dashboards.db/insert-dashcard-series! card-series))))(def ^:private DashboardCardUpdates[:map@@ -229,7 +217,7 @@updates (shallow-updates (select-keys dashboard-card update-ks)(select-keys old-dashboard-card update-ks))](when (seq updates)- (t2/update! :model/DashboardCard dashcard-id updates))+ (dashboards.db/update-dashcard! dashcard-id updates))(when (not= (:series dashboard-card [])(:series old-dashboard-card []))(update-dashboard-cards-series! {dashcard-id series}))@@ -254,13 +242,12 @@(t2/with-transaction [_conn](let [card-ids (keep :card_id dashboard-cards)](when (seq card-ids)- (let [in-report-cards (t2/select :model/Card :id [:in card-ids] :document_id [:<> nil])]+ (let [in-report-cards (dashboards.db/document-cards-among card-ids)](when (seq in-report-cards)(throw (ex-info "Cards with 'document_id' cannot be added to dashboards"{:status-code 400:in-report-card-ids (map :id in-report-cards)}))))))- (let [dashboard-card-ids (t2/insert-returning-pks!- :model/DashboardCard+ (let [dashboard-card-ids (dashboards.db/insert-dashcards!(for [dashcard dashboard-cards](merge {:parameter_mappings []:visualization_settings {}@@ -269,7 +256,7 @@;; add series to the DashboardCard(update-dashboard-cards-series! (zipmap dashboard-card-ids (map #(get % :series []) dashboard-cards)));; return the full DashboardCard- (-> (t2/select :model/DashboardCard :id [:in dashboard-card-ids])+ (-> (dashboards.db/dashcards-by-ids dashboard-card-ids)(t2/hydrate :series))))))(defn- cleanup-orphaned-inline-parameters!@@ -278,18 +265,18 @@from deleted cards become orphaned."[dashboard-card-ids](when (seq dashboard-card-ids)- (let [cards-being-deleted (t2/select :model/DashboardCard :id [:in dashboard-card-ids])+ (let [cards-being-deleted (dashboards.db/dashcards-by-ids dashboard-card-ids)orphaned-param-ids (set (mapcat :inline_parameters cards-being-deleted));; Get dashboard IDs (should all be the same, but let's be safe)dashboard-ids (set (map :dashboard_id cards-being-deleted))](when (and (seq orphaned-param-ids) (= 1 (count dashboard-ids)))(let [dashboard-id (first dashboard-ids)- dashboard (t2/select-one :model/Dashboard :id dashboard-id)+ dashboard (dashboards.db/dashboard dashboard-id)current-params (:parameters dashboard)cleaned-params (filterv #(not (contains? orphaned-param-ids (:id %)))current-params)](when (not= (count current-params) (count cleaned-params))- (t2/update! :model/Dashboard dashboard-id {:parameters cleaned-params})+ (dashboards.db/update-dashboard! dashboard-id {:parameters cleaned-params})(count orphaned-param-ids)))))))(defn delete-dashboard-cards!@@ -300,86 +287,18 @@;; Clean up inline parameters before deletion (since we need to read the cards first)(cleanup-orphaned-inline-parameters! dashboard-card-ids);; Delete the cards- (t2/delete! :model/PulseCard :dashboard_card_id [:in dashboard-card-ids])- (t2/delete! :model/DashboardCard :id [:in dashboard-card-ids])))+ (dashboards.db/delete-pulse-cards-for-dashcards! dashboard-card-ids)+ (dashboards.db/delete-dashcards! dashboard-card-ids)));;; ----------------------------------------------- Link cards -----------------------------------------------------(def ^:private all-card-info-columns- {:model :text- :id :integer- :name :text- :description :text-- ;; for cards and datasets- :collection_id :integer- :display :text-- ;; for tables- :db_id :integer})--(def ^:private link-card-columns-for-model- {"database" [:id :name :description]- "table" [:id [:display_name :name] :description :db_id]- "dashboard" [:id :name :description :collection_id]- "card" [:id :name :description :collection_id :display]- "dataset" [:id :name :description :collection_id :display]- "collection" [:id :name :description]})--(defn- ->column-alias- "Returns the column name. If the column is aliased, i.e. [`:original_name` `:aliased_name`], return the aliased- column name"- [column-or-aliased]- (if (sequential? column-or-aliased)- (second column-or-aliased)- column-or-aliased))--(defn- select-clause-for-link-card-model- "The search query uses a `union-all` which requires that there be the same number of columns in each of the segments- of the query. This function will take the columns for `model` and will inject constant `nil` values for any column- missing from `entity-columns` but found in `all-card-info-columns`."- [model]- (let [model-cols (link-card-columns-for-model model)- model-col-alias->honeysql-clause (m/index-by ->column-alias model-cols)]- (for [[col col-type] all-card-info-columns- :let [maybe-aliased-col (get model-col-alias->honeysql-clause col)]]- (cond- (= col :model)- [(h2x/literal model) :model]-- maybe-aliased-col- maybe-aliased-col-- ;; This entity is missing the column, project a null for that column value. For Postgres and H2, cast it to the- ;; correct type, e.g.- ;;- ;; SELECT cast(NULL AS integer)- ;;- ;; For MySQL, this is not needed.- :else- [(when-not (= (mdb/db-type) :mysql)- [:cast nil col-type])- col]))))-(def ^:private link-card-models(set (keys serdes/link-card-model->toucan-model)))-(defn link-card-info-query-for-model- "Return a honeysql query that is used to fetch info for a linkcard."- [model id-or-ids]- ^:allow-subquery {:select (select-clause-for-link-card-model model)- :from (t2/table-name (serdes/link-card-model->toucan-model model))- :where (if (coll? id-or-ids)- [:in :id (mapv ensure-integer-link-card-id id-or-ids)]- [:= :id (ensure-integer-link-card-id id-or-ids)])})--(defn- link-card-info-query- [link-card-model->ids]- (if (= 1 (count link-card-model->ids))- (apply link-card-info-query-for-model (first link-card-model->ids))- {:select [:*]- :from [[^:allow-subquery {:union-all (map #(apply link-card-info-query-for-model %) link-card-model->ids)}- :alias_is_required_by_sql_but_not_needed_here]]}))+(defn link-card-entity+ "The instance of the link-card `model` (a string like \"card\" or \"table\") with `id`, or nil."+ [model id]+ (dashboards.db/link-card-entity model id))(mi/define-batched-hydration-method dashcard-linkcard-info:dashcard/linkcard-info@@ -401,7 +320,7 @@(let [;; query all entities in 1 db call;; {[:table 3] {:name ...}}model-and-id->info- (-> (m/index-by (juxt :model :id) (t2/query (link-card-info-query model-and-ids)))+ (-> (m/index-by (juxt :model :id) (dashboards.db/link-card-info-rows model-and-ids))(update-vals (fn [{model :model :as instance}](if (mi/can-read? (t2/instance (serdes/link-card-model->toucan-model model) instance))instance@@ -427,9 +346,9 @@(defmethod serdes/generate-path "DashboardCard" [_ dashcard](remove nil?- [(serdes/infer-self-path "Dashboard" (t2/select-one 'Dashboard :id (:dashboard_id dashcard)))+ [(serdes/infer-self-path "Dashboard" (dashboards.db/dashboard (:dashboard_id dashcard)))(when (:dashboard_tab_id dashcard)- (serdes/infer-self-path "DashboardTab" (t2/select-one :model/DashboardTab :id (:dashboard_tab_id dashcard))))+ (serdes/infer-self-path "DashboardTab" (dashboards.db/dashboard-tab (:dashboard_tab_id dashcard))))(serdes/infer-self-path "DashboardCard" dashcard)]))(defmethod serdes/make-spec "DashboardCard" [_model-name opts]diff --git a/src/metabase/dashboards/models/dashboard_tab.clj b/src/metabase/dashboards/models/dashboard_tab.cljindex 3305fdbb911..4275209074a 100644--- a/src/metabase/dashboards/models/dashboard_tab.clj+++ b/src/metabase/dashboards/models/dashboard_tab.clj@@ -1,6 +1,7 @@(ns metabase.dashboards.models.dashboard-tab(:require[medley.core :as m]+ [metabase.dashboards.db :as dashboards.db][metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.models.interface :as mi][metabase.models.serialization :as serdes]@@ -34,7 +35,7 @@(assert (= 1 (count (set (map :dashboard_id tabs)))), "All tabs must belong to the same dashboard")(let [dashboard-id (:dashboard_id (first tabs))tab-ids (map :id tabs)- dashcards (t2/select :model/DashboardCard :dashboard_id dashboard-id :dashboard_tab_id [:in tab-ids])+ dashcards (dashboards.db/dashcards-in-tabs dashboard-id tab-ids)tab-id->dashcards (-> (group-by :dashboard_tab_id dashcards)(update-vals #(sort dashboard-card/dashcard-comparator %)))tabs (sort-by :position tabs)]@@ -44,12 +45,12 @@(defmethod mi/perms-objects-set :model/DashboardTab[dashtab read-or-write](let [dashboard (or (:dashboard dashtab)- (t2/select-one :model/Dashboard :id (:dashboard_id dashtab)))]+ (dashboards.db/dashboard (:dashboard_id dashtab)))](mi/perms-objects-set dashboard read-or-write)));;; ----------------------------------------------- SERIALIZATION ----------------------------------------------------(defmethod serdes/generate-path "DashboardTab" [_ dashcard]- [(serdes/infer-self-path "Dashboard" (t2/select-one :model/Dashboard :id (:dashboard_id dashcard)))+ [(serdes/infer-self-path "Dashboard" (dashboards.db/dashboard (:dashboard_id dashcard)))(serdes/infer-self-path "DashboardTab" dashcard)])(defmethod serdes/make-spec "DashboardTab" [_model-name _opts]@@ -64,9 +65,9 @@"Create the new tabs and returned a mapping from temporary tab ID to the new tab ID."[dashboard-id :- ms/PositiveIntnew-tabs :- [:sequential [:map [:id neg-int?]]]]- (let [new-tab-ids (t2/insert-returning-pks! :model/DashboardTab (->> new-tabs- (map #(dissoc % :id))- (map #(assoc % :dashboard_id dashboard-id))))]+ (let [new-tab-ids (dashboards.db/insert-dashboard-tabs! (->> new-tabs+ (map #(dissoc % :id))+ (map #(assoc % :dashboard_id dashboard-id))))](zipmap (map :id new-tabs) new-tab-ids)))(mu/defn update-tabs! :- nil?@@ -83,14 +84,14 @@(select-keys new-tab update-ks))))new-tabs)](doseq [tab to-update-tabs]- (t2/update! :model/DashboardTab (:id tab) (select-keys tab update-ks)))+ (dashboards.db/update-dashboard-tab! (:id tab) (select-keys tab update-ks)))nil))(mu/defn delete-tabs! :- nil?"Delete tabs of a Dashboard"[tab-ids :- [:sequential {:min 1} ms/PositiveInt]](when (seq tab-ids)- (t2/delete! :model/DashboardTab :id [:in tab-ids]))+ (dashboards.db/delete-dashboard-tabs! tab-ids))nil)(defn do-update-tabs!@@ -109,10 +110,10 @@_ (when-let [to-delete-ids (seq to-delete-ids)](delete-tabs! to-delete-ids))old->new-tab-id (when (seq to-create)- (let [new-tab-ids (t2/insert-returning-pks! :model/DashboardTab- (->> to-create- (map #(dissoc % :id))- (map #(assoc % :dashboard_id dashboard-id))))]+ (let [new-tab-ids (dashboards.db/insert-dashboard-tabs!+ (->> to-create+ (map #(dissoc % :id))+ (map #(assoc % :dashboard_id dashboard-id))))](zipmap (map :id to-create) new-tab-ids)))](when (seq to-update)(update-tabs! current-tabs to-update))diff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex 992f62a0de2..ba3d288e5f9 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -17,6 +17,7 @@[metabase.collections.core :as collections][metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as collection.root]+ [metabase.dashboards-rest.db :as dashboards-rest.db][metabase.dashboards.models.dashboard :as dashboard][metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.dashboards.models.dashboard-tab :as dashboard-tab]@@ -61,11 +62,9 @@(set! *warn-on-reflection* true)(defn- dashboards-list [filter-option]- (as-> (t2/select :model/Dashboard {:where [:and (case (or (keyword filter-option) :all)- (:all :archived) true- :mine [:= :creator_id api/*current-user-id*])- [:= :archived (= (keyword filter-option) :archived)]]- :order-by [:%lower.name]}) <>+ (as-> (dashboards-rest.db/dashboards (= (keyword filter-option) :archived)+ (when (= (keyword filter-option) :mine)+ api/*current-user-id*)) <>(t2/hydrate <> :creator)(filter mi/can-read? <>)))@@ -147,16 +146,10 @@(defn- stored-references[dashboard-id]- {:cards (into (set (t2/select-fn-vec :card_id :model/ParameterCard- :parameterized_object_type "dashboard"- :parameterized_object_id dashboard-id))- (concat (t2/select-fn-vec :card_id :model/DashboardCard :dashboard_id dashboard-id)- (t2/select-fn-vec :card_id :model/DashboardCardSeries- {:where [:in :dashboardcard_id- ^:allow-subquery {:select [:id]- :from [(t2/table-name :model/DashboardCard)]- :where [:= :dashboard_id dashboard-id]}]})))- :actions (set (t2/select-fn-vec :action_id :model/DashboardCard :dashboard_id dashboard-id))})+ {:cards (into (set (dashboards-rest.db/parameter-card-ids "dashboard" dashboard-id))+ (concat (dashboards-rest.db/dashboard-card-ids dashboard-id)+ (dashboards-rest.db/dashboard-series-card-ids dashboard-id)))+ :actions (set (dashboards-rest.db/dashboard-action-ids dashboard-id))})(def ^:private no-references {:cards #{} :actions #{}})@@ -199,7 +192,7 @@;; collection to change position, check that and fix up if needed(api/maybe-reconcile-collection-position! dashboard-data);; Ok, now save the Dashboard- (first (t2/insert-returning-instances! :model/Dashboard dashboard-data)))]+ (dashboards-rest.db/insert-dashboard! dashboard-data))](events/publish-event! :event/dashboard-create {:object dash :user-id api/*current-user-id*})(analytics/track-event! :snowplow/dashboard{:event :dashboard-created@@ -289,7 +282,7 @@another, and thus do not work as one would expect when used as map keys.)"[hashes](when (seq hashes)- (into {} (for [[k v] (t2/select-fn->fn :query_hash :average_execution_time :model/Query :query_hash [:in hashes])]+ (into {} (for [[k v] (dashboards-rest.db/query-average-execution-times hashes)]{(vec k) v}))))(defn- add-query-average-duration-to-card@@ -356,7 +349,7 @@(fn [card](when card(let [dataset-query (or (:dataset_query card)- (t2/select-one-fn :dataset_query :model/Card :id (:id card)))+ (dashboards-rest.db/card-query (:id card)))download-level (when (seq dataset-query)(perms/download-perms-level dataset-query api/*current-user-id*))](assoc card :download_perms (case download-level@@ -382,7 +375,7 @@(span/with-span!{:name "get-dashboard":attributes {:dashboard/id id}}- (-> (t2/select-one :model/Dashboard :id id)+ (-> (dashboards-rest.db/dashboard id)api/read-checkhydrate-dashboard-detailscollection.root/hydrate-root-collection@@ -488,11 +481,11 @@(defn- duplicate-tabs[new-dashboard existing-tabs]- (let [new-tab-ids (t2/insert-returning-pks! :model/DashboardTab- (for [tab existing-tabs]- (-> tab- (assoc :dashboard_id (:id new-dashboard))- (dissoc :id :entity_id :created_at :updated_at))))]+ (let [new-tab-ids (dashboards-rest.db/insert-dashboard-tabs!+ (for [tab existing-tabs]+ (-> tab+ (assoc :dashboard_id (:id new-dashboard))+ (dissoc :id :entity_id :created_at :updated_at))))](zipmap (map :id existing-tabs) new-tab-ids)))(defn- update-colvalmap-setting@@ -587,9 +580,7 @@;; if we're trying to save the new dashboard in a Collection make sure we have permissions to do that(api/create-check :model/Dashboard {:collection_id collection_id})(api/check-400 (not (and (= is_deep_copy false)- (t2/exists? :model/Card- :dashboard_id from-dashboard-id- :archived false)))+ (dashboards-rest.db/unarchived-dashboard-question-exists? from-dashboard-id)))(deferred-tru "You cannot do a shallow copy of this dashboard because it contains Dashboard Questions."))(let [existing-dashboard (get-dashboard from-dashboard-id)dashboard-data {:name (or name (:name existing-dashboard))@@ -605,7 +596,7 @@;; collection to change position, check that and fix up if needed(api/maybe-reconcile-collection-position! dashboard-data);; Ok, now save the Dashboard- (let [dash (first (t2/insert-returning-instances! :model/Dashboard dashboard-data))+ (let [dash (dashboards-rest.db/insert-dashboard! dashboard-data){id->new-card :copiedid->referenced-card :referenceduncopied :discarded}@@ -647,7 +638,7 @@[](perms/check-has-application-permission :setting)(public-sharing.validation/check-public-sharing-enabled)- (t2/select [:model/Dashboard :name :id :public_uuid], :public_uuid [:not= nil], :archived false))+ (dashboards-rest.db/public-dashboards));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -659,7 +650,7 @@[](perms/check-has-application-permission :setting)(embedding.validation/check-embedding-enabled)- (t2/select [:model/Dashboard :name :id], :enable_embedding true, :archived false))+ (dashboards-rest.db/embeddable-dashboards));;; --------------------------------------------- Fetching/Updating/Etc. ---------------------------------------------@@ -754,7 +745,7 @@cards (app-db/query query)]{:total (count cards):data (api.collection/post-process-rows {}- (t2/select-one :model/Collection :id (:collection_id dashboard))+ (dashboards-rest.db/collection (:collection_id dashboard))cards):limit (request/limit):offset (request/offset)@@ -781,7 +772,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](let [dashboard (api/write-check :model/Dashboard id)]- (t2/delete! :model/Dashboard :id id)+ (dashboards-rest.db/delete-dashboard! id)(events/publish-event! :event/dashboard-delete {:object dashboard :user-id api/*current-user-id*}))api/generic-204-no-content)@@ -797,7 +788,7 @@(when (seq parameter-mappings)(let [card-ids (into #{} (keep :card-id) parameter-mappings)card-id->query (when (seq card-ids)- (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))+ (dashboards-rest.db/card-queries card-ids))field-ids (into [](keep (fn [{:keys [target card-id]}](when target@@ -819,7 +810,7 @@[dashboard-id](m/map-vals (fn [mappings](into #{} (map #(select-keys % [:target :parameter_id])) mappings))- (t2/select-pk->fn :parameter_mappings :model/DashboardCard :dashboard_id dashboard-id)))+ (dashboards-rest.db/dashcard-parameter-mappings dashboard-id)))(defn- check-updated-parameter-mapping-permissions"In 0.41.0+ you now require data permissions for the Table in question to add or modify Dashboard parameter mappings.@@ -837,9 +828,7 @@(assoc mapping :dashcard-id dashcard-id));; need to add the appropriate `:card-id` for all the new mappings we're going to check.dashcard-id->card-id (when (seq new-mappings)- (t2/select-pk->fn :card_id :model/DashboardCard- :dashboard_id dashboard-id- :id [:in (set (map :dashcard-id new-mappings))]))+ (dashboards-rest.db/dashcard-card-ids-by-id dashboard-id (set (map :dashcard-id new-mappings))))new-mappings (for [{:keys [dashcard-id], :as mapping} new-mappings](assoc mapping :card-id (get dashcard-id->card-id dashcard-id)))](check-parameter-mapping-permissions new-mappings)))@@ -847,7 +836,7 @@(defn- create-dashcards (filter pos-int?)) dashcards)]- (api/check-not-archived (t2/select-one :model/Card :id card-id)))+ (api/check-not-archived (dashboards-rest.db/card card-id)))(check-parameter-mapping-permissions (for [{:keys [card_id parameter_mappings]} dashcardsmapping parameter_mappings](assoc mapping :card-id card_id)))@@ -861,7 +850,7 @@dashcards)(defn- delete-dashcards! [dashcard-ids]- (let [dashboard-cards (t2/select :model/DashboardCard :id [:in dashcard-ids])]+ (let [dashboard-cards (dashboards-rest.db/dashcards-by-ids dashcard-ids)](dashboard-card/delete-dashboard-cards! dashcard-ids)dashboard-cards))@@ -873,11 +862,7 @@[existing-dashboard new-dashcards](let [grandfathered-ids (into #{} (mapcat dashcard-card-ids) (:dashcards existing-dashboard))](when-let [card-ids (seq (remove grandfathered-ids (mapcat dashcard-card-ids new-dashcards)))]- (api/check-400 (not (t2/exists? :model/Card- {:where [:and- [:not= :dashboard_id (u/the-id existing-dashboard)]- [:not= :dashboard_id nil]- [:in :id (set card-ids)]]}))))))+ (api/check-400 (not (dashboards-rest.db/card-internal-to-other-dashboard-exists? (u/the-id existing-dashboard) (set card-ids)))))))(defn- do-update-dashcards![dashboard current-cards new-cards]@@ -958,7 +943,7 @@- The user info for the creator of the pulse- The users affected by the pulse"[{bad-pulse-id :id pulse-name :name :keys [parameters creator_id]}]- (let [creator (t2/select-one [:model/User :first_name :last_name :email] creator_id)]+ (let [creator (dashboards-rest.db/user-name-and-email creator_id)]{:pulse-id bad-pulse-id:pulse-name pulse-name:bad-parameters parameters@@ -966,20 +951,17 @@:affected-users (flatten(for [{pulse-channel-id :idchannel-type :channel_type- {:keys [channel]} :details} (t2/select [:model/PulseChannel :id :channel_type :details]- :pulse_id [:= bad-pulse-id])]+ {:keys [channel]} :details} (dashboards-rest.db/pulse-channels-for-pulse bad-pulse-id)](case channel-type:email (let [pulse-channel-recipients (when (= :email channel-type)- (t2/select :model/PulseChannelRecipient- :pulse_channel_id pulse-channel-id))]+ (dashboards-rest.db/pulse-channel-recipients pulse-channel-id))](when (seq pulse-channel-recipients)(map(fn [{:keys [common_name] :as recipient}](assoc recipient:notification-type channel-type:recipient common_name))- (t2/select [:model/User :first_name :last_name :email]- :id [:in (map :user_id pulse-channel-recipients)]))))+ (dashboards-rest.db/user-names-and-emails (map :user_id pulse-channel-recipients))))):slack {:notification-type channel-type:recipient channel}nil)))}))@@ -988,12 +970,10 @@"Identify and return any pulses used in a subscription that contain parameters that are no longer on the dashboard."[dashboard-id original-dashboard-params](when (seq original-dashboard-params)- (let [{:keys [resolved-params]} (t2/hydrate- (t2/select-one [:model/Dashboard :id :parameters] dashboard-id)- :resolved-params)+ (let [{:keys [resolved-params]} (t2/hydrate (dashboards-rest.db/dashboard-parameters dashboard-id) :resolved-params)dashboard-params (set (keys resolved-params))];; ordered so the notifications go out in a stable order rather than whatever order the rows come back in- (->> (t2/select :model/Pulse :dashboard_id dashboard-id :archived false {:order-by [[:id :asc]]})+ (->> (dashboards-rest.db/unarchived-pulses-for-dashboard dashboard-id)(keep (fn [{:keys [parameters] :as pulse}](let [bad-params (filterv(fn [{param-id :id}] (not (contains? dashboard-params param-id)))@@ -1013,9 +993,7 @@(when-some [broken-pulses (broken-pulses dashboard-id original-dashboard-params)](let [{dashboard-name :namedashboard-description :description- dashboard-creator :creator} (t2/hydrate- (t2/select-one [:model/Dashboard :name :description :creator_id] dashboard-id)- :creator)]+ dashboard-creator :creator} (t2/hydrate (dashboards-rest.db/dashboard-name-columns dashboard-id) :creator)](for [broken-pulse broken-pulses](assoc(bad-pulse-notification-data broken-pulse)@@ -1049,10 +1027,7 @@;; If there are parameters in the update, we want the old params so that we can do a check to see if any of;; the notifications were broken by the update.{original-params :resolved-params} (when parameters- (t2/hydrate- (t2/select-one :model/Dashboard id)- [:dashcards :card]- :resolved-params))+ (t2/hydrate (dashboards-rest.db/dashboard id) [:dashcards :card] :resolved-params))changes-stats (atom nil);; tabs are always sent in production as well when dashcards are updated, but there are lots of;; tests that exclude it. so this only checks for dashcards@@ -1073,7 +1048,7 @@:non-nil #{:name :parameters :caveats :points_of_interest :show_in_getting_started :enable_embedding:embedding_params :archived :auto_apply_filters}))](dashboard/cascade-card-state-from-dashboard-update! current-dash dash-updates)- (t2/update! :model/Dashboard id updates)+ (dashboards-rest.db/update-dashboard! id updates)(when (contains? updates :collection_id)(events/publish-event! :event/collection-touch {:collection-id id :user-id api/*current-user-id*}));; Handle broken subscriptions, if any, when parameters changed@@ -1118,7 +1093,7 @@(select-keys dashcards-changes-stats [:created-dashcards :deleted-dashcards])))))(collections/check-for-remote-sync-update current-dash))true))- (let [dashboard (t2/select-one :model/Dashboard id)]+ (let [dashboard (dashboards-rest.db/dashboard id)];; skip publishing the event if it's just a change in its collection position(when-not (= #{:collection_position}(set (keys dash-updates)))@@ -1234,15 +1209,15 @@(api/check-superuser)(public-sharing.validation/check-public-sharing-enabled)(api/check-not-archived (api/read-check :model/Dashboard dashboard-id))- (let [existing-public-uuid (t2/select-one-fn :public_uuid :model/Dashboard :id dashboard-id)+ (let [existing-public-uuid (dashboards-rest.db/dashboard-public-uuid dashboard-id)uuid (or existing-public-uuid(u/prog1 (str (random-uuid))(events/publish-event! :event/dashboard-public-link-created{:object-id dashboard-id:user-id api/*current-user-id*})- (t2/update! :model/Dashboard dashboard-id- {:public_uuid <>- :made_public_by_id api/*current-user-id*})))]+ (dashboards-rest.db/update-dashboard! dashboard-id+ {:public_uuid <>+ :made_public_by_id api/*current-user-id*})))]{:uuid uuid}));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API@@ -1259,9 +1234,9 @@(perms/check-has-application-permission :setting)(public-sharing.validation/check-public-sharing-enabled)(api/check-exists? :model/Dashboard :id dashboard-id, :public_uuid [:not= nil], :archived false)- (t2/update! :model/Dashboard dashboard-id- {:public_uuid nil- :made_public_by_id nil})+ (dashboards-rest.db/update-dashboard! dashboard-id+ {:public_uuid nil+ :made_public_by_id nil})(events/publish-event! :event/dashboard-public-link-deleted{:object-id dashboard-id:user-id api/*current-user-id*})@@ -1275,7 +1250,7 @@"Return related entities."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (-> (t2/select-one :model/Dashboard :id id) api/read-check xrays/related))+ (-> (dashboards-rest.db/dashboard id) api/read-check xrays/related));;; ---------------------------------------------- Transient dashboards ----------------------------------------------@@ -1338,7 +1313,7 @@(if api/*is-superuser?*"/"(collection/children-location- (t2/select-one :model/Collection :personal_owner_id api/*current-user-id*)))))+ (dashboards-rest.db/personal-collection-for-user api/*current-user-id*)))))dashboard (dashboard/save-transient-dashboard! dashboard parent-collection-id)](events/publish-event! :event/dashboard-create {:object dashboard :user-id api/*current-user-id*})dashboard))@@ -1454,9 +1429,7 @@{:keys [parameters]} :- [:map[:parameters {:optional true} ::actions.schema/prefetch-parameter-values]]](api/read-check :model/Dashboard dashboard-id)- (let [dashcard (api/check-404 (t2/select-one :model/DashboardCard- :id dashcard-id- :dashboard_id dashboard-id))]+ (let [dashcard (api/check-404 (dashboards-rest.db/dashcard-in-dashboard dashcard-id dashboard-id))](actions/fetch-values(api/check-404 (actions/dashcard->action dashcard))parameters)))@@ -1500,9 +1473,9 @@(m/mapply qp.dashboard/process-query-for-dashcard(mergebody- {:dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- :card (api/check-404 (t2/select-one :model/Card card-id))- :dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))}))))+ {:dashboard (api/check-404 (dashboards-rest.db/dashboard dashboard-id))+ :card (api/check-404 (dashboards-rest.db/card card-id))+ :dashcard (api/check-404 (dashboards-rest.db/dashcard dashcard-id))}))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -1528,9 +1501,9 @@[:format_rows {:default false} ms/BooleanValue][:pivot_results {:default false} ms/BooleanValue]]](m/mapply qp.dashboard/process-query-for-dashcard- {:dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- :card (api/check-404 (t2/select-one :model/Card card-id))- :dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))+ {:dashboard (api/check-404 (dashboards-rest.db/dashboard dashboard-id))+ :card (api/check-404 (dashboards-rest.db/card card-id))+ :dashcard (api/check-404 (dashboards-rest.db/dashcard dashcard-id)):export-format export-format:parameters parameters:context (api.dataset/export-format->context export-format)@@ -1561,7 +1534,7 @@(m/mapply qp.dashboard/process-query-for-dashcard(mergebody- {:dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- :card (api/check-404 (t2/select-one :model/Card card-id))- :dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))+ {:dashboard (api/check-404 (dashboards-rest.db/dashboard dashboard-id))+ :card (api/check-404 (dashboards-rest.db/card card-id))+ :dashcard (api/check-404 (dashboards-rest.db/dashcard dashcard-id)):qp qp.pivot/run-pivot-query})))diff --git a/src/metabase/dashboards_rest/db.clj b/src/metabase/dashboards_rest/db.cljnew file mode 100644index 00000000000..924e24dcb6c--- /dev/null+++ b/src/metabase/dashboards_rest/db.clj@@ -0,0 +1,185 @@+(ns metabase.dashboards-rest.db+ "Application database queries for the dashboards REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++(defn dashboards+ "The archived or unarchived (`archived?`) Dashboards, restricted to those created by `creator-id` when given, in+ case-insensitive name order."+ [archived? creator-id]+ (t2/select :model/Dashboard {:where [:and+ (when creator-id [:= :creator_id creator-id])+ [:= :archived archived?]]+ :order-by [:%lower.name]}))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn dashboard-parameters+ "The id and parameters of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one [:model/Dashboard :id :parameters] dashboard-id))++(defn dashboard-name-columns+ "The name, description, and creator of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one [:model/Dashboard :name :description :creator_id] dashboard-id))++(defn dashboard-public-uuid+ "The public uuid of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one-fn :public_uuid :model/Dashboard :id dashboard-id))++(defn public-dashboards+ "The name, id, and public uuid of the unarchived Dashboards that are publicly shared."+ []+ (t2/select [:model/Dashboard :name :id :public_uuid], :public_uuid [:not= nil], :archived false))++(defn embeddable-dashboards+ "The name and id of the unarchived Dashboards with embedding enabled."+ []+ (t2/select [:model/Dashboard :name :id], :enable_embedding true, :archived false))++(defn insert-dashboard!+ "Insert the Dashboard `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Dashboard row))++(defn update-dashboard!+ "Apply `changes` to the Dashboard with `dashboard-id`."+ [dashboard-id changes]+ (t2/update! :model/Dashboard dashboard-id changes))++(defn delete-dashboard!+ "Delete the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/delete! :model/Dashboard :id dashboard-id))++(defn parameter-card-ids+ "The Card ids of the ParameterCards of the `parameterized-object-type` with `parameterized-object-id`."+ [parameterized-object-type parameterized-object-id]+ (t2/select-fn-vec :card_id :model/ParameterCard+ :parameterized_object_type parameterized-object-type+ :parameterized_object_id parameterized-object-id))++(defn dashboard-card-ids+ "The Card ids of the DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-fn-vec :card_id :model/DashboardCard :dashboard_id dashboard-id))++(defn dashboard-series-card-ids+ "The Card ids of the DashboardCardSeries of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-fn-vec :card_id :model/DashboardCardSeries+ {:where [:in :dashboardcard_id+ ^:allow-subquery {:select [:id]+ :from [(t2/table-name :model/DashboardCard)]+ :where [:= :dashboard_id dashboard-id]}]}))++(defn dashboard-action-ids+ "The Action ids of the DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-fn-vec :action_id :model/DashboardCard :dashboard_id dashboard-id))++(defn query-average-execution-times+ "A map of query hash to average execution time for the Queries with `query-hashes`."+ [query-hashes]+ (t2/select-fn->fn :query_hash :average_execution_time :model/Query :query_hash [:in query-hashes]))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn card-query+ "The query of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :dataset_query :model/Card :id card-id))++(defn card-queries+ "A map of Card id to query for the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))++(defn unarchived-dashboard-question-exists?+ "Whether an unarchived Card internal to the Dashboard with `dashboard-id` exists."+ [dashboard-id]+ (t2/exists? :model/Card :dashboard_id dashboard-id :archived false))++(defn card-internal-to-other-dashboard-exists?+ "Whether any of the Cards with `card-ids` is internal to a Dashboard other than `dashboard-id`."+ [dashboard-id card-ids]+ (t2/exists? :model/Card+ {:where [:and+ [:not= :dashboard_id dashboard-id]+ [:not= :dashboard_id nil]+ [:in :id card-ids]]}))++(defn insert-dashboard-tabs!+ "Insert the DashboardTab `rows` and return their ids."+ [rows]+ (t2/insert-returning-pks! :model/DashboardTab rows))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn personal-collection-for-user+ "The personal Collection of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/Collection :personal_owner_id user-id))++(defn dashcard+ "The DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one :model/DashboardCard dashcard-id))++(defn dashcard-in-dashboard+ "The DashboardCard with `dashcard-id` on the Dashboard with `dashboard-id`, or nil."+ [dashcard-id dashboard-id]+ (t2/select-one :model/DashboardCard :id dashcard-id :dashboard_id dashboard-id))++(defn dashcards-by-ids+ "The DashboardCards with `dashcard-ids`."+ [dashcard-ids]+ (t2/select :model/DashboardCard :id [:in dashcard-ids]))++(defn dashcard-parameter-mappings+ "A map of DashboardCard id to parameter mappings for the DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-pk->fn :parameter_mappings :model/DashboardCard :dashboard_id dashboard-id))++(defn dashcard-card-ids-by-id+ "A map of DashboardCard id to Card id for the DashboardCards with `dashcard-ids` of the Dashboard with+ `dashboard-id`."+ [dashboard-id dashcard-ids]+ (t2/select-pk->fn :card_id :model/DashboardCard :dashboard_id dashboard-id :id [:in dashcard-ids]))++(defn user-name-and-email+ "The name and email of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :first_name :last_name :email] user-id))++(defn user-names-and-emails+ "The names and emails of the Users with `user-ids`."+ [user-ids]+ (t2/select [:model/User :first_name :last_name :email] :id [:in user-ids]))++(defn pulse-channels-for-pulse+ "The id, type, and details of the PulseChannels of the Pulse with `pulse-id`."+ [pulse-id]+ (t2/select [:model/PulseChannel :id :channel_type :details] :pulse_id [:= pulse-id]))++(defn pulse-channel-recipients+ "The PulseChannelRecipients of the PulseChannel with `pulse-channel-id`."+ [pulse-channel-id]+ (t2/select :model/PulseChannelRecipient :pulse_channel_id pulse-channel-id))++(defn unarchived-pulses-for-dashboard+ "The unarchived Pulses of the Dashboard with `dashboard-id`, in id order."+ [dashboard-id]+ (t2/select :model/Pulse :dashboard_id dashboard-id :archived false {:order-by [[:id :asc]]}))diff --git a/src/metabase/data_studio/api/table.clj b/src/metabase/data_studio/api/table.cljindex 27f6f18b180..cc867381035 100644--- a/src/metabase/data_studio/api/table.clj+++ b/src/metabase/data_studio/api/table.clj@@ -2,10 +2,10 @@"/api/data-studio/table endpoints for bulk table operations."(:require[clojure.set :as set]- [clojure.string :as str][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]+ [metabase.data-studio.db :as data-studio.db][metabase.database-routing.core :as database-routing][metabase.driver.settings :as driver.settings][metabase.driver.util :as driver.u]@@ -15,12 +15,10 @@[metabase.util :as u][metabase.util.jvm :as u.jvm][metabase.util.log :as log]- [metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms][metabase.util.quick-task :as quick-task]- [metabase.warehouse-schema.models.table :as table]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.models.table :as table]))(set! *warn-on-reflection* true)@@ -31,66 +29,44 @@[:schema_ids {:optional true} [:sequential :string]][:table_ids {:optional true} [:sequential ms/PositiveInt]]])-(mu/defn ^:private table-selectors->filter- [{:keys [database_ids table_ids schema_ids]}]- (let [schema-expr (fn [s]- (let [[schema-db-id schema-name] (str/split s #"\:")]- [:and [:= :db_id (parse-long schema-db-id)] [:= :schema schema-name]]))]- (cond-> [:or false]- (seq database_ids) (conj [:in :db_id (sort database_ids)])- (seq table_ids) (conj [:in :id (sort table_ids)])- (seq schema_ids) (conj (into [:or] (map schema-expr) (sort schema_ids))))))-(mr/def ::data-layers(into [:enum {:decode/string keyword}] table/data-layers));;; ------------------------------------------------ Remapping Graph Traversal -------------------------------------------------(defn- remapped-table-ids+(defn- remapped-table-ids-for-tables"Find tables connected via FK remapping (Dimensions).`input-field` and `output-field` are field aliases (:source_field or :target_field).- Returns table IDs from `output-field` that are connected to `tables` via `input-field`.- `tables` can be a set of table IDs or a HoneySQL subquery map."- [input-field output-field tables]- (if (empty? tables)+ Returns table IDs from `output-field` that are connected to the Tables with `table-ids` via `input-field`."+ [input-field output-field table-ids]+ (if (empty? table-ids)#{}- (let [input-table-id (keyword (name input-field) "table_id")- output-table-id (keyword (name output-field) "table_id")- not-in-tables (if (map? tables)- [:not [:exists (-> tables- (assoc :select [1])- (update :where (fn [where]- [:and where [:= :id output-table-id]])))]]- [:not [:in output-table-id tables]])]- (into #{} (map :table_id)- (t2/reducible-query {:select [[output-table-id :table_id]]- :from [[(t2/table-name :model/Dimension) :dim]]- :join [[(t2/table-name :model/Field) :source_field]- [:= :dim.field_id :source_field.id]- [(t2/table-name :model/Field) :target_field]- [:= :dim.human_readable_field_id :target_field.id]]- :where [:and- [:= :dim.type "external"]- [:in input-table-id tables]- not-in-tables]})))))+ (into #{} (map :table_id)+ (data-studio.db/fk-remapped-table-ids-for-tables+ (keyword (name input-field) "table_id")+ (keyword (name output-field) "table_id")+ table-ids+ table-ids))))++(defn- remapped-table-ids-for-selectors+ "Find tables connected via FK remapping (Dimensions) to the Tables picked out by `selectors`.+ `input-field` and `output-field` are field aliases (:source_field or :target_field)."+ [input-field output-field selectors]+ (into #{} (map :table_id)+ (data-studio.db/fk-remapped-table-ids-for-selectors+ (keyword (name input-field) "table_id")+ (keyword (name output-field) "table_id")+ selectors)))(defn- upstream-table-ids- "Given a table selector (set of IDs or subquery), find all tables that these tables depend on- via FK remapping (Dimensions)."- [source-tables]- (remapped-table-ids :source_field :target_field source-tables))+ "Given a set of table IDs, find all tables that these tables depend on via FK remapping (Dimensions)."+ [table-ids]+ (remapped-table-ids-for-tables :source_field :target_field table-ids))(defn- downstream-table-ids- "Given a table selector (set of IDs or subquery), find all tables that depend on these tables- via FK remapping (Dimensions)."- [target-tables]- (remapped-table-ids :target_field :source_field target-tables))--(defn- table-subquery- "Create a subquery that selects table IDs matching the given WHERE clause."- [where]- ^:allow-subquery- {:select [:id] :from [(t2/table-name :model/Table)] :where where})+ "Given a set of table IDs, find all tables that depend on these tables via FK remapping (Dimensions)."+ [table-ids]+ (remapped-table-ids-for-tables :target_field :source_field table-ids))(defn- traverse-graph"Recursively traverse the remapping graph starting from initial-ids.@@ -105,21 +81,21 @@new-neighbors)))))(defn- all-upstream-table-ids- "Get all upstream table IDs recursively for tables matching the given WHERE clause.+ "Get all upstream table IDs recursively for tables picked out by `selectors`.The first hop uses a subquery to avoid materializing potentially millions of IDs;subsequent hops use IDs since remappings are rare."- [source-table-where]- (let [initial-ids (upstream-table-ids (table-subquery source-table-where))]+ [selectors]+ (let [initial-ids (remapped-table-ids-for-selectors :source_field :target_field selectors)](if (empty? initial-ids)#{}(traverse-graph upstream-table-ids initial-ids))))(defn- all-downstream-table-ids- "Get all downstream table IDs recursively for tables matching the given WHERE clause.+ "Get all downstream table IDs recursively for tables picked out by `selectors`.The first hop uses a subquery to avoid materializing potentially millions of IDs;subsequent hops use IDs since remappings are rare."- [target-table-where]- (let [initial-ids (downstream-table-ids (table-subquery target-table-where))]+ [selectors]+ (let [initial-ids (remapped-table-ids-for-selectors :target_field :source_field selectors)](if (empty? initial-ids)#{}(traverse-graph downstream-table-ids initial-ids))))@@ -157,7 +133,7 @@(u.jvm/in-virtual-thread*(fn [](doseq [[db-id tables] (group-by :db_id newly-unhidden)]- (let [database (t2/select-one :model/Database db-id)]+ (let [database (data-studio.db/database db-id)];; it's okay to allow testing H2 connections during sync. We only want to disallow you from testing them for the;; purposes of creating a new H2 database.(if (binding [driver.settings/*allow-testing-h2-connections* true@@ -190,21 +166,21 @@[:owner_email {:optional true} [:maybe :string]][:owner_user_id {:optional true} [:maybe :int]]]]](api/check-data-analyst)- (let [where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))+ (let [selectors (select-keys body [:database_ids :schema_ids :table_ids])set-ks [:data_authority:data_source:data_layer:owner_email:owner_user_id:entity_type]- existing-tables (t2/select :model/Table {:where where})+ existing-tables (data-studio.db/tables-matching-selectors selectors)table-ids (set (map :id existing-tables))set-map (select-keys body set-ks)](when (seq set-map)- (t2/update! :model/Table [:in table-ids] set-map)+ (data-studio.db/update-tables! table-ids set-map)(maybe-sync-unhidden-tables! existing-tables set-map);; Publish update events for remote sync tracking- (let [updated-tables (t2/select :model/Table :id [:in table-ids])]+ (let [updated-tables (data-studio.db/tables table-ids)](doseq [table updated-tables](events/publish-event! :event/table-update {:object table:user-id api/*current-user-id*}))))@@ -216,17 +192,16 @@_query-paramsbody :- ::table-selectors](api/check-data-analyst)- (let [fields [:model/Table :id :db_id :name :display_name :schema :is_published]- where (table-selectors->filter (select-keys body [:database_ids :schema_ids :table_ids]))- selected-tables (t2/select fields {:where where :limit 2})+ (let [selectors (select-keys body [:database_ids :schema_ids :table_ids])+ selected-tables (data-studio.db/selection-columns-for-selectors selectors 2)selected-table (when-not (next selected-tables)(first selected-tables))- upstream-ids (all-upstream-table-ids where)- downstream-ids (all-downstream-table-ids where)+ upstream-ids (all-upstream-table-ids selectors)+ downstream-ids (all-downstream-table-ids selectors)upstream-tables (when (seq upstream-ids)- (t2/select fields :id [:in upstream-ids]))+ (data-studio.db/selection-columns-for-tables upstream-ids))downstream-tables (when (seq downstream-ids)- (t2/select fields :id [:in downstream-ids]))]+ (data-studio.db/selection-columns-for-tables downstream-ids))]{:selected_table selected-table:published_downstream_tables (filterv :is_published downstream-tables):unpublished_upstream_tables (filterv (complement :is_published) upstream-tables)}))@@ -244,9 +219,9 @@_body :- ::table-selectors](api/check-data-analyst)- (let [tables (t2/select :model/Table {:where (table-selectors->filter body), :order-by [[:id]]})+ (let [tables (data-studio.db/tables-matching-selectors-in-id-order body)db-ids (sort (set (map :db_id tables)))]- (doseq [database (t2/select :model/Database :id [:in db-ids])]+ (doseq [database (data-studio.db/databases db-ids)](try(binding [driver.settings/*allow-testing-h2-connections* truedriver.settings/*allow-testing-sqlite-connections* true]@@ -264,7 +239,7 @@_body :- ::table-selectors](api/check-data-analyst)- (let [tables (t2/select :model/Table {:where (table-selectors->filter body), :order-by [[:id]]})]+ (let [tables (data-studio.db/tables-matching-selectors-in-id-order body)];; same permission skip as the single-table api, see comment in /:id/rescan_values(doseq [table tables](events/publish-event! :event/table-manual-scan {:object table :user-id api/*current-user-id*})@@ -277,12 +252,8 @@_body :- ::table-selectors](api/check-data-analyst)- (let [tables (t2/select :model/Table {:where (table-selectors->filter body), :order-by [[:id]]})]- (let [field-ids-to-delete-q ^:allow-subquery- {:select [:id]- :from [(t2/table-name :model/Field)]- :where [:in :table_id (map :id tables)]}]- (t2/delete! (t2/table-name :model/FieldValues) :field_id [:in field-ids-to-delete-q]))+ (let [tables (data-studio.db/tables-matching-selectors-in-id-order body)]+ (data-studio.db/delete-field-values-for-tables! (map :id tables))nil))(def ^{:arglists '([request respond raise])} routesdiff --git a/src/metabase/data_studio/db.clj b/src/metabase/data_studio/db.cljnew file mode 100644index 00000000000..7a08b5993f4--- /dev/null+++ b/src/metabase/data_studio/db.clj@@ -0,0 +1,104 @@+(ns metabase.data-studio.db+ "Application database queries for the data studio module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [clojure.string :as str]+ [toucan2.core :as t2]))++(defn- table-selectors-where+ "The `:where` clause for the Tables picked out by `selectors`, a map of `:database_ids`, `:schema_ids`,+ and/or `:table_ids`."+ [{:keys [database_ids table_ids schema_ids]}]+ (let [schema-expr (fn [s]+ (let [[schema-db-id schema-name] (str/split s #"\:")]+ [:and [:= :db_id (parse-long schema-db-id)] [:= :schema schema-name]]))]+ (cond-> [:or false]+ (seq database_ids) (conj [:in :db_id (sort database_ids)])+ (seq table_ids) (conj [:in :id (sort table_ids)])+ (seq schema_ids) (conj (into [:or] (map schema-expr) (sort schema_ids))))))++(defn fk-remapped-table-ids-for-tables+ "The `:table_id`s reached through external Dimensions from the Tables with `table-ids`, reading the Table id+ of the `input-table-id` column and returning that of the `output-table-id` column, excluding ids already in+ `exclude-table-ids`."+ [input-table-id output-table-id table-ids exclude-table-ids]+ (t2/reducible-query {:select [[output-table-id :table_id]]+ :from [[(t2/table-name :model/Dimension) :dim]]+ :join [[(t2/table-name :model/Field) :source_field]+ [:= :dim.field_id :source_field.id]+ [(t2/table-name :model/Field) :target_field]+ [:= :dim.human_readable_field_id :target_field.id]]+ :where [:and+ [:= :dim.type "external"]+ [:in input-table-id table-ids]+ [:not [:in output-table-id exclude-table-ids]]]}))++(defn fk-remapped-table-ids-for-selectors+ "The `:table_id`s reached through external Dimensions from the Tables picked out by `selectors`, reading the+ Table id of the `input-table-id` column and returning that of the `output-table-id` column, excluding Tables+ also picked out by `selectors`."+ [input-table-id output-table-id selectors]+ (let [where (table-selectors-where selectors)]+ (t2/reducible-query {:select [[output-table-id :table_id]]+ :from [[(t2/table-name :model/Dimension) :dim]]+ :join [[(t2/table-name :model/Field) :source_field]+ [:= :dim.field_id :source_field.id]+ [(t2/table-name :model/Field) :target_field]+ [:= :dim.human_readable_field_id :target_field.id]]+ :where [:and+ [:= :dim.type "external"]+ [:in input-table-id ^:allow-subquery+ {:select [:id] :from [(t2/table-name :model/Table)] :where where}]+ [:not [:exists ^:allow-subquery+ {:select [1]+ :from [(t2/table-name :model/Table)]+ :where [:and where [:= :id output-table-id]]}]]]})))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn databases+ "The Databases with `database-ids`."+ [database-ids]+ (t2/select :model/Database :id [:in database-ids]))++(defn tables-matching-selectors+ "The Tables picked out by `selectors`, a map of `:database_ids`, `:schema_ids`, and/or `:table_ids`."+ [selectors]+ (t2/select :model/Table {:where (table-selectors-where selectors)}))++(defn tables-matching-selectors-in-id-order+ "The Tables picked out by `selectors`, in id order."+ [selectors]+ (t2/select :model/Table {:where (table-selectors-where selectors), :order-by [[:id]]}))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn update-tables!+ "Apply `changes` to the Tables with `table-ids`."+ [table-ids changes]+ (t2/update! :model/Table [:in table-ids] changes))++(defn selection-columns-for-selectors+ "Up to `limit` id, database, name, schema, and published flag of the Tables picked out by `selectors`."+ [selectors limit]+ (t2/select [:model/Table :id :db_id :name :display_name :schema :is_published]+ {:where (table-selectors-where selectors), :limit limit}))++(defn selection-columns-for-tables+ "The id, database, name, schema, and published flag of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :db_id :name :display_name :schema :is_published] :id [:in table-ids]))++(defn delete-field-values-for-tables!+ "Delete the FieldValues of the Fields of the Tables with `table-ids`."+ [table-ids]+ (t2/delete! (t2/table-name :model/FieldValues)+ :field_id [:in ^:allow-subquery {:select [:id]+ :from [(t2/table-name :model/Field)]+ :where [:in :table_id table-ids]}]))diff --git a/src/metabase/documents/api/document.clj b/src/metabase/documents/api/document.cljindex 8fcfedb2edd..84643d82e26 100644--- a/src/metabase/documents/api/document.clj+++ b/src/metabase/documents/api/document.clj@@ -5,7 +5,7 @@[metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.collections.core :as collections]- [metabase.collections.models.collection :as collection]+ [metabase.documents.db :as documents.db][metabase.documents.models.document :as m.document][metabase.documents.prose-mirror :as prose-mirror][metabase.documents.schema :as documents.schema]@@ -160,9 +160,7 @@(pos-int? (-> % :attrs :id)))(-> % :attrs :id)))to-clone (when (seq card-ids)- (t2/select :model/Card {:where [:and [:in :id card-ids]- [:or [:<> :document_id id]- [:= :document_id nil]]]}))]+ (documents.db/cards-not-in-document card-ids id))](m.document/with-content-gate-cache(reduce (fn [accum card](api/read-check card)@@ -178,8 +176,7 @@publish a read event, so it is safe to use on write paths (PUT/POST) where recording a view would beboth semantically wrong and an extra, avoidable round-trip."[id]- (t2/hydrate (t2/select-one :model/Document :id id)- :creator :can_write :can_delete :can_restore :is_remote_synced))+ (t2/hydrate (documents.db/document id) :creator :can_write :can_delete :can_restore :is_remote_synced))(defn get-document"Get document by id, checking that it exists and the current user can read it, and recording a view.@@ -224,11 +221,11 @@concurrent edit cannot be overwritten. Returns the updated document."[document-id card-id position & {:keys [extra-attrs]}](t2/with-transaction [_conn]- (let [document (api/check-404 (t2/select-one :model/Document :id document-id))+ (let [document (api/check-404 (documents.db/document document-id))updated (prose-mirror/insert-card-embed document card-id position extra-attrs)updates (cond-> (select-keys updated [:document])(:is_placeholder document) (assoc :is_placeholder false))]- (t2/update! :model/Document document-id updates)+ (documents.db/update-document! document-id updates)(collections/check-for-remote-sync-update document)))(get-document document-id :log-view? false))@@ -240,14 +237,9 @@"Gets existing `Documents`."[_route-params_query-params]- {:items (as-> (t2/select :model/Document {:where [:and- (collection/visible-collection-filter-clause)- [:= :archived false]- ;; Documents attached to an exploration are- ;; internal to that exploration — every other listing- ;; surface (search, recents, collection items)- ;; excludes them too.- [:= :exploration_id nil]]}) docs+ ;; Documents attached to an exploration are internal to that exploration — every other listing surface (search,+ ;; recents, collection items) excludes them too.+ {:items (as-> (documents.db/visible-unarchived-documents) docs(filter mi/can-read? docs)(t2/hydrate docs :creator :can_write :is_remote_synced))})@@ -265,12 +257,12 @@(when collection_position(api/maybe-reconcile-collection-position! {:collection_id collection_id:collection_position collection_position}))- (let [document-id (t2/insert-returning-pk! :model/Document {:name name- :collection_id collection_id- :collection_position collection_position- :document document- :content_type prose-mirror/prose-mirror-content-type- :creator_id api/*current-user-id*})+ (let [document-id (documents.db/insert-document! {:name name+ :collection_id collection_id+ :collection_position collection_position+ :document document+ :content_type prose-mirror/prose-mirror-content-type+ :creator_id api/*current-user-id*})cards-to-update-in-ast (merge (clone-cards-in-document! {:id document-id:collection_id collection_id:document document@@ -278,11 +270,11 @@(when-not (empty? cards)(create-cards-for-document! cards document-id collection_id @api/*current-user*)))](when (seq cards-to-update-in-ast)- (t2/update! :model/Document :id document-id- (update-cards-in-ast- {:document document- :content_type prose-mirror/prose-mirror-content-type}- cards-to-update-in-ast)))+ (documents.db/update-document! document-id+ (update-cards-in-ast+ {:document document+ :content_type prose-mirror/prose-mirror-content-type}+ cards-to-update-in-ast)))(u/prog1 (get-document document-id)(when (collections/remote-synced-collection? (:collection_id <>))(collections/check-non-remote-synced-dependencies <>)))))]@@ -315,7 +307,7 @@;; Use a lightweight fetch for the guard: we only need the raw row for the archived/permission/collection-move;; checks below. Calling `get-document` here would hydrate display fields we don't use and record a *view* of;; the document on every save.- (let [existing-document (api/check-404 (t2/select-one :model/Document :id document-id))]+ (let [existing-document (api/check-404 (documents.db/document document-id))](when-not (contains? body :archived)(api/check-not-archived existing-document))(api/write-check existing-document)@@ -338,18 +330,18 @@pairings (draft-stored-result-pairings document(:content_type existing-document)draft-card-id-map)]- (t2/update! :model/Document document-id- (cond-> document-updates- document (merge (update-cards-in-ast- {:document document- :content_type (:content_type existing-document)}- card-id-map))- name (assoc :name name)- (contains? body :collection_id) (assoc :collection_id collection_id)- ;; First body save clears the auto-created Summary placeholder flag.- (and (:is_placeholder existing-document)- (contains? body :document))- (assoc :is_placeholder false)))+ (documents.db/update-document! document-id+ (cond-> document-updates+ document (merge (update-cards-in-ast+ {:document document+ :content_type (:content_type existing-document)}+ card-id-map))+ name (assoc :name name)+ (contains? body :collection_id) (assoc :collection_id collection_id)+ ;; First body save clears the auto-created Summary placeholder flag.+ (and (:is_placeholder existing-document)+ (contains? body :document))+ (assoc :is_placeholder false)))(when (seq pairings)(card/carry-pairings-for-document! document-id pairings)))(collections/check-for-remote-sync-update existing-document))@@ -373,12 +365,12 @@(api.macros/defendpoint :delete "/:document-id""Permanently deletes an archived Document."[{:keys [document-id]} :- [:map [:document-id ms/PositiveInt]]]- (let [document (api/check-404 (t2/select-one :model/Document :id document-id))]+ (let [document (api/check-404 (documents.db/document document-id))](api/write-check document)(when-not (:archived document)(let [msg (tru "Document must be archived before it can be deleted.")](throw (ex-info msg {:status-code 400, :errors {:archived msg}}))))- (t2/delete! :model/Document :id document-id)+ (documents.db/delete-document! document-id)(events/publish-event! :event/document-delete{:object document:user-id api/*current-user-id*})@@ -399,7 +391,7 @@[source-document-id :- ms/PositiveIntnew-document-id :- ms/PositiveIntnew-collection-id :- [:or :nil ms/PositiveInt]]- (let [cards-to-copy (t2/select :model/Card :document_id source-document-id)]+ (let [cards-to-copy (documents.db/cards-for-document source-document-id)](reduce (fn [accum card];; The document_id FK can outlive a card's presence in the document body, and the card may sit in a;; collection the caller cannot read. Read-check each card before copying, mirroring@@ -412,9 +404,9 @@:collection_id new-collection-id))@api/*current-user*)](when (or (:archived card) (:archived_directly card))- (t2/update! :model/Card (:id new-card)- {:archived (boolean (:archived card))- :archived_directly (boolean (:archived_directly card))}))+ (documents.db/update-card! (:id new-card)+ {:archived (boolean (:archived card))+ :archived_directly (boolean (:archived_directly card))}))(assoc accum (:id card) (:id new-card)))){}cards-to-copy)))@@ -431,7 +423,7 @@(api/create-check :model/Document {:collection_id collection_id})(let [existing-document (api/check-404(api/read-check- (t2/select-one :model/Document :id from-document-id :archived false)))+ (documents.db/unarchived-document from-document-id)))document-data {:name (or name (:name existing-document)):document (:document existing-document):content_type (:content_type existing-document)@@ -441,14 +433,14 @@new-document (t2/with-transaction [_conn](when collection_position(api/maybe-reconcile-collection-position! document-data))- (let [new-document-id (t2/insert-returning-pk! :model/Document document-data)+ (let [new-document-id (documents.db/insert-document! document-data)card-id-map (copy-cards-for-document! from-document-id new-document-id collection_id)](when (seq card-id-map)- (t2/update! :model/Document :id new-document-id- (update-cards-in-ast- {:document (:document existing-document)- :content_type (:content_type existing-document)}- card-id-map)))+ (documents.db/update-document! new-document-id+ (update-cards-in-ast+ {:document (:document existing-document)+ :content_type (:content_type existing-document)}+ card-id-map)))(u/prog1 (get-document new-document-id)(when (collections/remote-synced-collection? collection_id)(collections/check-non-remote-synced-dependencies <>)))))]@@ -477,14 +469,14 @@;; Use a transaction to prevent race conditions when two requests arrive simultaneously.;; Only one request will successfully create the UUID; both will return the same value.(t2/with-transaction [_conn]- (if-let [existing-uuid (t2/select-one-fn :public_uuid :model/Document :id document-id)]+ (if-let [existing-uuid (documents.db/document-public-uuid document-id)]{:uuid existing-uuid}(do- (t2/update! :model/Document document-id- {:public_uuid (str (random-uuid))- :made_public_by_id api/*current-user-id*})+ (documents.db/update-document! document-id+ {:public_uuid (str (random-uuid))+ :made_public_by_id api/*current-user-id*});; Always select after update to ensure we return what's actually stored- {:uuid (t2/select-one-fn :public_uuid :model/Document :id document-id)}))))+ {:uuid (documents.db/document-public-uuid document-id)}))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -505,9 +497,9 @@(api/check-superuser)(public-sharing.validation/check-public-sharing-enabled)(api/check-exists? :model/Document :id document-id, :public_uuid [:not= nil], :archived false)- (t2/update! :model/Document document-id- {:public_uuid nil- :made_public_by_id nil})+ (documents.db/update-document! document-id+ {:public_uuid nil+ :made_public_by_id nil})api/generic-204-no-content)(api.macros/defendpoint :get "/public" :- [:sequential [:map@@ -526,7 +518,7 @@[](api/check-superuser)(public-sharing.validation/check-public-sharing-enabled)- (t2/select [:model/Document :name :id :public_uuid], :public_uuid [:not= nil], :archived false))+ (documents.db/public-documents));;; ------------------------------------------------ Card Downloads --------------------------------------------------@@ -536,10 +528,10 @@Throws a 404 exception via `api/check-404` if any validation fails. Returns card-id on success."[document-id card-id]- (let [document (api/check-404 (t2/select-one :model/Document :id document-id :archived false))]+ (let [document (api/check-404 (documents.db/unarchived-document document-id))](api/read-check document)(api/check-404 (and (contains? (set (prose-mirror/card-ids document)) card-id)- (t2/exists? :model/Card :id card-id :document_id document-id :archived false)))))+ (documents.db/unarchived-card-in-document-exists? card-id document-id)))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -575,7 +567,7 @@[:pivot_results {:default false} ms/BooleanValue]]](validate-card-in-document document-id card-id)(qp.card/process-query-for-card- (api/check-404 (t2/select-one :model/Card card-id)) export-format+ (api/check-404 (documents.db/card card-id)) export-format:parameters parameters:constraints nil:context (api.dataset/export-format->context export-format)diff --git a/src/metabase/documents/db.clj b/src/metabase/documents/db.cljnew file mode 100644index 00000000000..df07505559c--- /dev/null+++ b/src/metabase/documents/db.clj@@ -0,0 +1,126 @@+(ns metabase.documents.db+ "Application database queries for the documents module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [java-time.api :as t]+ [metabase.collections.models.collection :as collection]+ [toucan2.core :as t2]))++(defn document+ "The Document with `id`, or nil."+ [id]+ (t2/select-one :model/Document :id id))++(defn unarchived-document+ "The Document with `id` if it is not archived, or nil."+ [id]+ (t2/select-one :model/Document :id id :archived false))++(defn visible-unarchived-documents+ "The unarchived Documents not attached to an Exploration, in a Collection visible to the current user."+ []+ (t2/select :model/Document {:where [:and+ (collection/visible-collection-filter-clause)+ [:= :archived false]+ [:= :exploration_id nil]]}))++(defn insert-document!+ "Insert the Document `row` and return its id."+ [row]+ (t2/insert-returning-pk! :model/Document row))++(defn update-document!+ "Apply `changes` to the Document with `id`."+ [id changes]+ (t2/update! :model/Document id changes))++(defn delete-document!+ "Delete the Document with `id`."+ [id]+ (t2/delete! :model/Document :id id))++(defn document-public-uuid+ "The public uuid of the Document with `id`, or nil."+ [id]+ (t2/select-one-fn :public_uuid :model/Document :id id))++(defn document-exploration-id+ "The Exploration id of the Document with `id`, or nil."+ [id]+ (t2/select-one-fn :exploration_id :model/Document :id id))++(defn public-documents+ "The name, id, and public uuid of the unarchived Documents that are publicly shared."+ []+ (t2/select [:model/Document :name :id :public_uuid], :public_uuid [:not= nil], :archived false))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card card-id))++(defn cards-not-in-document+ "The Cards with `card-ids` that do not belong to the Document with `document-id`."+ [card-ids document-id]+ (t2/select :model/Card {:where [:and [:in :id card-ids]+ [:or [:<> :document_id document-id]+ [:= :document_id nil]]]}))++(defn cards-for-document+ "The Cards of the Document with `document-id`."+ [document-id]+ (t2/select :model/Card :document_id document-id))++(defn unarchived-cards-for-documents+ "The unarchived Cards of the Documents with `document-ids`."+ [document-ids]+ (t2/select :model/Card :document_id [:in document-ids] :archived false))++(defn unarchived-card-in-document-exists?+ "Whether the unarchived Card with `card-id` belongs to the Document with `document-id`."+ [card-id document-id]+ (t2/exists? :model/Card :id card-id :document_id document-id :archived false))++(defn update-card!+ "Apply `changes` to the Card with `card-id`."+ [card-id changes]+ (t2/update! :model/Card card-id changes))++(defn update-cards-for-document!+ "Apply `changes` to the Cards of the Document with `document-id`."+ [document-id changes]+ (t2/update! :model/Card :document_id document-id changes))++(defn unarchived-collection-exists?+ "Whether an unarchived Collection with `collection-id` exists."+ [collection-id]+ (t2/exists? :model/Collection :id collection-id :archived false))++(defn user-columns+ "The id, email, and name of the Users with `user-ids`."+ [user-ids]+ (t2/select [:model/User :id :email :first_name :last_name] :id [:in user-ids]))++(defn table+ "The Table with `id`, or nil."+ [id]+ (t2/select-one :model/Table :id id))++(defn dashboard+ "The Dashboard with `id`, or nil."+ [id]+ (t2/select-one :model/Dashboard :id id))++(defn update-documents-last-viewed-at!+ "Move `last_viewed_at` of each Document in `document-id->timestamp` forward to its timestamp, without touching+ `updated_at`."+ [document-id->timestamp]+ ;; A raw update rather than `t2/update!` so Toucan 2 model hooks don't fire: the :model/Document after-update+ ;; publishes :event/document-update and syncs card collections, side effects that must not re-run on retry.+ (t2/query {:update (t2/table-name :model/Document)+ :set {:last_viewed_at (into [:case]+ (mapcat (fn [[id timestamp]]+ [[:= :id id] [:greatest [:coalesce :last_viewed_at (t/offset-date-time 0)] timestamp]])+ document-id->timestamp))+ :updated_at :updated_at}+ :where [:in :id (keys document-id->timestamp)]}))diff --git a/src/metabase/documents/models/document.clj b/src/metabase/documents/models/document.cljindex 02cfd0f6ef2..f7d429decf0 100644--- a/src/metabase/documents/models/document.clj+++ b/src/metabase/documents/models/document.clj@@ -3,6 +3,7 @@[clojure.string :as str][metabase.api.common :as api][metabase.collections.models.collection :as collection]+ [metabase.documents.db :as documents.db][metabase.documents.prose-mirror :as prose-mirror][metabase.events.core :as events][metabase.models.interface :as mi]@@ -111,15 +112,15 @@([instance](and (mi/current-user-has-full-permissions? :read instance)(content-visible? instance)))- ([model pk]- (mi/can-read? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-read? (documents.db/document pk))))(defmethod mi/can-write? :model/Document([instance](and (mi/current-user-has-full-permissions? :write instance)(content-visible? instance)))- ([model pk]- (mi/can-write? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-write? (documents.db/document pk))))(def DocumentName"Validations for the name of a document"@@ -141,7 +142,7 @@(when old-collection-id(api/write-check :model/Collection old-collection-id))(when new-collection-id- (api/check-400 (t2/exists? :model/Collection :id new-collection-id :archived false))+ (api/check-400 (documents.db/unarchived-collection-exists? new-collection-id))(api/write-check :model/Collection new-collection-id)))(methodical/defmethod t2/batched-hydrate [:model/Document :creator]@@ -149,9 +150,10 @@[_model k documents](mi/instances-with-hydrated-datadocuments k- #(-> (t2/select [:model/User :id :email :first_name :last_name] :id (keep :creator_id documents))- (map (juxt :id identity))- (into {}))+ #(when-let [creator-ids (seq (keep :creator_id documents))]+ (-> (documents.db/user-columns creator-ids)+ (map (juxt :id identity))+ (into {}))):creator_id {:default {}}))(methodical/defmethod t2/batched-hydrate [:model/Document :cards]@@ -161,9 +163,7 @@(let [document-ids (keep :id documents);; Fetch all cards for all documents in one batched queryall-cards (when (seq document-ids)- (t2/select :model/Card- :document_id [:in document-ids]- :archived false))+ (documents.db/unarchived-cards-for-documents document-ids));; Group cards by document_id, then convert each group to a map keyed by card IDcards-by-doc-id (group-by :document_id all-cards)cards-maps-by-doc-id (update-vals cards-by-doc-id@@ -179,9 +179,7 @@(let [update-map {:collection_id collection-id:archived (boolean archived):archived_directly (boolean archived-directly)}]- (t2/update! :model/Card- :document_id document-id- update-map)))+ (documents.db/update-cards-for-document! document-id update-map)))(t2/define-after-update :model/Document[{:keys [id collection_id archived archived_directly] :as instance}]@@ -259,11 +257,14 @@;;; ---------------------------------------------- Serialization ---------------------------------------------------(def ^:private ast-model->db-model- {"card" :model/Card- "dataset" :model/Card- "table" :model/Table- "dashboard" :model/Dashboard})+(defn- ast-model->entity+ "The database row identified by the smart-link/card-embed `model` (\"card\", \"dataset\", \"table\", or+ \"dashboard\") and `id`, or nil."+ [model id]+ (case model+ ("card" "dataset") (documents.db/card id)+ "table" (documents.db/table id)+ "dashboard" (documents.db/dashboard id)))(def ^:private model->serdes-model{"card" "Card"@@ -287,7 +288,7 @@node (cond-> node(= prose-mirror/card-embed-type type)(update :attrs #(apply dissoc % non-portable-card-embed-attrs)))]- (if-let [db-model (and id (t2/select-one (ast-model->db-model model) :id id))]+ (if-let [db-model (and id (ast-model->entity model id))](assoc-in node [:attrs id-key] (mapv #(dissoc % :label) (serdes/generate-path (model->serdes-model model) db-model)))(u/prog1 node(log/warnf "entity_id not found for %s at id: %s" model id)))))@@ -398,7 +399,7 @@(defmethod serdes/descendants "Document"[_model-name id _opts]- (when-let [document (t2/select-one :model/Document :id id)]+ (when-let [document (documents.db/document id)](when (= prose-mirror/prose-mirror-content-type (:content_type document))(merge(into {}diff --git a/src/metabase/documents/view_log.clj b/src/metabase/documents/view_log.cljindex e6a4fd4426a..07feac2f3e1 100644--- a/src/metabase/documents/view_log.clj+++ b/src/metabase/documents/view_log.clj@@ -5,12 +5,12 @@[metabase.activity-feed.core :as activity-feed][metabase.app-db.cluster-lock :as cluster-lock][metabase.batch-processing.core :as grouper]+ [metabase.documents.db :as documents.db][metabase.events.core :as events][metabase.util.log :as log][metabase.view-log.core :as view-log][methodical.core :as m]- [steffan-westcott.clj-otel.api.trace.span :as span]- [toucan2.core :as t2]))+ [steffan-westcott.clj-otel.api.trace.span :as span]))(def ^:private document-statistics-lock"keyword to use for locking document updates that can deadlock"@@ -28,16 +28,7 @@;; :retry-transient? — the body is a single idempotent statement, safe to re-run on a;; multi-master deadlock (e.g. MariaDB Galera, where the cluster lock can't serialize writers).(cluster-lock/with-cluster-lock {:lock document-statistics-lock :retry-transient? true}- ;; Use t2/query (raw SQL) instead of t2/update! so we don't trigger Toucan2 model hooks — the- ;; :model/Document after-update publishes :event/document-update and syncs card collections, which- ;; are side effects outside the tx and must not re-fire when :retry-transient? re-runs the body.- (t2/query {:update (t2/table-name :model/Document)- :set {:last_viewed_at (into [:case]- (mapcat (fn [[id timestamp]]- [[:= :id id] [:greatest [:coalesce :last_viewed_at (t/offset-date-time 0)] timestamp]])- document-id->timestamp))- :updated_at :updated_at} ;; setting last_viewed_at should not update the updated_at column- :where [:in :id (keys document-id->timestamp)]}))+ (documents.db/update-documents-last-viewed-at! document-id->timestamp))(catch Exception e(log/errorf "Failed to update document last_viewed_at: %s" (ex-message e))))))@@ -68,7 +59,7 @@;; Exploration documents aren't first-class content — they're surfaced only through their;; owning Exploration, and are hidden from search and collection listings. Skip recording;; recent views for them so they don't crowd out real document views in the bucket cap.- (when (nil? (t2/select-one-fn :exploration_id :model/Document :id object-id))+ (when (nil? (documents.db/document-exploration-id object-id))(activity-feed/update-users-recent-views! user-id :model/Document object-id :view))(catch Throwable e(log/warnf "Failed to process document view event. %s: %s" topic (ex-message e))))))diff --git a/src/metabase/driver/db.clj b/src/metabase/driver/db.cljnew file mode 100644index 00000000000..5693525fc67--- /dev/null+++ b/src/metabase/driver/db.clj@@ -0,0 +1,29 @@+(ns metabase.driver.db+ "Application database queries for the driver module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ ^{:clj-kondo/ignore [:discouraged-namespace]}+ [toucan2.core :as t2]))++(defn databases+ "Every Database."+ []+ (t2/select :model/Database))++(defn table-field-names+ "The names of the Fields of the Table with `table-id`."+ [table-id]+ (t2/select-fn-vec :name [:model/Field :name] :table_id table-id))++(defn database-connection-details+ "The engine and connection details of the Database with `database-id`, or nil."+ [database-id]+ (t2/select-one [:model/Database :id :engine :details :write_data_details :admin_details] :id database-id))++(defn json-field-names-with-unfolding-disabled+ "The names of the JSON Fields of the Table with `table-id` that have JSON unfolding disabled."+ [table-id]+ (t2/select-fn-set :name [:model/Field :name]+ :table_id table-id+ :base_type :type/JSON+ :json_unfolding false))diff --git a/src/metabase/driver/events/report_timezone_updated.clj b/src/metabase/driver/events/report_timezone_updated.cljindex 1e5a9d3e6bb..413fad4da63 100644--- a/src/metabase/driver/events/report_timezone_updated.clj+++ b/src/metabase/driver/events/report_timezone_updated.clj@@ -2,12 +2,10 @@(:require[metabase.driver :as driver][metabase.driver-api.core :as driver-api]+ [metabase.driver.db :as driver.db][metabase.events.core :as events][metabase.util.log :as log]- [methodical.core :as methodical]- ;; event handler runs outside any query; it enumerates Database rows itself, no metadata provider exists- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(events/derive! ::event :metabase/event)(events/derive! :event/report-timezone-updated ::event)@@ -20,7 +18,7 @@`nil` (meaning subsequent queries will not attempt to change the session timezone) or something considered invalidby a given Database (meaning subsequent queries will fail to change the session timezone)."[]- (doseq [{driver :engine, id :id, :as database} (t2/select :model/Database)]+ (doseq [{driver :engine, id :id, :as database} (driver.db/databases)](try(driver/notify-database-updated driver database)(catch Throwable ediff --git a/src/metabase/driver/sql_jdbc/actions.clj b/src/metabase/driver/sql_jdbc/actions.cljindex e3d12f2fa9b..5362d133759 100644--- a/src/metabase/driver/sql_jdbc/actions.clj+++ b/src/metabase/driver/sql_jdbc/actions.clj@@ -9,6 +9,7 @@[medley.core :as m][metabase.driver :as driver][metabase.driver-api.core :as driver-api]+ [metabase.driver.db :as driver.db][metabase.driver.sql-jdbc.execute :as sql-jdbc.execute][metabase.driver.sql.query-processor :as sql.qp][metabase.driver.util :as driver.u]@@ -19,8 +20,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.performance :as perf :refer [some mapv select-keys empty? not-empty get-in]]- [methodical.core :as methodical]- [toucan2.core :as t2])+ [methodical.core :as methodical])(:import(java.sql Connection SQLException)))@@ -276,7 +276,7 @@(let [field-names (driver-api/cached-value[::correct-columns-name table-id](fn []- (t2/select-fn-vec :name [:model/Field :name] :table_id table-id)+ (driver.db/table-field-names table-id);; can't use lib here because fields from lib only return active fields and visible fields;; :/#_(let [database (driver-api/cached-database-via-table-id table-id)]diff --git a/src/metabase/driver/sql_jdbc/connection.clj b/src/metabase/driver/sql_jdbc/connection.cljindex 629f3143143..1e745ff609b 100644--- a/src/metabase/driver/sql_jdbc/connection.clj+++ b/src/metabase/driver/sql_jdbc/connection.clj@@ -9,6 +9,7 @@[metabase.driver :as driver][metabase.driver-api.core :as driver-api][metabase.driver.connection :as driver.conn]+ [metabase.driver.db :as driver.db][metabase.driver.settings :as driver.settings][metabase.driver.sql-jdbc.common :as sql-jdbc.common][metabase.driver.sql-jdbc.connection.ssh-tunnel :as ssh]@@ -18,10 +19,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.performance :refer [get-in mapv select-keys]]- [potemkin :as p]- ;; pool invalidation re-fetches Database details from the app db; runs outside any query context- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [potemkin :as p])(:import(com.mchange.v2.c3p0 DataSources)(javax.sql DataSource)@@ -414,7 +412,7 @@;; the hash didn't match, but it's possible that a stale instance of `DatabaseInstance`;; was passed in (ex: from a long-running sync operation); fetch the latest one from;; our app DB, and see if it STILL doesn't match- (not= curr-hash (-> (t2/select-one [:model/Database :id :engine :details :write_data_details :admin_details] :id database-id)+ (not= curr-hash (-> (driver.db/database-connection-details database-id)jdbc-spec-hash)))))(defn- get-canonical-pooldiff --git a/src/metabase/driver/sql_jdbc/sync/describe_table.clj b/src/metabase/driver/sql_jdbc/sync/describe_table.cljindex 3df5ec2e97b..f897c0bab20 100644--- a/src/metabase/driver/sql_jdbc/sync/describe_table.clj+++ b/src/metabase/driver/sql_jdbc/sync/describe_table.clj@@ -10,6 +10,7 @@[metabase.driver-api.core :as driver-api][metabase.driver.common.table-rows-sample :as table-rows-sample][metabase.driver.connection :as driver.conn]+ [metabase.driver.db :as driver.db][metabase.driver.settings :as driver.settings][metabase.driver.sql :as driver.sql][metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]@@ -25,10 +26,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.performance :refer [some select-keys every? mapv empty? not-empty]]- [potemkin :as p]- ;; sync-time read of already-synced Field rows; sync runs without a metadata provider- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [potemkin :as p])(:import(com.fasterxml.jackson.coreJsonFactory@@ -752,10 +750,7 @@"Given a table return a list of json fields that need to unfold."[driver conn table](let [fields-with-json-unfolding-disabled- (->> (t2/select-fn-set :name [:model/Field :name]- :table_id (u/the-id table)- :base_type :type/JSON- :json_unfolding false)+ (->> (driver.db/json-field-names-with-unfolding-disabled (u/the-id table));; in a delay so we'll query only if there's at least one json field(delay))](into #{}diff --git a/src/metabase/eid_translation/db.clj b/src/metabase/eid_translation/db.cljnew file mode 100644index 00000000000..58694630bc5--- /dev/null+++ b/src/metabase/eid_translation/db.clj@@ -0,0 +1,104 @@+(ns metabase.eid-translation.db+ "Application database queries for the entity id translation module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn- ids-by-entity-ids+ [model entity-ids]+ (t2/select-fn->fn :entity_id :id [model :id :entity_id] :entity_id [:in entity-ids]))++(defn action-ids-by-entity-ids+ "A map of entity id to id for the Actions whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Action entity-ids))++(defn card-ids-by-entity-ids+ "A map of entity id to id for the Cards whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Card entity-ids))++(defn collection-ids-by-entity-ids+ "A map of entity id to id for the Collections whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Collection entity-ids))++(defn dashboard-ids-by-entity-ids+ "A map of entity id to id for the Dashboards whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Dashboard entity-ids))++(defn dashboard-card-ids-by-entity-ids+ "A map of entity id to id for the DashboardCards whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/DashboardCard entity-ids))++(defn dashboard-tab-ids-by-entity-ids+ "A map of entity id to id for the DashboardTabs whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/DashboardTab entity-ids))++(defn dimension-ids-by-entity-ids+ "A map of entity id to id for the Dimensions whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Dimension entity-ids))++(defn document-ids-by-entity-ids+ "A map of entity id to id for the Documents whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Document entity-ids))++(defn exploration-ids-by-entity-ids+ "A map of entity id to id for the Explorations whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Exploration entity-ids))++(defn measure-ids-by-entity-ids+ "A map of entity id to id for the Measures whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Measure entity-ids))++(defn permissions-group-ids-by-entity-ids+ "A map of entity id to id for the PermissionsGroups whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/PermissionsGroup entity-ids))++(defn pulse-ids-by-entity-ids+ "A map of entity id to id for the Pulses whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Pulse entity-ids))++(defn pulse-card-ids-by-entity-ids+ "A map of entity id to id for the PulseCards whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/PulseCard entity-ids))++(defn pulse-channel-ids-by-entity-ids+ "A map of entity id to id for the PulseChannels whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/PulseChannel entity-ids))++(defn segment-ids-by-entity-ids+ "A map of entity id to id for the Segments whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Segment entity-ids))++(defn native-query-snippet-ids-by-entity-ids+ "A map of entity id to id for the NativeQuerySnippets whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/NativeQuerySnippet entity-ids))++(defn timeline-ids-by-entity-ids+ "A map of entity id to id for the Timelines whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Timeline entity-ids))++(defn transform-ids-by-entity-ids+ "A map of entity id to id for the Transforms whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/Transform entity-ids))++(defn user-ids-by-entity-ids+ "A map of entity id to id for the Users whose entity id is in `entity-ids`."+ [entity-ids]+ (ids-by-entity-ids :model/User entity-ids))diff --git a/src/metabase/eid_translation/util.clj b/src/metabase/eid_translation/util.cljindex e5ad5ccad0b..566c1014a73 100644--- a/src/metabase/eid_translation/util.clj+++ b/src/metabase/eid_translation/util.clj@@ -3,6 +3,7 @@[malli.core :as mc][malli.error :as me][metabase.batch-processing.core :as grouper]+ [metabase.eid-translation.db :as eid-translation.db][metabase.eid-translation.impl :as eid-translation][metabase.eid-translation.settings :as eid-translation.settings][metabase.util :as u]@@ -106,7 +107,26 @@"Given a model and a sequence of entity ids on that model, return a pairs of entity-id, id."[api-name eids](let [model (->model api-name) ;; This lookup is safe because we've already validated the api-names- eid->id (into {} (t2/select-fn->fn :entity_id :id [model :id :entity_id] :entity_id [:in eids]))]+ eid->id (into {} (case model+ :model/Action (eid-translation.db/action-ids-by-entity-ids eids)+ :model/Card (eid-translation.db/card-ids-by-entity-ids eids)+ :model/Collection (eid-translation.db/collection-ids-by-entity-ids eids)+ :model/Dashboard (eid-translation.db/dashboard-ids-by-entity-ids eids)+ :model/DashboardCard (eid-translation.db/dashboard-card-ids-by-entity-ids eids)+ :model/DashboardTab (eid-translation.db/dashboard-tab-ids-by-entity-ids eids)+ :model/Dimension (eid-translation.db/dimension-ids-by-entity-ids eids)+ :model/Document (eid-translation.db/document-ids-by-entity-ids eids)+ :model/Exploration (eid-translation.db/exploration-ids-by-entity-ids eids)+ :model/Measure (eid-translation.db/measure-ids-by-entity-ids eids)+ :model/PermissionsGroup (eid-translation.db/permissions-group-ids-by-entity-ids eids)+ :model/Pulse (eid-translation.db/pulse-ids-by-entity-ids eids)+ :model/PulseCard (eid-translation.db/pulse-card-ids-by-entity-ids eids)+ :model/PulseChannel (eid-translation.db/pulse-channel-ids-by-entity-ids eids)+ :model/Segment (eid-translation.db/segment-ids-by-entity-ids eids)+ :model/NativeQuerySnippet (eid-translation.db/native-query-snippet-ids-by-entity-ids eids)+ :model/Timeline (eid-translation.db/timeline-ids-by-entity-ids eids)+ :model/Transform (eid-translation.db/transform-ids-by-entity-ids eids)+ :model/User (eid-translation.db/user-ids-by-entity-ids eids)))](mapv (fn entity-id-info [entity-id][entity-id (if-let [id (get eid->id entity-id)]{:id id :type api-name :status :ok}diff --git a/src/metabase/embedding/db.clj b/src/metabase/embedding/db.cljnew file mode 100644index 00000000000..f2956ab5931--- /dev/null+++ b/src/metabase/embedding/db.clj@@ -0,0 +1,15 @@+(ns metabase.embedding.db+ "Application database queries for the embedding module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn count-embedded-cards+ "Number of Cards that have embedding enabled."+ []+ (t2/count :model/Card :enable_embedding true))++(defn count-embedded-dashboards+ "Number of Dashboards that have embedding enabled."+ []+ (t2/count :model/Dashboard :enable_embedding true))diff --git a/src/metabase/embedding/settings.clj b/src/metabase/embedding/settings.cljindex 59f650377e2..0f6751c08ad 100644--- a/src/metabase/embedding/settings.clj+++ b/src/metabase/embedding/settings.clj@@ -3,6 +3,7 @@(:require[clojure.string :as str][metabase.analytics.core :as analytics]+ [metabase.embedding.db :as embedding.db][metabase.premium-features.core :as premium-features][metabase.server.settings :as server.settings][metabase.settings.core :as setting :refer [defsetting]]@@ -10,8 +11,7 @@[metabase.util.i18n :as i18n :refer [deferred-tru]][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.random :as u.random]- [toucan2.core :as t2]))+ [metabase.util.random :as u.random]))(defsetting embedding-secret-key(deferred-tru "Secret key used to sign JSON Web Tokens for requests to `/api/embed` endpoints.")@@ -69,8 +69,8 @@;; Don't track "localhost:*" as a meaningful origin since it was;; the old default and may still exist in migrated instances(and sdk-origins (not (str/blank? sdk-origins)) (not= "localhost:*" sdk-origins)))))- :number-embedded-questions (t2/count :model/Card :enable_embedding true)- :number-embedded-dashboards (t2/count :model/Dashboard :enable_embedding true)}))))))+ :number-embedded-questions (embedding.db/count-embedded-cards)+ :number-embedded-dashboards (embedding.db/count-embedded-dashboards)}))))))(defsetting ^:deprecated enable-embedding;; To be removed in 0.53.0diff --git a/src/metabase/embedding_rest/api/common.clj b/src/metabase/embedding_rest/api/common.cljindex 3d111b7bff9..4ce17f311b3 100644--- a/src/metabase/embedding_rest/api/common.clj+++ b/src/metabase/embedding_rest/api/common.clj@@ -7,6 +7,7 @@[metabase.dashboards.schema :as dashboards.schema][metabase.database-routing.core :as database-routing][metabase.eid-translation.core :as eid-translation]+ [metabase.embedding-rest.db :as embedding-rest.db][metabase.embedding.jwt :as embed][metabase.embedding.validation :as embedding.validation][metabase.lib.schema.parameter :as lib.schema.parameter]@@ -27,8 +28,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)@@ -311,15 +311,13 @@(eid-translation/->id :model/Card)))(defn card-for-unsigned-token- "Return the info needed for embedding about Card specified in `token`. Additional `constraints` can be passed to the- `public-card` function that fetches the Card."- [unsigned-token & {:keys [embedding-params constraints]}]- {:pre [((some-fn empty? sequential?) constraints) (even? (count constraints))]}+ "Return the info needed for embedding about Card specified in `token`."+ [unsigned-token & {:keys [embedding-params enable-embedding?]}](let [card-id (unsigned-token->card-id unsigned-token)token-params (embed/get-in-unsigned-token-or-throw unsigned-token [:params])resolved-embedding-params (or embedding-params- (t2/select-one-fn :embedding_params :model/Card :id card-id))]- (-> (apply api.public/public-card card-id constraints)+ (embedding-rest.db/card-embedding-params card-id))]+ (-> (api.public/public-card card-id :enable-embedding? enable-embedding?)api.public/combine-parameters-and-template-tags(remove-token-parameters token-params)(enabled-params resolved-embedding-params)@@ -424,15 +422,13 @@(eid-translation/->id :model/Dashboard)))(mu/defn dashboard-for-unsigned-token :- ::dashboards.schema/dashboard- "Return the info needed for embedding about Dashboard specified in `token`. Additional `constraints` can be passed to- the `public-dashboard` function that fetches the Dashboard."- [unsigned-token & {:keys [embedding-params constraints]}]- {:pre [((some-fn empty? sequential?) constraints) (even? (count constraints))]}+ "Return the info needed for embedding about Dashboard specified in `token`."+ [unsigned-token & {:keys [embedding-params enable-embedding?]}](let [dashboard-id (unsigned-token->dashboard-id unsigned-token)embedding-params (or embedding-params- (t2/select-one-fn :embedding_params :model/Dashboard, :id dashboard-id))+ (embedding-rest.db/dashboard-embedding-params dashboard-id))token-params (embed/get-in-unsigned-token-or-throw unsigned-token [:params])]- (-> (apply api.public/public-dashboard dashboard-id constraints)+ (-> (api.public/public-dashboard dashboard-id :enable-embedding? enable-embedding?)(substitute-token-parameters-in-text token-params)(remove-locked-parameters embedding-params)(remove-token-parameters token-params)@@ -584,7 +580,7 @@& {:keys [preview] :or {preview false}}](let [unsigned-token (embed/unsign token)dashboard-id (unsigned-token->dashboard-id unsigned-token)- dashboard (t2/select-one :model/Dashboard :id dashboard-id)+ dashboard (embedding-rest.db/dashboard dashboard-id)_ (when-not preview (check-embedding-enabled-for-dashboard dashboard))slug-token-params (embed/get-in-unsigned-token-or-throw unsigned-token [:params]){parameters :parameters@@ -639,7 +635,7 @@([token param-key value {:keys [preview] :or {preview false}}](let [unsigned-token (embed/unsign token)dashboard-id (unsigned-token->dashboard-id unsigned-token)- dashboard (t2/select-one :model/Dashboard :id dashboard-id)+ dashboard (embedding-rest.db/dashboard dashboard-id)_ (when-not preview (check-embedding-enabled-for-dashboard dashboard))slug-token-params (embed/get-in-unsigned-token-or-throw unsigned-token [:params])parameters (:parameters dashboard)diff --git a/src/metabase/embedding_rest/api/embed.clj b/src/metabase/embedding_rest/api/embed.cljindex e50cc2c82f8..f90d414eb44 100644--- a/src/metabase/embedding_rest/api/embed.clj+++ b/src/metabase/embedding_rest/api/embed.clj@@ -20,6 +20,7 @@[metabase.api.macros :as api.macros][metabase.eid-translation.core :as eid-translation][metabase.embedding-rest.api.common :as api.embed.common]+ [metabase.embedding-rest.db :as embedding-rest.db][metabase.embedding.jwt :as embedding.jwt][metabase.events.core :as events][metabase.parameters.schema :as parameters.schema]@@ -32,8 +33,7 @@[metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [ring.util.codec :as codec]- [toucan2.core :as t2]))+ [ring.util.codec :as codec]))(set! *warn-on-reflection* true)@@ -80,8 +80,8 @@[:token api.embed.common/EncodedToken]]](let [unsigned (unsign-and-translate-ids token)card-id (api.embed.common/unsigned-token->card-id unsigned)]- (api.embed.common/check-embedding-enabled-for-card (api/check-404 (t2/select-one [:model/Card :enable_embedding :archived] :id card-id)))- (api.embed.common/card-for-unsigned-token unsigned, :constraints [:enable_embedding true])))+ (api.embed.common/check-embedding-enabled-for-card (api/check-404 (embedding-rest.db/card-embedding-flags card-id)))+ (api.embed.common/card-for-unsigned-token unsigned :enable-embedding? true)))(defn ^:private run-query-for-unsigned-token-async"Run the query belonging to Card identified by `unsigned-token`. Checks that embedding is enabled both globally and@@ -91,7 +91,7 @@qp qp.card/process-query-for-card-default-qp}:as options}](let [card-id (api.embed.common/unsigned-token->card-id unsigned-token)- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-card card)(api.embed.common/process-query-for-card-with-params:export-format export-format@@ -164,8 +164,8 @@[:token api.embed.common/EncodedToken]]](let [unsigned (unsign-and-translate-ids token)dashboard-id (api.embed.common/unsigned-token->dashboard-id unsigned)]- (api.embed.common/check-embedding-enabled-for-dashboard (api/check-404 (t2/select-one [:model/Dashboard :enable_embedding :archived] :id dashboard-id)))- (u/prog1 (api.embed.common/dashboard-for-unsigned-token unsigned, :constraints [:enable_embedding true])+ (api.embed.common/check-embedding-enabled-for-dashboard (api/check-404 (embedding-rest.db/dashboard-embedding-flags dashboard-id)))+ (u/prog1 (api.embed.common/dashboard-for-unsigned-token unsigned :enable-embedding? true)(events/publish-event! :event/dashboard-read {:object-id (:id <>), :user-id api/*current-user-id*}))))(defn- process-query-for-dashcard-with-signed-token@@ -186,9 +186,9 @@qp qp.card/process-query-for-card-default-qp}}](let [unsigned-token (unsign-and-translate-ids token)dashboard-id (api.embed.common/unsigned-token->dashboard-id unsigned-token)- dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- card (api/check-404 (t2/select-one :model/Card card-id))]+ dashboard (api/check-404 (embedding-rest.db/dashboard dashboard-id))+ dashcard (api/check-404 (embedding-rest.db/dashcard dashcard-id))+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-dashboard dashboard)(api.embed.common/process-query-for-dashcard:export-format export-format@@ -312,7 +312,7 @@[:param-key ms/NonBlankString]]](let [unsigned (unsign-and-translate-ids token)card-id (api.embed.common/unsigned-token->card-id unsigned)- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-card card)(api.embed.common/card-param-values {:unsigned-token unsigned:card card@@ -327,7 +327,7 @@[{:keys [token param-key prefix]} :- api.embed.common/SearchParams](let [unsigned (unsign-and-translate-ids token)card-id (api.embed.common/unsigned-token->card-id unsigned)- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-card card)(api.embed.common/card-param-values {:unsigned-token unsigned:card card@@ -347,7 +347,7 @@[:value :string]]](let [unsigned (unsign-and-translate-ids token)card-id (api.embed.common/unsigned-token->card-id unsigned)- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-card card)(api.embed.common/card-param-remapped-value {:unsigned-token unsigned:card card@@ -407,7 +407,7 @@[:lonField ::api.tiles/legacy-ref]]](let [unsigned (unsign-and-translate-ids token)card-id (api.embed.common/unsigned-token->card-id unsigned)- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-card card)(request/as-admin(api.embed.common/process-tiles-query-for-card@@ -437,9 +437,9 @@[:lonField ::api.tiles/legacy-ref]]](let [unsigned (unsign-and-translate-ids token)dashboard-id (api.embed.common/unsigned-token->dashboard-id unsigned)- dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- card (api/check-404 (t2/select-one :model/Card card-id))]+ dashboard (api/check-404 (embedding-rest.db/dashboard dashboard-id))+ dashcard (api/check-404 (embedding-rest.db/dashcard dashcard-id))+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/check-embedding-enabled-for-dashboard dashboard)(api.embed.common/process-tiles-query-for-dashcarddashboard dashcard carddiff --git a/src/metabase/embedding_rest/api/preview_embed.clj b/src/metabase/embedding_rest/api/preview_embed.cljindex 16341e10866..5bb6b73bec6 100644--- a/src/metabase/embedding_rest/api/preview_embed.clj+++ b/src/metabase/embedding_rest/api/preview_embed.clj@@ -12,6 +12,7 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.embedding-rest.api.common :as api.embed.common]+ [metabase.embedding-rest.db :as embedding-rest.db][metabase.embedding.jwt :as embed][metabase.embedding.validation :as embedding.validation][metabase.parameters.schema :as parameters.schema]@@ -19,8 +20,7 @@[metabase.request.core :as request][metabase.tiles.api :as api.tiles][metabase.util.malli.schema :as ms]- [ring.util.codec :as codec]- [toucan2.core :as t2]))+ [ring.util.codec :as codec]))(defn- check-and-unsign [token](api/check-superuser)@@ -54,7 +54,7 @@query-params :- api.embed.common/QueryParams](let [unsigned-token (check-and-unsign token)card-id (embed/get-in-unsigned-token-or-throw unsigned-token [:resource :question])- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/process-query-for-card-with-params:export-format :api:card card@@ -70,7 +70,7 @@from the token, so a preview reflects the settings being edited rather than the published ones."[unsigned-token](let [card-id (api.embed.common/unsigned-token->card-id unsigned-token)]- (-> (api/check-404 (t2/select-one :model/Card card-id))+ (-> (api/check-404 (embedding-rest.db/card card-id))(assoc :embedding_params (embed/get-in-unsigned-token-or-throw unsigned-token [:_embedding_params])))))(api.macros/defendpoint :get "/card/:token/params/:param-key/values" :- ms/FieldValuesResult@@ -171,9 +171,9 @@query-params :- api.embed.common/QueryParams](let [unsigned-token (check-and-unsign token)dashboard-id (embed/get-in-unsigned-token-or-throw unsigned-token [:resource :dashboard])- dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- card (api/check-404 (t2/select-one :model/Card card-id))+ dashboard (api/check-404 (embedding-rest.db/dashboard dashboard-id))+ dashcard (api/check-404 (embedding-rest.db/dashcard dashcard-id))+ card (api/check-404 (embedding-rest.db/card card-id))embedding-params (embed/get-in-unsigned-token-or-throw unsigned-token [:_embedding_params])token-params (embed/get-in-unsigned-token-or-throw unsigned-token [:params])](api.embed.common/process-query-for-dashcard@@ -196,7 +196,7 @@query-params :- api.embed.common/QueryParams](let [unsigned-token (check-and-unsign token)card-id (embed/get-in-unsigned-token-or-throw unsigned-token [:resource :question])- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/process-query-for-card-with-params:export-format :api:card card@@ -218,9 +218,9 @@query-params :- api.embed.common/QueryParams](let [unsigned-token (check-and-unsign token)dashboard-id (embed/get-in-unsigned-token-or-throw unsigned-token [:resource :dashboard])- dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- card (api/check-404 (t2/select-one :model/Card card-id))+ dashboard (api/check-404 (embedding-rest.db/dashboard dashboard-id))+ dashcard (api/check-404 (embedding-rest.db/dashcard dashcard-id))+ card (api/check-404 (embedding-rest.db/card card-id))embedding-params (embed/get-in-unsigned-token-or-throw unsigned-token [:_embedding_params])token-params (embed/get-in-unsigned-token-or-throw unsigned-token [:params])](api.embed.common/process-query-for-dashcard@@ -252,7 +252,7 @@[:lonField ::api.tiles/legacy-ref]]](let [unsigned-token (check-and-unsign token)card-id (api.embed.common/unsigned-token->card-id unsigned-token)- card (api/check-404 (t2/select-one :model/Card card-id))]+ card (api/check-404 (embedding-rest.db/card card-id))](request/as-admin(api.embed.common/process-tiles-query-for-cardcard@@ -281,9 +281,9 @@[:lonField ::api.tiles/legacy-ref]]](let [unsigned-token (check-and-unsign token)dashboard-id (embed/get-in-unsigned-token-or-throw unsigned-token [:resource :dashboard])- dashboard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- card (api/check-404 (t2/select-one :model/Card card-id))]+ dashboard (api/check-404 (embedding-rest.db/dashboard dashboard-id))+ dashcard (api/check-404 (embedding-rest.db/dashcard dashcard-id))+ card (api/check-404 (embedding-rest.db/card card-id))](api.embed.common/process-tiles-query-for-dashcarddashboard dashcard card(api.embed.common/tile-parameters-for-dashboarddiff --git a/src/metabase/embedding_rest/api/theme.clj b/src/metabase/embedding_rest/api/theme.cljindex 9cbc825750d..f097c6766f6 100644--- a/src/metabase/embedding_rest/api/theme.clj+++ b/src/metabase/embedding_rest/api/theme.clj@@ -3,6 +3,7 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.embedding-rest.db :as embedding-rest.db][metabase.embedding.settings :as embedding.settings][metabase.util.i18n :refer [tru]][metabase.util.malli.registry :as mr]@@ -27,14 +28,13 @@[]; settings field is used for theme card previews.; we can optimize this by only selecting the preview colors needed.- (t2/select :model/EmbeddingTheme {:order-by [[:created_at :asc]]- :select [:id :entity_id :name :settings :created_at :updated_at]}))+ (embedding-rest.db/embedding-themes))(api.macros/defendpoint :get "/:id" :- ::EmbeddingTheme"Fetch a single embedding theme by ID."[{:keys [id]} :- [:map [:id ms/PositiveInt]]]- (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))- (t2/select-one :model/EmbeddingTheme :id id))+ (api/check-404 (embedding-rest.db/embedding-theme-exists? id))+ (embedding-rest.db/embedding-theme id))(api.macros/defendpoint :post "/" :- ::EmbeddingTheme"Create a new embedding theme."@@ -43,9 +43,8 @@{:keys [name settings]} :- [:map[:name ms/NonBlankString][:settings ms/Map]]]- (t2/insert-returning-instance! :model/EmbeddingTheme- {:name name- :settings settings}))+ (embedding-rest.db/insert-embedding-theme! {:name name+ :settings settings}))(api.macros/defendpoint :put "/:id" :- ::EmbeddingTheme"Update an embedding theme."@@ -54,28 +53,27 @@{:keys [name settings]} :- [:map[:name {:optional true} [:maybe ms/NonBlankString]][:settings {:optional true} [:maybe ms/Map]]]]- (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))- (t2/update! :model/EmbeddingTheme id- (cond-> {}- name (assoc :name name)- settings (assoc :settings settings)))- (t2/select-one :model/EmbeddingTheme :id id))+ (api/check-404 (embedding-rest.db/embedding-theme-exists? id))+ (embedding-rest.db/update-embedding-theme! id+ (cond-> {}+ name (assoc :name name)+ settings (assoc :settings settings)))+ (embedding-rest.db/embedding-theme id))(api.macros/defendpoint :delete "/:id" :- :nil"Delete an embedding theme."[{:keys [id]} :- [:map [:id ms/PositiveInt]]]- (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))- (t2/delete! :model/EmbeddingTheme :id id)+ (api/check-404 (embedding-rest.db/embedding-theme-exists? id))+ (embedding-rest.db/delete-embedding-theme! id)nil)(api.macros/defendpoint :post "/:id/copy" :- ::EmbeddingTheme"Copy an embedding theme."[{:keys [id]} :- [:map [:id ms/PositiveInt]]]- (api/check-404 (t2/exists? :model/EmbeddingTheme :id id))- (let [source-theme (t2/select-one :model/EmbeddingTheme :id id)]- (t2/insert-returning-instance! :model/EmbeddingTheme- {:name (tru "Copy of {0}" (:name source-theme))- :settings (:settings source-theme)})))+ (api/check-404 (embedding-rest.db/embedding-theme-exists? id))+ (let [source-theme (embedding-rest.db/embedding-theme id)]+ (embedding-rest.db/insert-embedding-theme! {:name (tru "Copy of {0}" (:name source-theme))+ :settings (:settings source-theme)})))(api.macros/defendpoint :post "/seed-defaults" :- :nil"Seed default embedding themes on first call, using the payloads built by the frontend from the@@ -92,6 +90,6 @@(locking seed-defaults-lock(t2/with-transaction [_conn](when-not (embedding.settings/default-embedding-themes-seeded)- (t2/insert! :model/EmbeddingTheme themes)+ (embedding-rest.db/insert-embedding-themes! themes)(embedding.settings/default-embedding-themes-seeded! true))))nil)diff --git a/src/metabase/embedding_rest/db.clj b/src/metabase/embedding_rest/db.cljnew file mode 100644index 00000000000..4daf1083054--- /dev/null+++ b/src/metabase/embedding_rest/db.clj@@ -0,0 +1,76 @@+(ns metabase.embedding-rest.db+ "Application database queries for the embedding REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card card-id))++(defn card-embedding-params+ "The embedding parameters of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :embedding_params :model/Card :id card-id))++(defn card-embedding-flags+ "The embedding-enabled and archived flags of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :enable_embedding :archived] :id card-id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard dashboard-id))++(defn dashboard-embedding-params+ "The embedding parameters of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one-fn :embedding_params :model/Dashboard, :id dashboard-id))++(defn dashboard-embedding-flags+ "The embedding-enabled and archived flags of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one [:model/Dashboard :enable_embedding :archived] :id dashboard-id))++(defn dashcard+ "The DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one :model/DashboardCard dashcard-id))++(defn embedding-themes+ "The id, entity id, name, settings, and timestamps of every EmbeddingTheme, oldest first."+ []+ (t2/select :model/EmbeddingTheme {:order-by [[:created_at :asc]]+ :select [:id :entity_id :name :settings :created_at :updated_at]}))++(defn embedding-theme-exists?+ "Whether an EmbeddingTheme with `id` exists."+ [id]+ (t2/exists? :model/EmbeddingTheme :id id))++(defn embedding-theme+ "The EmbeddingTheme with `id`, or nil."+ [id]+ (t2/select-one :model/EmbeddingTheme :id id))++(defn insert-embedding-theme!+ "Insert the EmbeddingTheme `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/EmbeddingTheme row))++(defn insert-embedding-themes!+ "Insert the EmbeddingTheme `rows`."+ [rows]+ (t2/insert! :model/EmbeddingTheme rows))++(defn update-embedding-theme!+ "Apply `changes` to the EmbeddingTheme with `id`."+ [id changes]+ (t2/update! :model/EmbeddingTheme id changes))++(defn delete-embedding-theme!+ "Delete the EmbeddingTheme with `id`."+ [id]+ (t2/delete! :model/EmbeddingTheme :id id))diff --git a/src/metabase/entity_retrieval/core.clj b/src/metabase/entity_retrieval/core.cljindex e99b51101d3..61299941ec2 100644--- a/src/metabase/entity_retrieval/core.clj+++ b/src/metabase/entity_retrieval/core.clj@@ -11,9 +11,9 @@the current user can read."(:require[clojure.string :as str]+ [metabase.entity-retrieval.db :as entity-retrieval.db][metabase.entity-retrieval.mirror]- [potemkin :as p]- [toucan2.core :as t2]))+ [potemkin :as p]))(comment metabase.entity-retrieval.mirror/keep-me)@@ -68,18 +68,13 @@ref's) differs from the type it was curated under (a card-flavor relabel)."[entity-refs](if-let [wanted (seq (into #{} (map (juxt :model :id)) entity-refs))]- ;; row-value IN isn't portable across our app DBs, so match the wanted (type, id) pairs with OR-of-ANDs.;; Normalize each ref's type to the stored key, so a card ref (metric/model) matches its `card` row.- (let [clause (into [:or]- (map (fn [[t id]]- [:and- [:= :entity_type (normalize-entity-type t)]- [:= :entity_local_id id]]))- wanted)- by-class (into {} (remove (comp str/blank? val))- (t2/select-fn->fn #(entity-class (:entity_type %) (:entity_local_id %))- (comp :instructions :ai_context)- :model/OsiAiContext {:where clause}))]+ (let [pairs (map (fn [[t id]] [(normalize-entity-type t) id]) wanted)+ by-class (into {}+ (comp (map (juxt #(entity-class (:entity_type %) (:entity_local_id %))+ (comp :instructions :ai_context)))+ (remove (comp str/blank? second)))+ (entity-retrieval.db/ai-contexts-for-entities pairs))];; key the result back by the caller's original [type id] ref(into {} (keep (fn [[t id]](when-let [instr (by-class (entity-class t id))]diff --git a/src/metabase/entity_retrieval/db.clj b/src/metabase/entity_retrieval/db.cljnew file mode 100644index 00000000000..3435a08db17--- /dev/null+++ b/src/metabase/entity_retrieval/db.clj@@ -0,0 +1,17 @@+(ns metabase.entity-retrieval.db+ "Application database queries for the entity retrieval module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn ai-contexts-for-entities+ "The OsiAiContext rows for the given `[entity-type entity-local-id]` pairs."+ [entity-type+ids]+ ;; row-value IN isn't portable across our app DBs, so match the wanted (type, id) pairs with OR-of-ANDs.+ (t2/select :model/OsiAiContext+ {:where (into [:or]+ (map (fn [[entity-type entity-local-id]]+ [:and+ [:= :entity_type entity-type]+ [:= :entity_local_id entity-local-id]]))+ entity-type+ids)}))diff --git a/src/metabase/explorations/api.clj b/src/metabase/explorations/api.cljindex ceb6d841d57..cc0e067e972 100644--- a/src/metabase/explorations/api.clj+++ b/src/metabase/explorations/api.clj@@ -6,12 +6,12 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]]- [metabase.app-db.core :as mdb][metabase.collections.models.collection :as collection][metabase.documents.core :as documents][metabase.events.core :as events][metabase.explorations.blocks :as explorations.blocks][metabase.explorations.core :as explorations]+ [metabase.explorations.db :as explorations.db][metabase.explorations.derived-perms :as derived-perms][metabase.explorations.models.exploration :as expl.model][metabase.explorations.models.exploration-block :as block]@@ -40,7 +40,7 @@;;; ----------------------------------------- helpers -----------------------------------------(defn- get-exploration-or-404 [id]- (api/check-404 (t2/select-one :model/Exploration :id id)))+ (api/check-404 (explorations.db/exploration id)))(defn- check-destination-collection-perms!"When `updates` moves the exploration to a different `collection_id`, verify the current@@ -63,9 +63,7 @@"Propagate an Exploration's new `collection_id` to its Summary document.Mirrors the dashboard-question cascade in `dashboards_rest/api.clj`."[exploration-id new-coll-id]- (t2/update! :model/Document- :exploration_id exploration-id- {:collection_id new-coll-id}))+ (explorations.db/move-summary-documents! exploration-id new-coll-id))(defn- cascade-archived-to-documents!"Propagate an Exploration's archive flip to its Summary document.@@ -75,28 +73,21 @@(user-archived) are never touched."[exploration-id new-archived?](if new-archived?- (t2/update! :model/Document- :exploration_id exploration-id- :archived false- {:archived true :archived_directly false})- (t2/update! :model/Document- :exploration_id exploration-id- :archived true- :archived_directly false- {:archived false})))+ (explorations.db/archive-summary-documents! exploration-id)+ (explorations.db/unarchive-summary-documents! exploration-id)))(defn- insert-summary-document!"Insert the auto-created Summary document for a newly created exploration. Explore-furthermust not call this — there is one Summary per exploration."[exploration-id coll-id]- (t2/insert! :model/Document- {:name summary-document-name- :document {:type "doc" :content []}- :content_type documents/prose-mirror-content-type- :creator_id api/*current-user-id*- :collection_id coll-id- :exploration_id exploration-id- :is_placeholder true}))+ (explorations.db/insert-document!+ {:name summary-document-name+ :document {:type "doc" :content []}+ :content_type documents/prose-mirror-content-type+ :creator_id api/*current-user-id*+ :collection_id coll-id+ :exploration_id exploration-id+ :is_placeholder true}))(defn- blocks-by-thread-id"The persisted blocks (`ExplorationBlock`) for `thread-ids`, in authoring order, grouped by@@ -104,9 +95,7 @@[thread-ids](when (seq thread-ids)(group-by :exploration_thread_id- (t2/select :model/ExplorationBlock- :exploration_thread_id [:in thread-ids]- {:order-by [[:position :asc] [:id :asc]]}))))+ (explorations.db/blocks-for-threads thread-ids))))(defn- attach-query-dimension-labels"Attach `:dimension_name` to each query on `thread`. Dimension snapshots come from the@@ -145,11 +134,10 @@block-ids (map :id all-blocks)pages-by-block (when (seq block-ids)(group-by :exploration_block_id- (t2/select :model/ExplorationPage- :exploration_block_id [:in block-ids])))+ (explorations.db/pages-for-blocks block-ids)))card-ids (distinct (mapcat #(map :card_id (:metrics %)) all-blocks))cards (when (seq card-ids)- (t2/select [:model/Card :id :name] :id [:in card-ids]))+ (explorations.db/card-names card-ids))card-name-by-id (into {} (map (juxt :id :name)) cards)](mapv (fn [thread](let [blocks (get blocks-by-thread (:id thread) [])@@ -232,8 +220,7 @@(defn- hydrate-exploration [exploration](-> exploration- (t2/hydrate :creator :can_write :collection :document- [:threads :queries :timelines])+ (t2/hydrate :creator :can_write :collection :document [:threads :queries :timelines])(update :threads#(some->> %(mapv (comp redact-thread-query-errors attach-thread-status))@@ -255,9 +242,8 @@in two blocks is stored on both."[thread-id blocks](when (seq blocks)- (t2/insert! :model/ExplorationBlock- (positional-rows thread-id- (map #(select-keys % [:metrics :dimensions]) blocks)))))+ (explorations.db/insert-blocks! (positional-rows thread-id+ (map #(select-keys % [:metrics :dimensions]) blocks)))))(defn- insert-thread-timelines!"Attach `timeline-ids` to the thread, in payload order. Deduped (`distinct`, keeping first@@ -265,9 +251,8 @@`(exploration_thread_id, timeline_id)` constraint and 500 the create."[thread-id timeline-ids](when (seq timeline-ids)- (t2/insert! :model/ExplorationThreadTimeline- (positional-rows thread-id- (map (fn [tl-id] {:timeline_id tl-id}) (distinct timeline-ids))))))+ (explorations.db/insert-thread-timelines! (positional-rows thread-id+ (map (fn [tl-id] {:timeline_id tl-id}) (distinct timeline-ids))))))(defn- reset-thread-for-rerun!"CAS-reset a *terminal* thread (`completed_at` set — natural completion, terminal failure, or@@ -280,23 +265,8 @@`completed_at IS NOT NULL` keeps a thread that is still working from being restarted under itself."[thread-id](t2/with-transaction [_conn]- (when (pos? (t2/query-one- {:update :exploration_thread- :set {:started_at (t/offset-date-time)- :query_plan_started_at nil- :query_plan_transcript nil- :analysis_started_at nil- :completed_at nil- :canceled_at nil}- :where [:and- [:= :id thread-id]- [:not= :completed_at nil]- [:not-exists ^:allow-subquery {:select [1]- :from [:exploration_query]- :where [:and- [:= :exploration_thread_id thread-id]- [:= :status "running"]]}]]}))- (t2/delete! :model/ExplorationQuery :exploration_thread_id thread-id)+ (when (pos? (explorations.db/reset-terminal-thread! thread-id (t/offset-date-time)))+ (explorations.db/delete-queries-for-thread! thread-id);; Enqueue planning inside the reset transaction so the plan message publishes iff the reset;; commits (:queue/exploration-plan is :transactional :require).(explorations.queues/start-thread! thread-id)@@ -650,27 +620,25 @@(api/read-check :model/Timeline timeline-id))(let [persisted(t2/with-transaction [_]- (let [exploration (first (t2/insert-returning-instances! :model/Exploration- {:name name- :description description- :collection_id collection_id- :creator_id api/*current-user-id*}))+ (let [exploration (explorations.db/insert-exploration! {:name name+ :description description+ :collection_id collection_id+ :creator_id api/*current-user-id*});; `started_at` marks the thread as started (past the draft phase). Planning itself;; is kicked off by the `start-thread!` enqueue below — its plan message rides a;; `:transactional :require` queue, so it publishes only once this whole transaction,;; including the dependent block/timeline rows below, commits atomically.;; The plan listener therefore can never observe (or plan) a half-built thread.- thread (first (t2/insert-returning-instances! :model/ExplorationThread- {:exploration_id (:id exploration)- :prompt prompt- :position 0- :started_at (t/offset-date-time)}))+ thread (explorations.db/insert-thread! {:exploration_id (:id exploration)+ :prompt prompt+ :position 0+ :started_at (t/offset-date-time)})tid (:id thread)](insert-blocks! tid blocks)(insert-thread-timelines! tid timeline_ids)(insert-summary-document! (:id exploration) collection_id)(explorations.queues/start-thread! tid)- (t2/select-one :model/Exploration :id (:id exploration))))]+ (explorations.db/exploration (:id exploration))))];; Published after the transaction commits (matching PUT) so listeners can never observe an;; exploration that isn't visible to other connections yet.(events/publish-event! :event/exploration-create@@ -708,18 +676,16 @@{:keys [page_id explore_filters]} :- ExploreFurther](let [exploration (get-exploration-or-404 id)](api/write-check exploration)- (let [page (api/check-404 (t2/select-one :model/ExplorationPage :id page_id))- block (api/check-404 (t2/select-one :model/ExplorationBlock- :id (:exploration_block_id page)))+ (let [page (api/check-404 (explorations.db/page page_id))+ block (api/check-404 (explorations.db/block (:exploration_block_id page)))src-thread-id (:exploration_thread_id block)- src-thread (t2/select-one :model/ExplorationThread :id src-thread-id)+ src-thread (explorations.db/thread src-thread-id);; The clicked page must live in *this* exploration — a page keys off a block off a;; thread off an exploration, and "Explore further" only ever drills a chart the caller;; is already viewing here. Reject anything else with a 404: without this check a caller;; could copy any page in the instance (metric selections, dimension snapshots, card ids,;; and the queries the planner then runs) into an exploration they can write (IDOR).- _ (api/check-404 (t2/exists? :model/ExplorationThread- :id src-thread-id :exploration_id id))+ _ (api/check-404 (explorations.db/thread-in-exploration? src-thread-id id))_ (api/check-403(contains? (derived-perms/thread-ids-with-visible-derived-data [src-thread-id])src-thread-id))@@ -727,7 +693,7 @@metric-selection (first metric-selections)cards (mapv (fn [{:keys [card_id]}](api/read-check- (api/check-404 (when card_id (t2/select-one :model/Card :id card_id)))))+ (api/check-404 (when card_id (explorations.db/card card_id)))))metric-selections)card (api/check-404 (first cards))card-name (:name card)@@ -738,36 +704,29 @@;; carries `:explore_filters`; `into` keeps that earlier segment scope and adds this one.metrics' (mapv #(update % :explore_filters (fnil into []) enriched-filters)(:metrics block))- timeline-ids (t2/select-fn-vec :timeline_id :model/ExplorationThreadTimeline- :exploration_thread_id src-thread-id- {:order-by [[:position :asc] [:id :asc]]})- next-position (inc (or (t2/select-one-fn :position :model/ExplorationThread- :exploration_id id- {:order-by [[:position :desc] [:id :desc]]})- 0))]+ timeline-ids (explorations.db/thread-timeline-ids src-thread-id)+ next-position (inc (or (explorations.db/last-thread-position id) 0))](t2/with-transaction [_]- (let [thread (first (t2/insert-returning-instances!- :model/ExplorationThread- {:exploration_id id- :name (explore-further-thread-name card-name- enriched-filters- top-level-follow-up?)- :data_access_token (drill-thread-token exploration cards)- :position next-position- ;; drill lineage — lets the sidebar nest this thread- ;; under the one owning the drilled page- :source_page_id page_id}))+ (let [thread (explorations.db/insert-thread!+ {:exploration_id id+ :name (explore-further-thread-name card-name+ enriched-filters+ top-level-follow-up?)+ :data_access_token (drill-thread-token exploration cards)+ :position next-position+ ;; drill lineage — lets the sidebar nest this thread+ ;; under the one owning the drilled page+ :source_page_id page_id})tid (:id thread)]- (t2/insert! :model/ExplorationBlock- {:exploration_thread_id tid- :metrics metrics'- :dimensions (stringify-dim-types (:dimensions block))- :position 0})+ (explorations.db/insert-blocks! {:exploration_thread_id tid+ :metrics metrics'+ :dimensions (stringify-dim-types (:dimensions block))+ :position 0})(insert-thread-timelines! tid timeline-ids);; Stamp `started_at` last — it's the signal the planning worker claims on.- (t2/update! :model/ExplorationThread tid {:started_at (t/offset-date-time)})+ (explorations.db/update-thread! tid {:started_at (t/offset-date-time)})(explorations.queues/start-thread! tid)- (let [persisted (t2/select-one :model/Exploration :id id)]+ (let [persisted (explorations.db/exploration id)](events/publish-event! :event/exploration-update{:object persisted :user-id api/*current-user-id*})(hydrate-exploration persisted)))))))@@ -784,72 +743,19 @@;; converts explicitly via [[explorations/exploration-data->api]].)(explorations/exploration-data {:q q}))-(defn- my-explorations-honeysql- "HoneySQL for the explorations `user-id` created or edited, ordered by that user's most-recent- touch (descending). \"Touch\" is the union of three streams, all attributed to the user:-- 1. the user's `Exploration` revisions (metadata / structure edits),- 2. the user's `Document` revisions for the exploration's Summary document- (mapped back via `document.exploration_id`),- 3. `exploration.created_at` for explorations the user created — creation is a touch, and- `created_at` stays reliable even after the creation revision ages out of the- `revision/max-revisions` cap.-- An exploration appears iff the user produced at least one touch, and `archived`/unreadable ones- are excluded — so the `COUNT(*) OVER ()` total matches what the caller sees.- `current_user_last_touched_at` is non-null on every row. `limit`/`offset` are appended only when- paged."- [user-id limit offset]- (let [my-touches ^:allow-subquery- {:union-all- [^:allow-subquery- {:select [[:model_id :eid] [:timestamp :ts]]- :from [:revision]- :where [:and [:= :model "Exploration"] [:= :user_id user-id]]}- ^:allow-subquery- {:select [[:d.exploration_id :eid] [:dr.timestamp :ts]]- :from [[:revision :dr]]- :join [[:document :d] [:= :d.id :dr.model_id]]- :where [:and- [:= :dr.model "Document"]- [:= :dr.user_id user-id]- [:not= :d.exploration_id nil]]}- ^:allow-subquery- {:select [[:id :eid] [:created_at :ts]]- :from [:exploration]- :where [:= :creator_id user-id]}]}- ;; MAX rather than GREATEST — the latter's NULL semantics differ across app DBs. And- ;; `my-touches` is a derived table here rather than a sibling CTE: a second `:with` binding- ;; that selects from the first silently returns no rows under our HoneySQL/H2 stack.- agg ^:allow-subquery- {:select [:eid [[:max :ts] :max_ts]]- :from [[my-touches :my_touches]]- :group-by [:eid]}]- (cond-> {:select [:exploration.*- [:agg.max_ts :current_user_last_touched_at]- [[:over [[:count :*] ^:allow-subquery {} :total_count]]]]- :from [:exploration]- :join [[agg :agg] [:= :agg.eid :exploration.id]]- :where [:and- [:= :exploration.archived false]- (collection/visible-collection-filter-clause :exploration.collection_id)]- :order-by [[:current_user_last_touched_at :desc] [:exploration.id :desc]]}- limit (assoc :limit limit)- offset (assoc :offset offset))))-;; Declared before `/:id` so the literal route wins — `"mine"` would otherwise fail the;; `:id` PositiveInt coercion rather than fall through here.(api.macros/defendpoint :get "/mine" :- ::MineResponse"Explorations the current user created or edited, most-recently-touched first, paginated.\"Touched\" composes the user's own edits to the exploration, to its Summary document, and its- creation — see [[my-explorations-honeysql]]. Explorations that were moved into a collection the- user can no longer read are excluded, as are archived ones. Returns the collection-items- envelope: `{:total :limit :offset :data}`."+ creation — see [[metabase.explorations.db/my-explorations]]. Explorations that were moved into a+ collection the user can no longer read are excluded, as are archived ones. Returns the+ collection-items envelope: `{:total :limit :offset :data}`."[](let [limit (request/limit)offset (request/offset)- rows (-> (t2/select :model/Exploration (my-explorations-honeysql api/*current-user-id* limit offset))+ rows (-> (explorations.db/my-explorations api/*current-user-id* limit offset)(t2/hydrate :creator :collection))]{:total (or (-> rows first :total_count) 0):limit limit@@ -881,12 +787,12 @@(check-destination-collection-perms! existing updates')(t2/with-transaction [_](when (seq updates')- (t2/update! :model/Exploration id updates')+ (explorations.db/update-exploration! id updates')(when (contains? updates' :collection_id)(cascade-collection-id-to-documents! id (:collection_id updates')))(when (contains? updates' :archived)(cascade-archived-to-documents! id (:archived updates')))))- (let [updated (t2/select-one :model/Exploration :id id)]+ (let [updated (explorations.db/exploration id)](when (seq updates')(events/publish-event! :event/exploration-update{:object updated :user-id api/*current-user-id*}))@@ -900,17 +806,17 @@[{:keys [id]} :- [:map [:id ms/PositiveInt]]](let [existing (get-exploration-or-404 id)](api/write-check existing)- (t2/delete! :model/Exploration :id id))+ (explorations.db/delete-exploration! id))nil)(defn- get-exploration-page-or-404[page-id]- (api/check-404 (t2/select-one :model/ExplorationPage :id page-id)))+ (api/check-404 (explorations.db/page page-id)))(defn- get-thread-or-404"Fetch the thread, or 404."[thread-id]- (api/check-404 (t2/select-one :model/ExplorationThread :id thread-id)))+ (api/check-404 (explorations.db/thread thread-id)))(defn- write-check-thread [thread-id](let [thread (get-thread-or-404 thread-id)]@@ -957,11 +863,7 @@(t2/with-transaction [_conn];; CAS gate on `completed_at IS NULL` makes both already-canceled and already-completed;; threads safe no-ops. When this UPDATE matches 0 rows, the thread is already terminal.- (t2/update! :model/ExplorationThread- :id thread-id- :completed_at nil- {:canceled_at now- :completed_at now})+ (explorations.db/cancel-thread! thread-id now);; Bulk-flip pending → canceled. SKIP LOCKED on Postgres/MySQL skips the row currently;; held by an in-flight QP worker so this API call doesn't block on QP duration; that row;; will commit as `done` (or `error`) naturally. H2 has only one worker (see worker-count@@ -971,26 +873,16 @@;; MySQL/MariaDB reject updating a table referenced by a subquery in the same statement;; (error 1093). The selected rows stay locked until the surrounding transaction commits,;; so the SKIP LOCKED semantics are preserved.- (let [pending-ids (map :id- (t2/query- (cond-> {:select [:id]- :from [:exploration_query]- :where [:and- [:= :exploration_thread_id thread-id]- [:= :status "pending"]]}- (not= :h2 (mdb/db-type)) (assoc :for [:update :skip-locked]))))]+ (let [pending-ids (explorations.db/lock-pending-query-ids-for-thread thread-id)](when (seq pending-ids)- (t2/query- {:update (t2/table-name :model/ExplorationQuery)- :set {:status "canceled"}- :where [:in :id pending-ids]})))))- (t2/select-one [:model/ExplorationThread :id :canceled_at :completed_at] :id thread-id))+ (explorations.db/cancel-queries! pending-ids)))))+ (explorations.db/thread-terminal-state thread-id))(defn- get-exploration-query-or-404"Fetch an `ExplorationQuery` by id and read-check it. The model's `can-read?` delegates upthrough `ExplorationThread` to the parent `Exploration`."[query-id]- (api/read-check (api/check-404 (t2/select-one :model/ExplorationQuery :id query-id))))+ (api/read-check (api/check-404 (explorations.db/query query-id))))(defn- stream-stored-result"Replay a worker-serialized QP result (gzipped+nippy bytes from `:model/StoredResult.result_data`)@@ -1042,7 +934,7 @@{:keys [starred]} :- [:map [:starred :boolean]]](let [page (get-exploration-page-or-404 id)](api/write-check page)- (t2/update! :model/ExplorationPage id {:starred starred}))+ (explorations.db/update-page! id {:starred starred}))nil)(api.macros/defendpoint :put "/pages/hidden" :- :nil@@ -1056,15 +948,13 @@(doseq [id page_ids](api/write-check (get-exploration-page-or-404 id)))(when (seq page_ids)- (t2/update! :model/ExplorationPage :id [:in page_ids] {:hidden hidden}))+ (explorations.db/update-pages! page_ids {:hidden hidden}))nil)(defn- summary-document-or-404"The non-archived Summary document for `exploration-id`, or 404."[exploration-id]- (api/check-404 (t2/select-one :model/Document- :exploration_id exploration-id- :archived false)))+ (api/check-404 (explorations.db/unarchived-summary-document exploration-id)))(defn- exploration-query-ids-belong-to-exploration?"True when every id in `eq-ids` refers to an `ExplorationQuery` whose thread belongs to@@ -1072,30 +962,19 @@[exploration-id eq-ids](let [distinct-ids (distinct eq-ids)](= (count distinct-ids)- (t2/count :model/ExplorationQuery- {:where [:and- [:in :id distinct-ids]- [:in :exploration_thread_id- ^:allow-subquery {:select [:id]- :from [:exploration_thread]- :where [:= :exploration_id exploration-id]}]]}))))+ (explorations.db/query-count-in-exploration exploration-id distinct-ids))))(defn- document-summary"Project a Document onto the `::ExplorationDocument` wire shape."[doc-id]- (t2/select-one [:model/Document- :id :name :exploration_id :creator_id :content_type- :created_at :updated_at :archived :is_placeholder]- :id doc-id))+ (explorations.db/summary-document-columns doc-id))(defn- page-explore-filters"Hydrated explore-further filters on the block that owns `page-id`, or nilwhen the page is unfiltered."[page-id]- (when-let [block-id (t2/select-one-fn :exploration_block_id- :model/ExplorationPage- :id page-id)]- (-> (t2/select-one-fn :metrics :model/ExplorationBlock :id block-id)+ (when-let [block-id (explorations.db/page-block-id page-id)]+ (-> (explorations.db/block-metrics block-id)first:explore_filtersnot-empty)))diff --git a/src/metabase/explorations/db.clj b/src/metabase/explorations/db.cljnew file mode 100644index 00000000000..180867b20b8--- /dev/null+++ b/src/metabase/explorations/db.clj@@ -0,0 +1,780 @@+(ns metabase.explorations.db+ "Application database queries for the explorations module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods,+ and transactions."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.collections.models.collection :as collection]+ [metabase.queries.core :as queries]+ [toucan2.core :as t2]))++;;; ----------------------------------------------- Exploration -----------------------------------------------++(defn exploration+ "The Exploration with `exploration-id`, or nil."+ [exploration-id]+ (t2/select-one :model/Exploration :id exploration-id))++(defn- my-explorations-query+ "The query for the Explorations `user-id` created or edited, ordered by that user's most-recent+ touch (descending). \"Touch\" is the union of three streams, all attributed to the user:++ 1. the user's `Exploration` revisions (metadata / structure edits),+ 2. the user's `Document` revisions for the exploration's Summary document+ (mapped back via `document.exploration_id`),+ 3. `exploration.created_at` for explorations the user created — creation is a touch, and+ `created_at` stays reliable even after the creation revision ages out of the+ `revision/max-revisions` cap.++ An exploration appears iff the user produced at least one touch, and `archived`/unreadable ones+ are excluded — so the `COUNT(*) OVER ()` total matches what the caller sees.+ `current_user_last_touched_at` is non-null on every row. `limit`/`offset` are appended only when+ paged."+ [user-id limit offset]+ (let [my-touches ^:allow-subquery+ {:union-all+ [^:allow-subquery+ {:select [[:model_id :eid] [:timestamp :ts]]+ :from [:revision]+ :where [:and [:= :model "Exploration"] [:= :user_id user-id]]}+ ^:allow-subquery+ {:select [[:d.exploration_id :eid] [:dr.timestamp :ts]]+ :from [[:revision :dr]]+ :join [[:document :d] [:= :d.id :dr.model_id]]+ :where [:and+ [:= :dr.model "Document"]+ [:= :dr.user_id user-id]+ [:not= :d.exploration_id nil]]}+ ^:allow-subquery+ {:select [[:id :eid] [:created_at :ts]]+ :from [:exploration]+ :where [:= :creator_id user-id]}]}+ ;; MAX rather than GREATEST — the latter's NULL semantics differ across app DBs. And+ ;; `my-touches` is a derived table here rather than a sibling CTE: a second `:with` binding+ ;; that selects from the first silently returns no rows under our HoneySQL/H2 stack.+ agg ^:allow-subquery+ {:select [:eid [[:max :ts] :max_ts]]+ :from [[my-touches :my_touches]]+ :group-by [:eid]}]+ (cond-> {:select [:exploration.*+ [:agg.max_ts :current_user_last_touched_at]+ [[:over [[:count :*] ^:allow-subquery {} :total_count]]]]+ :from [:exploration]+ :join [[agg :agg] [:= :agg.eid :exploration.id]]+ :where [:and+ [:= :exploration.archived false]+ (collection/visible-collection-filter-clause :exploration.collection_id)]+ :order-by [[:current_user_last_touched_at :desc] [:exploration.id :desc]]}+ limit (assoc :limit limit)+ offset (assoc :offset offset))))++(defn my-explorations+ "The Explorations `user-id` created or edited, most-recently-touched first, each carrying+ `:current_user_last_touched_at` and a `:total_count` window column; paginated by `limit`/`offset`."+ [user-id limit offset]+ (t2/select :model/Exploration (my-explorations-query user-id limit offset)))++(defn exploration-creator-id-for-thread+ "The creator of the Exploration owning the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-one-fn :creator_id :model/Exploration+ {:join [:exploration_thread [:= :exploration_thread.exploration_id :exploration.id]]+ :where [:= :exploration_thread.id thread-id]}))++(defn insert-exploration!+ "Insert `exploration` and return the new instance."+ [exploration]+ (first (t2/insert-returning-instances! :model/Exploration exploration)))++(defn update-exploration!+ "Apply `changes` to the Exploration with `exploration-id`."+ [exploration-id changes]+ (t2/update! :model/Exploration exploration-id changes))++(defn delete-exploration!+ "Delete the Exploration with `exploration-id`."+ [exploration-id]+ (t2/delete! :model/Exploration :id exploration-id))++;;; ------------------------------------------------- Threads -------------------------------------------------++(defn thread+ "The ExplorationThread with `thread-id`, or nil."+ [thread-id]+ (t2/select-one :model/ExplorationThread :id thread-id))++(defn thread-exploration-id-row+ "The `:exploration_id` row of the ExplorationThread with `thread-id`, or nil."+ [thread-id]+ (t2/select-one [:model/ExplorationThread :exploration_id] :id thread-id))++(defn thread-terminal-state+ "The ID, cancel time, and completion time of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-one [:model/ExplorationThread :id :canceled_at :completed_at] :id thread-id))++(defn thread-planning-state+ "The ID, cancel time, and analysis start time of the ExplorationThread with `thread-id`, or nil."+ [thread-id]+ (t2/select-one [:model/ExplorationThread :id :canceled_at :analysis_started_at] :id thread-id))++(defn thread-exploration-id+ "The Exploration ID of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-one-fn :exploration_id :model/ExplorationThread :id thread-id))++(defn thread-prompt+ "The prompt of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-one-fn :prompt :model/ExplorationThread :id thread-id))++(defn thread-transcript+ "The query-plan transcript of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-one-fn :query_plan_transcript :model/ExplorationThread :id thread-id))++(defn thread-in-exploration?+ "Whether the ExplorationThread with `thread-id` belongs to the Exploration with `exploration-id`."+ [thread-id exploration-id]+ (t2/exists? :model/ExplorationThread :id thread-id :exploration_id exploration-id))++(defn thread-canceled?+ "Whether the ExplorationThread with `thread-id` has been canceled."+ [thread-id]+ (t2/exists? :model/ExplorationThread :id thread-id :canceled_at [:not= nil]))++(defn threads-for-explorations+ "The ExplorationThreads of the Explorations with `exploration-ids`, in position order."+ [exploration-ids]+ (t2/select :model/ExplorationThread+ :exploration_id [:in exploration-ids]+ {:order-by [[:position :asc] [:id :asc]]}))++(defn thread-ids-for-exploration+ "The IDs of the ExplorationThreads of the Exploration with `exploration-id`."+ [exploration-id]+ (t2/select-pks-set :model/ExplorationThread :exploration_id exploration-id))++(defn lens-stamped-threads+ "The ID and data-access token of the ExplorationThreads among `thread-ids` that carry a token."+ [thread-ids]+ (t2/select [:model/ExplorationThread :id :data_access_token]+ :id [:in thread-ids]+ :data_access_token [:not= nil]))++(defn last-thread-position+ "The highest position among the ExplorationThreads of the Exploration with `exploration-id`."+ [exploration-id]+ (t2/select-one-fn :position :model/ExplorationThread+ :exploration_id exploration-id+ {:order-by [[:position :desc] [:id :desc]]}))++(defn lock-thread+ "The `:id` row of the ExplorationThread with `thread-id`, locked for update."+ [thread-id]+ (t2/query {:select [:id]+ :from [:exploration_thread]+ :where [:= :id thread-id]+ :for [:update]}))++(defn insert-thread!+ "Insert `thread` and return the new instance."+ [thread]+ (first (t2/insert-returning-instances! :model/ExplorationThread thread)))++(defn update-thread!+ "Apply `changes` to the ExplorationThread with `thread-id`."+ [thread-id changes]+ (t2/update! :model/ExplorationThread thread-id changes))++(defn cancel-thread!+ "Mark the uncompleted ExplorationThread with `thread-id` canceled and completed at `now`, returning the number of+ rows updated."+ [thread-id now]+ (t2/update! :model/ExplorationThread+ :id thread-id+ :completed_at nil+ {:canceled_at now+ :completed_at now}))++(defn reset-terminal-thread!+ "Reset the terminal ExplorationThread with `thread-id` to freshly started at `started-at`, if no query of it is+ still running. Returns the number of rows updated."+ [thread-id started-at]+ (t2/query-one {:update :exploration_thread+ :set {:started_at started-at+ :query_plan_started_at nil+ :query_plan_transcript nil+ :analysis_started_at nil+ :completed_at nil+ :canceled_at nil}+ :where [:and+ [:= :id thread-id]+ [:not= :completed_at nil]+ [:not-exists ^:allow-subquery {:select [1]+ :from [:exploration_query]+ :where [:and+ [:= :exploration_thread_id thread-id]+ [:= :status "running"]]}]]}))++(defn claim-thread-analysis!+ "Stamp the analysis start and completion of the ExplorationThread with `thread-id` at `now` if it has not been+ claimed, canceled, or left with pending queries. Returns the number of rows updated."+ [thread-id now]+ (t2/query-one {:update :exploration_thread+ :set {:analysis_started_at now+ :completed_at now}+ :where [:and+ [:= :id thread-id]+ [:= :analysis_started_at nil]+ [:= :canceled_at nil]+ [:not-exists ^:allow-subquery {:select [1]+ :from [:exploration_query]+ :where [:and+ [:= :exploration_thread_id thread-id]+ [:= :status "pending"]]}]]}))++;;; ------------------------------------------------- Blocks -------------------------------------------------++(defn block+ "The ExplorationBlock with `block-id`, or nil."+ [block-id]+ (t2/select-one :model/ExplorationBlock :id block-id))++(defn block-thread-id-row+ "The `:exploration_thread_id` row of the ExplorationBlock with `block-id`, or nil."+ [block-id]+ (t2/select-one [:model/ExplorationBlock :exploration_thread_id] :id block-id))++(defn block-metrics+ "The metric selections of the ExplorationBlock with `block-id`."+ [block-id]+ (t2/select-one-fn :metrics :model/ExplorationBlock :id block-id))++(defn block-for-page+ "The ExplorationBlock owning the ExplorationPage with `page-id`, or nil."+ [page-id]+ (t2/select-one :model/ExplorationBlock+ {:join [[:exploration_page :p] [:= :p.exploration_block_id :exploration_block.id]]+ :where [:= :p.id page-id]}))++(defn blocks-for-thread+ "The ExplorationBlocks of the ExplorationThread with `thread-id`, in position order."+ [thread-id]+ (t2/select :model/ExplorationBlock :exploration_thread_id thread-id {:order-by [[:position :asc] [:id :asc]]}))++(defn blocks-for-threads+ "The ExplorationBlocks of the ExplorationThreads with `thread-ids`, in position order."+ [thread-ids]+ (t2/select :model/ExplorationBlock+ :exploration_thread_id [:in thread-ids]+ {:order-by [[:position :asc] [:id :asc]]}))++(defn block-metrics-for-threads-newest-first+ "The thread ID and metric selections of the ExplorationBlocks of the ExplorationThreads with `thread-ids`, in+ reverse position order."+ [thread-ids]+ (t2/select [:model/ExplorationBlock :exploration_thread_id :metrics]+ :exploration_thread_id [:in thread-ids]+ {:order-by [[:position :desc] [:id :desc]]}))++(defn block-ids-for-thread+ "The IDs of the ExplorationBlocks of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-pks-vec :model/ExplorationBlock :exploration_thread_id thread-id))++(defn insert-blocks!+ "Insert one ExplorationBlock map or a sequence of them."+ [blocks]+ (t2/insert! :model/ExplorationBlock blocks))++;;; -------------------------------------------------- Pages --------------------------------------------------++(defn page+ "The ExplorationPage with `page-id`, or nil."+ [page-id]+ (t2/select-one :model/ExplorationPage :id page-id))++(defn page-block-id-row+ "The `:exploration_block_id` row of the ExplorationPage with `page-id`, or nil."+ [page-id]+ (t2/select-one [:model/ExplorationPage :exploration_block_id] :id page-id))++(defn page-block-id+ "The block ID of the ExplorationPage with `page-id`."+ [page-id]+ (t2/select-one-fn :exploration_block_id :model/ExplorationPage :id page-id))++(defn page-id-for-key+ "The ID of the ExplorationPage of the given block, Card, dimension, and query type, or nil."+ [block-id card-id dimension-id query-type]+ (t2/select-one-pk :model/ExplorationPage+ :exploration_block_id block-id+ :card_id card-id+ :dimension_id dimension-id+ :query_type query-type))++(defn pages-for-blocks+ "The ExplorationPages of the ExplorationBlocks with `block-ids`."+ [block-ids]+ (t2/select :model/ExplorationPage :exploration_block_id [:in block-ids]))++(defn page-ids-for-blocks+ "The IDs of the ExplorationPages of the ExplorationBlocks with `block-ids`."+ [block-ids]+ (t2/select-pks-vec :model/ExplorationPage :exploration_block_id [:in block-ids]))++(defn starred-page-ids+ "The IDs of the starred ExplorationPages among `page-ids`."+ [page-ids]+ (t2/select-pks-set :model/ExplorationPage :id [:in page-ids] :starred true))++(defn page-thread-ids+ "Rows of ExplorationPage `:id` and the `:thread_id` of its block, for the ExplorationThreads with `thread-ids`."+ [thread-ids]+ (t2/query {:select [[:p.id :id] [:b.exploration_thread_id :thread_id]]+ :from [[:exploration_page :p]]+ :join [[:exploration_block :b] [:= :b.id :p.exploration_block_id]]+ :where [:in :b.exploration_thread_id thread-ids]}))++(defn insert-page!+ "Insert `page` and return its ID."+ [page]+ (t2/insert-returning-pk! :model/ExplorationPage page))++(defn update-page!+ "Apply `changes` to the ExplorationPage with `page-id`."+ [page-id changes]+ (t2/update! :model/ExplorationPage page-id changes))++(defn update-pages!+ "Apply `changes` to the ExplorationPages with `page-ids`."+ [page-ids changes]+ (t2/update! :model/ExplorationPage :id [:in page-ids] changes))++(defn delete-pages!+ "Delete the ExplorationPages with `page-ids`."+ [page-ids]+ (t2/delete! :model/ExplorationPage :id [:in page-ids]))++;;; ------------------------------------------------- Queries -------------------------------------------------++(defn query+ "The ExplorationQuery with `query-id`, or nil."+ [query-id]+ (t2/select-one :model/ExplorationQuery :id query-id))++(defn query-thread-id-row+ "The `:exploration_thread_id` row of the ExplorationQuery with `query-id`, or nil."+ [query-id]+ (t2/select-one [:model/ExplorationQuery :exploration_thread_id] :id query-id))++(defn query-thread-id+ "The thread ID of the ExplorationQuery with `query-id`."+ [query-id]+ (t2/select-one-fn :exploration_thread_id :model/ExplorationQuery :id query-id))++(defn finished-query-thread-id+ "The thread ID of the ExplorationQuery with `query-id` if it has finished, or nil."+ [query-id]+ (t2/select-one-fn :exploration_thread_id :model/ExplorationQuery+ :id query-id :status [:in ["done" "error" "canceled"]]))++(defn runnable-query+ "The pending ExplorationQuery with `query-id` on an uncanceled thread, or nil."+ [query-id]+ (t2/select-one :model/ExplorationQuery+ {:select [:eq.*]+ :from [[:exploration_query :eq]]+ :join [[:exploration_thread :et] [:= :et.id :eq.exploration_thread_id]]+ :where [:and+ [:= :eq.id query-id]+ [:= :eq.status "pending"]+ [:= :et.canceled_at nil]]}))++(defn queries-for-threads+ "The ExplorationQueries of the ExplorationThreads with `thread-ids`, in position order."+ [thread-ids]+ (t2/select :model/ExplorationQuery+ :exploration_thread_id [:in thread-ids]+ {:order-by [[:position :asc] [:id :asc]]}))++(defn lens-stamped-queries+ "The ID, thread, Database, query, and data-access token of the ExplorationQueries with a query on the+ ExplorationThreads with `thread-ids`, in ID order."+ [thread-ids]+ (t2/select [:model/ExplorationQuery :id :exploration_thread_id :database_id :dataset_query :data_access_token]+ :exploration_thread_id [:in thread-ids]+ :dataset_query [:not= nil]+ {:order-by [[:id :asc]]}))++(defn thread-has-queries?+ "Whether the ExplorationThread with `thread-id` has any ExplorationQuery."+ [thread-id]+ (t2/exists? :model/ExplorationQuery :exploration_thread_id thread-id))++(defn query-count-in-exploration+ "The number of ExplorationQueries among `query-ids` belonging to the Exploration with `exploration-id`."+ [exploration-id query-ids]+ (t2/count :model/ExplorationQuery+ {:where [:and+ [:in :id query-ids]+ [:in :exploration_thread_id+ ^:allow-subquery {:select [:id]+ :from [:exploration_thread]+ :where [:= :exploration_id exploration-id]}]]}))++(defn pending-query-count+ "The number of pending ExplorationQueries."+ []+ (t2/count :model/ExplorationQuery :status "pending"))++(defn oldest-pending-query-created-at+ "The creation time of the oldest pending ExplorationQuery, or nil."+ []+ (t2/select-one-fn :created_at :model/ExplorationQuery+ {:where [:= :status "pending"]+ :order-by [[:created_at :asc]]+ :limit 1}))++(defn pending-query-ids-for-thread+ "The IDs of the pending ExplorationQueries of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/select-pks-vec :model/ExplorationQuery :exploration_thread_id thread-id :status "pending"))++(defn lock-pending-query-ids-for-thread+ "The ids of the pending ExplorationQueries of the ExplorationThread with `thread-id`, locked for+ update (`SKIP LOCKED` outside H2, whose single-worker model neither needs nor supports it)."+ [thread-id]+ (map :id (t2/query (cond-> {:select [:id]+ :from [:exploration_query]+ :where [:and+ [:= :exploration_thread_id thread-id]+ [:= :status "pending"]]}+ (not= :h2 (mdb/db-type)) (assoc :for [:update :skip-locked])))))++(defn page-ids-with-queries+ "The subset of `page-ids` that some ExplorationQuery points at."+ [page-ids]+ (t2/select-fn-set :page_id :model/ExplorationQuery :page_id [:in page-ids]))++(defn insert-queries!+ "Insert the ExplorationQuery `rows`."+ [rows]+ (t2/insert! :model/ExplorationQuery rows))++(defn update-query!+ "Apply `changes` to the ExplorationQuery with `query-id`."+ [query-id changes]+ (t2/update! :model/ExplorationQuery query-id changes))++(defn fail-pending-query!+ "Mark the pending ExplorationQuery with `query-id` as errored with `message` at `finished-at`, returning the number+ of rows updated."+ [query-id message finished-at]+ (t2/update! :model/ExplorationQuery+ {:id query-id, :status "pending"}+ {:status "error"+ :error_message message+ :finished_at finished-at}))++(defn cancel-pending-queries-for-thread!+ "Mark the pending ExplorationQueries of the ExplorationThread with `thread-id` canceled."+ [thread-id]+ (t2/update! :model/ExplorationQuery+ {:exploration_thread_id thread-id, :status "pending"}+ {:status "canceled"}))++(defn cancel-queries!+ "Mark the ExplorationQueries with `query-ids` canceled."+ [query-ids]+ (t2/query {:update (t2/table-name :model/ExplorationQuery)+ :set {:status "canceled"}+ :where [:in :id query-ids]}))++(defn delete-queries-for-thread!+ "Delete the ExplorationQueries of the ExplorationThread with `thread-id`."+ [thread-id]+ (t2/delete! :model/ExplorationQuery :exploration_thread_id thread-id))++;;; ---------------------------------------------- Query results ----------------------------------------------++(defn query-result+ "The ExplorationQueryResult of the ExplorationQuery with `query-id`, or nil."+ [query-id]+ (t2/select-one :model/ExplorationQueryResult :exploration_query_id query-id))++(defn query-result-stored-result-id+ "The stored result ID of the ExplorationQueryResult of the ExplorationQuery with `query-id`."+ [query-id]+ (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult :exploration_query_id query-id))++(defn query-result-exists?+ "Whether the ExplorationQuery with `query-id` has an ExplorationQueryResult."+ [query-id]+ (t2/exists? :model/ExplorationQueryResult :exploration_query_id query-id))++(defn query-result-scores+ "The query ID and `score-column` of the ExplorationQueryResults of the ExplorationQueries with `query-ids`."+ [score-column query-ids]+ (t2/select [:model/ExplorationQueryResult :exploration_query_id score-column]+ :exploration_query_id [:in query-ids]))++(defn query-result-row-counts+ "The query ID and stored row count of the ExplorationQueryResults of the ExplorationQueries with `query-ids`."+ [query-ids]+ (t2/select [:model/ExplorationQueryResult+ :exploration_query_result.exploration_query_id+ [:stored_result.row_count :row_count]]+ {:join [:stored_result [:= :stored_result.id :exploration_query_result.stored_result_id]]+ :where [:in :exploration_query_result.exploration_query_id query-ids]}))++(defn insert-query-result!+ "Insert `query-result`."+ [query-result]+ (t2/insert! :model/ExplorationQueryResult query-result))++;;; ---------------------------------------------- Stored results ----------------------------------------------++(defn stored-result+ "The StoredResult with `stored-result-id`, or nil."+ [stored-result-id]+ (t2/select-one :model/StoredResult :id stored-result-id))++(defn orphaned-stored-result-ids+ "Up to `limit` `:id` rows of the StoredResults created before `created-before` that no ExplorationQueryResult or+ Card embed reaches, in ID order."+ [created-before limit]+ (t2/query {:select [:sr.id]+ :from [[:stored_result :sr]]+ :where [:and+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[:exploration_query_result :eqr]]+ :where [:= :eqr.stored_result_id :sr.id]}]]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[:stored_result_use :sru]]+ :where [:and+ [:= :sru.stored_result_id :sr.id]+ [:not= :sru.card_id nil]]}]]+ [:< :sr.created_at created-before]]+ :order-by [[:sr.id :asc]]+ :limit limit}))++(defn insert-stored-result!+ "Insert `stored-result` and return its ID."+ [stored-result]+ (first (t2/insert-returning-pks! :model/StoredResult stored-result)))++(defn insert-stored-result-use!+ "Insert `stored-result-use`."+ [stored-result-use]+ (t2/insert! :model/StoredResultUse stored-result-use))++(defn delete-stored-results!+ "Delete the StoredResults with `stored-result-ids`, returning the number deleted."+ [stored-result-ids]+ (t2/delete! :model/StoredResult :id [:in stored-result-ids]))++;;; ------------------------------------------------ Timelines ------------------------------------------------++(defn timelines+ "The Timelines with `timeline-ids`."+ [timeline-ids]+ (t2/select :model/Timeline :id [:in timeline-ids]))++(defn thread-timelines-for-threads+ "The ExplorationThreadTimelines of the ExplorationThreads with `thread-ids`, in position order."+ [thread-ids]+ (t2/select :model/ExplorationThreadTimeline+ :exploration_thread_id [:in thread-ids]+ {:order-by [[:position :asc] [:id :asc]]}))++(defn thread-timeline-ids+ "The Timeline IDs selected on the ExplorationThread with `thread-id`, in position order."+ [thread-id]+ (t2/select-fn-vec :timeline_id :model/ExplorationThreadTimeline+ :exploration_thread_id thread-id+ {:order-by [[:position :asc] [:id :asc]]}))++(defn thread-timeline-names+ "The `:name` rows of the Timelines selected on the ExplorationThread with `thread-id`, in position order."+ [thread-id]+ (t2/query {:select [[:t.name :name]]+ :from [[:exploration_thread_timeline :ett]]+ :left-join [[:timeline :t] [:= :t.id :ett.timeline_id]]+ :where [:= :ett.exploration_thread_id thread-id]+ :order-by [[:ett.position :asc]]}))++(defn thread-timeline-event-rows+ "The Timelines selected on the ExplorationThread with `thread-id` joined to their unarchived events, ordered by+ position and event timestamp."+ [thread-id]+ (t2/query {:select [[:t.id :timeline_id]+ [:t.name :timeline_name]+ [:t.description :timeline_description]+ [:te.id :event_id]+ [:te.name :event_name]+ [:te.description :event_description]+ [:te.timestamp :event_timestamp]+ [:te.icon :event_icon]+ [:ett.position :position]]+ :from [[:exploration_thread_timeline :ett]]+ :join [[:timeline :t] [:= :t.id :ett.timeline_id]]+ :left-join [[:timeline_event :te] [:and+ [:= :te.timeline_id :t.id]+ [:= :te.archived false]]]+ :where [:= :ett.exploration_thread_id thread-id]+ :order-by [[:ett.position :asc] [:te.timestamp :asc]]}))++(defn insert-thread-timelines!+ "Insert the ExplorationThreadTimeline `rows`."+ [rows]+ (t2/insert! :model/ExplorationThreadTimeline rows))++;;; ------------------------------------------------ Documents ------------------------------------------------++(defn summary-document-columns+ "The wire-shape columns of the Document with `document-id`, or nil."+ [document-id]+ (t2/select-one [:model/Document+ :id :name :exploration_id :creator_id :content_type+ :created_at :updated_at :archived :is_placeholder]+ :id document-id))++(defn summary-documents-for-explorations+ "The wire-shape columns of the Summary Documents of the Explorations with `exploration-ids`, oldest first."+ [exploration-ids]+ (t2/select [:model/Document+ :id :name :exploration_id :creator_id :content_type+ :created_at :updated_at :archived :is_placeholder]+ :exploration_id [:in exploration-ids]+ {:order-by [[:created_at :asc] [:id :asc]]}))++(defn unarchived-summary-document+ "The unarchived Summary Document of the Exploration with `exploration-id`, or nil."+ [exploration-id]+ (t2/select-one :model/Document :exploration_id exploration-id :archived false))++(defn document-exploration-id+ "The Exploration ID of the Document with `document-id`."+ [document-id]+ (t2/select-one-fn :exploration_id :model/Document :id document-id))++(defn insert-document!+ "Insert `document`."+ [document]+ (t2/insert! :model/Document document))++(defn move-summary-documents!+ "Move the Summary Documents of the Exploration with `exploration-id` to the Collection with `collection-id`."+ [exploration-id collection-id]+ (t2/update! :model/Document :exploration_id exploration-id {:collection_id collection-id}))++(defn archive-summary-documents!+ "Archive the unarchived Summary Documents of the Exploration with `exploration-id` as not archived directly."+ [exploration-id]+ (t2/update! :model/Document+ :exploration_id exploration-id+ :archived false+ {:archived true, :archived_directly false}))++(defn unarchive-summary-documents!+ "Unarchive the Summary Documents of the Exploration with `exploration-id` that were archived with it."+ [exploration-id]+ (t2/update! :model/Document+ :exploration_id exploration-id+ :archived true+ :archived_directly false+ {:archived false}))++;;; ------------------------------------------------ Other models ------------------------------------------------++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn card-names+ "The ID and name of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :name] :id [:in card-ids]))++(defn card-description+ "The description of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :description :model/Card :id card-id))++(defn card-presentation+ "The name, description, display, and visualization settings of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :name :description :display :visualization_settings] :id card-id))++(defn card-queries+ "The ID, schema, Database, and query of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :card_schema :database_id :dataset_query] :id [:in card-ids]))++(defn metric-cards-by-id+ "A map of ID to the planner columns of the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn identity+ [:model/Card :id :name :description :database_id :dataset_query :card_schema :dimensions+ :dimension_mappings]+ :id [:in card-ids]))++(defn metric-card-ids+ "The `:id`s of the Cards visible to the current user as metrics, restricted to `metric-ids` when+ non-empty, with those in `library-collection-ids` sorted first and then alphabetically by name."+ [metric-ids library-collection-ids]+ (t2/select [:model/Card :id]+ {:where (cond-> (queries/visible-metric-cards-where-clause)+ (seq metric-ids) (as-> where [:and where [:in :id (vec metric-ids)]]))+ :order-by [[[:case+ [:in :collection_id (if (seq library-collection-ids) library-collection-ids [-1])] 0+ :else 1] :asc]+ [:name :asc]]}))++;;; Columns we actually need from `Card` for the two functions below. We deliberately avoid pulling the full row+;;; (which includes large blobs like `:result_metadata`, `:visualization_settings`, `:parameter_mappings`, etc.) so+;;; the response stays small and JSON encoding is fast.+(def ^:private exploration-card-columns+ [:id :name :description :collection_id :database_id :table_id :type :entity_id+ :card_schema :dataset_query :dimensions :dimension_mappings])++(defn metric-cards-for-explorations+ "The exploration-relevant columns of the metric Cards with `card-ids`."+ [card-ids]+ (t2/select (into [:model/Card] exploration-card-columns) :id [:in card-ids] :type "metric"))++(defn cards-for-explorations+ "The exploration-relevant columns of the Cards with `card-ids`."+ [card-ids]+ (t2/select (into [:model/Card] exploration-card-columns) :id [:in card-ids]))++(defn library-metrics-root-collection+ "The ID and location of the library metrics Collection of `type`, or nil."+ [type]+ (t2/select-one [:model/Collection :id :location] :type type))++(defn segment-names+ "A map of ID to name for the Segments with `segment-ids`."+ [segment-ids]+ (t2/select-pk->fn :name [:model/Segment :id :name] :id [:in segment-ids]))++(defn segment-name+ "The name of the Segment with `segment-id`."+ [segment-id]+ (t2/select-one-fn :name :model/Segment :id segment-id))++(defn user-summaries-by-id+ "A map of ID to the ID, email, and names of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))++(defn live-comment-targets+ "The child target IDs of the live exploration Comments anchored to one of `child-target-ids`."+ [child-target-ids]+ (t2/select-fn-set :child_target_id :model/Comment+ :target_type "exploration"+ :child_target_id [:in child-target-ids]+ :deleted_at nil))diff --git a/src/metabase/explorations/derived_perms.clj b/src/metabase/explorations/derived_perms.cljindex 1f89af1befc..d9d75df94f6 100644--- a/src/metabase/explorations/derived_perms.clj+++ b/src/metabase/explorations/derived_perms.clj@@ -20,11 +20,11 @@(:require[clojure.set :as set][metabase.api.common :as api]+ [metabase.explorations.db :as explorations.db][metabase.lib-be.core :as lib-be][metabase.queries.core :as queries][metabase.query-permissions.core :as query-perms]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(defn- visibility-key"The inputs [[metabase.queries.cached-result/viewer-can-view-cached-result?]] actually depends on,@@ -90,11 +90,7 @@check and the lens comparison, and throws without it. That is also the step that stamps the token,so a row that has one but no token is a write-path bug — adjudicated and denied, not skipped."[thread-ids]- (t2/select [:model/ExplorationQuery- :id :exploration_thread_id :database_id :dataset_query :data_access_token]- :exploration_thread_id [:in thread-ids]- :dataset_query [:not= nil]- {:order-by [[:id :asc]]}))+ (explorations.db/lens-stamped-queries thread-ids))(defn- lens-stamped-threads"The `exploration_thread` rows for `thread-ids` carrying a tracked lens, in the shape the gate takes.@@ -107,12 +103,8 @@stamped, and, unlike the thread's queries, not deleted by a restart. A thread whose Card cannot beresolved is still returned, marked [[::indeterminate]] so it denies."[thread-ids]- (when-let [threads (seq (t2/select [:model/ExplorationThread :id :data_access_token]- :id [:in thread-ids]- :data_access_token [:not= nil]))]- (let [blocks (t2/select [:model/ExplorationBlock :exploration_thread_id :metrics]- :exploration_thread_id [:in (map :id threads)]- {:order-by [[:position :desc] [:id :desc]]})+ (when-let [threads (seq (explorations.db/lens-stamped-threads thread-ids))]+ (let [blocks (explorations.db/block-metrics-for-threads-newest-first (map :id threads));; descending order + `into {}` (later pairs win) leaves the thread's *first* block;; standing, whose metric is the one the token was computed over.card-id (into {} (keep (fn [b]@@ -121,8 +113,7 @@blocks)cards (when (seq card-id);; `:card_schema` is mandatory in any explicit Card column list- (u/index-by :id (t2/select [:model/Card :id :card_schema :database_id :dataset_query]- :id [:in (distinct (vals card-id))])))]+ (u/index-by :id (explorations.db/card-queries (distinct (vals card-id)))))](map (fn [{thread-id :id :as thread}](let [card (get cards (get card-id thread-id))](cond-> {:id thread-id@@ -187,7 +178,7 @@[exploration-id](if (nil? exploration-id)true- (let [thread-ids (t2/select-pks-set :model/ExplorationThread :exploration_id exploration-id)]+ (let [thread-ids (explorations.db/thread-ids-for-exploration exploration-id)](or (empty? thread-ids)(= thread-ids (thread-ids-with-visible-derived-data thread-ids))))))@@ -203,7 +194,7 @@(:id document)(exploration-content-visible?- (t2/select-one-fn :exploration_id :model/Document :id (:id document)))+ (explorations.db/document-exploration-id (:id document))):elsefalse))@@ -222,7 +213,7 @@withheld. A comment anchored to a page of a thread the viewer can see keeps its context; anythingelse (a Summary block, an unanchored comment, or a page of a gated thread) loses it."[exploration-id comments]- (let [thread-ids (t2/select-pks-set :model/ExplorationThread :exploration_id exploration-id)]+ (let [thread-ids (explorations.db/thread-ids-for-exploration exploration-id)](if (or (empty? thread-ids) (not-any? :context comments))comments(let [visible (thread-ids-with-visible-derived-data thread-ids)]@@ -230,11 +221,7 @@comments(let [page->thread (into {}(map (juxt :id :thread_id))- (t2/query {:select [[:p.id :id] [:b.exploration_thread_id :thread_id]]- :from [[:exploration_page :p]]- :join [[:exploration_block :b]- [:= :b.id :p.exploration_block_id]]- :where [:in :b.exploration_thread_id (vec thread-ids)]}))]+ (explorations.db/page-thread-ids (vec thread-ids)))](mapv (fn [comment];; A non-numeric `child_target_id` is a Summary block uuid, and a nil one is;; unanchored; both parse to nil and so fall through to the deny branch.diff --git a/src/metabase/explorations/impl.clj b/src/metabase/explorations/impl.cljindex 1f837b6bc0d..0715d978c5d 100644--- a/src/metabase/explorations/impl.clj+++ b/src/metabase/explorations/impl.clj@@ -9,15 +9,14 @@(:require[clojure.string :as str][metabase.collections.models.collection :as collection]+ [metabase.explorations.db :as explorations.db][metabase.explorations.models.exploration-block :as block][metabase.lib-be.core :as lib-be][metabase.lib-metric.core :as lib-metric][metabase.lib.core :as lib][metabase.metrics.core :as metrics]- [metabase.queries.core :as queries][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -27,19 +26,11 @@a nil score (didn't score) are kept."0.1)-;;; Columns we actually need from `Card`. We deliberately avoid pulling the full row-;;; (which includes large blobs like `:result_metadata`, `:visualization_settings`,-;;; `:parameter_mappings`, etc.) so the response stays small and JSON encoding is fast.-(def ^:private metric-card-cols- [:id :name :description :collection_id :database_id :table_id :type :entity_id- :card_schema :dataset_query :dimensions :dimension_mappings])-(defn- library-metrics-collection-ids"Set of collection ids (the library-metrics root + descendants) whose metric Cards should be sortedto the top of the /dimensions response."[]- (when-let [root (t2/select-one [:model/Collection :id :location]- :type collection/library-metrics-collection-type)]+ (when-let [root (explorations.db/library-metrics-root-collection collection/library-metrics-collection-type)](conj (or (collection/descendant-ids root) #{}) (:id root))))(defn- metric-query@@ -109,17 +100,8 @@name. Optionally restricted to `metric-ids` (when non-nil), preserving access checks butfiltering to that subset."[metric-ids library-ids]- (let [base-where (queries/visible-metric-cards-where-clause)- where (if (seq metric-ids)- [:and base-where [:in :id (vec metric-ids)]]- base-where)]- (->> (t2/select [:model/Card :id]- {:where where- :order-by [[[:case- [:in :collection_id (or (seq library-ids) [-1])] 0- :else 1] :asc]- [:name :asc]]})- (mapv :id))))+ (->> (explorations.db/metric-card-ids metric-ids library-ids)+ (mapv :id)))(defn- load-metric-cards"Load the metric Card rows for `card-ids` in a single batched SELECT, returning them@@ -128,9 +110,7 @@visualization_settings, dataset_query, etc.) and dominates response size."[card-ids](when (seq card-ids)- (let [rows (t2/select (into [:model/Card] metric-card-cols)- :id [:in card-ids]- :type "metric")+ (let [rows (explorations.db/metric-cards-for-explorations card-ids)by-id (u/index-by :id rows)](into [] (keep by-id) card-ids))))@@ -154,8 +134,7 @@(metrics/sync-dimensions! :metadata/metric id)(catch Throwable e(log/warnf e "Failed to sync dimensions for metric card %d" id))))- (let [healed (u/index-by :id (t2/select (into [:model/Card] metric-card-cols)- :id [:in broken-ids]))]+ (let [healed (u/index-by :id (explorations.db/cards-for-explorations broken-ids))](mapv #(or (get healed (:id %)) %) cards))))))(defn- simple-table-query?diff --git a/src/metabase/explorations/models/exploration.clj b/src/metabase/explorations/models/exploration.cljindex ae5bc4ad896..476eaf3c042 100644--- a/src/metabase/explorations/models/exploration.clj+++ b/src/metabase/explorations/models/exploration.clj@@ -1,6 +1,7 @@(ns metabase.explorations.models.exploration(:require[clojure.string :as str]+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][metabase.search.spec :as search.spec][metabase.util.i18n :refer [deferred-tru]]@@ -33,8 +34,7 @@[_model k explorations](mi/instances-with-hydrated-dataexplorations k- #(t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id (keep :creator_id explorations))+ #(explorations.db/user-summaries-by-id (keep :creator_id explorations)):creator_id{:default {}}))@@ -43,9 +43,7 @@(mi/instances-with-hydrated-dataexplorations k#(group-by :exploration_id- (t2/select :model/ExplorationThread- :exploration_id [:in (map :id explorations)]- {:order-by [[:position :asc] [:id :asc]]}))+ (explorations.db/threads-for-explorations (map :id explorations))):id{:default []}))@@ -57,11 +55,7 @@#(into {}(map (fn [[eid docs]] [eid (first docs)]))(group-by :exploration_id- (t2/select [:model/Document- :id :name :exploration_id :creator_id :content_type- :created_at :updated_at :archived :is_placeholder]- :exploration_id [:in (map :id explorations)]- {:order-by [[:created_at :asc] [:id :asc]]})))+ (explorations.db/summary-documents-for-explorations (map :id explorations)))):id{:default nil}))diff --git a/src/metabase/explorations/models/exploration_block.clj b/src/metabase/explorations/models/exploration_block.cljindex b0a18a576c8..249700decdd 100644--- a/src/metabase/explorations/models/exploration_block.clj+++ b/src/metabase/explorations/models/exploration_block.clj@@ -9,6 +9,7 @@entries carry their `dimension_mappings`, `:dimensions` entries carry the dim typesnapshot — so a block is self-contained for both planning and per-row materialization."(:require+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -44,14 +45,14 @@([instance](mi/can-read? :model/ExplorationThread (:exploration_thread_id instance)))([_model pk]- (when-let [g (t2/select-one [:model/ExplorationBlock :exploration_thread_id] :id pk)]+ (when-let [g (explorations.db/block-thread-id-row pk)](mi/can-read? :model/ExplorationThread (:exploration_thread_id g)))))(defmethod mi/can-write? :model/ExplorationBlock([instance](mi/can-write? :model/ExplorationThread (:exploration_thread_id instance)))([_model pk]- (when-let [g (t2/select-one [:model/ExplorationBlock :exploration_thread_id] :id pk)]+ (when-let [g (explorations.db/block-thread-id-row pk)](mi/can-write? :model/ExplorationThread (:exploration_thread_id g)))))(defn dimension-labeldiff --git a/src/metabase/explorations/models/exploration_page.clj b/src/metabase/explorations/models/exploration_page.cljindex aa9e278255c..286f1032efd 100644--- a/src/metabase/explorations/models/exploration_page.clj+++ b/src/metabase/explorations/models/exploration_page.clj@@ -2,6 +2,7 @@"A page within a block: the bundle of queries that appear together on one page(currently, those that share a card, dimension, and query_type)."(:require+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -17,12 +18,12 @@([instance](mi/can-read? :model/ExplorationBlock (:exploration_block_id instance)))([_model pk]- (when-let [p (t2/select-one [:model/ExplorationPage :exploration_block_id] :id pk)]+ (when-let [p (explorations.db/page-block-id-row pk)](mi/can-read? :model/ExplorationBlock (:exploration_block_id p)))))(defmethod mi/can-write? :model/ExplorationPage([instance](mi/can-write? :model/ExplorationBlock (:exploration_block_id instance)))([_model pk]- (when-let [p (t2/select-one [:model/ExplorationPage :exploration_block_id] :id pk)]+ (when-let [p (explorations.db/page-block-id-row pk)](mi/can-write? :model/ExplorationBlock (:exploration_block_id p)))))diff --git a/src/metabase/explorations/models/exploration_query.clj b/src/metabase/explorations/models/exploration_query.cljindex 25e4bd6acb1..3007ccbcf5c 100644--- a/src/metabase/explorations/models/exploration_query.clj+++ b/src/metabase/explorations/models/exploration_query.clj@@ -1,5 +1,6 @@(ns metabase.explorations.models.exploration-query(:require+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.util :as u]@@ -23,22 +24,21 @@([instance](mi/can-read? :model/ExplorationThread (:exploration_thread_id instance)))([_model pk]- (when-let [q (t2/select-one [:model/ExplorationQuery :exploration_thread_id] :id pk)]+ (when-let [q (explorations.db/query-thread-id-row pk)](mi/can-read? :model/ExplorationThread (:exploration_thread_id q)))))(defmethod mi/can-write? :model/ExplorationQuery([instance](mi/can-write? :model/ExplorationThread (:exploration_thread_id instance)))([_model pk]- (when-let [q (t2/select-one [:model/ExplorationQuery :exploration_thread_id] :id pk)]+ (when-let [q (explorations.db/query-thread-id-row pk)](mi/can-write? :model/ExplorationThread (:exploration_thread_id q)))))(defn- hydrate-score-from-result [score-key queries](mi/instances-with-hydrated-dataqueries score-key#(u/index-by :exploration_query_id score-key- (t2/select [:model/ExplorationQueryResult :exploration_query_id score-key]- :exploration_query_id [:in (map :id queries)]))+ (explorations.db/query-result-scores score-key (map :id queries))):id))(methodical/defmethod t2/batched-hydrate [:model/ExplorationQuery :interestingness_score]@@ -54,13 +54,7 @@(mi/instances-with-hydrated-dataqueries k#(u/index-by :exploration_query_id :row_count- (t2/select [:model/ExplorationQueryResult- :exploration_query_result.exploration_query_id- [:stored_result.row_count :row_count]]- {:join [:stored_result- [:= :stored_result.id :exploration_query_result.stored_result_id]]- :where [:in :exploration_query_result.exploration_query_id- (map :id queries)]}))+ (explorations.db/query-result-row-counts (map :id queries))):id))(methodical/defmethod t2/batched-hydrate [:model/ExplorationQuery :segment_name]@@ -69,5 +63,5 @@queries k#(let [seg-ids (into #{} (keep :segment_id) queries)](when (seq seg-ids)- (t2/select-pk->fn :name [:model/Segment :id :name] :id [:in seg-ids])))+ (explorations.db/segment-names seg-ids))):segment_id))diff --git a/src/metabase/explorations/models/exploration_query_result.clj b/src/metabase/explorations/models/exploration_query_result.cljindex a16ff00a1fd..b87c35e9e10 100644--- a/src/metabase/explorations/models/exploration_query_result.clj+++ b/src/metabase/explorations/models/exploration_query_result.clj@@ -3,6 +3,7 @@[clojure.edn :as edn][metabase.api.common :as api][metabase.explorations.composite :as composite]+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][metabase.queries.core :as queries][metabase.query-permissions.core :as query-perms]@@ -66,9 +67,8 @@full stored_result row (creator/db/blob/query) or nil when no result row exists yet (querystill pending/errored)."[eq-id]- (when-let [sr-id (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult- :exploration_query_id eq-id)]- (t2/select-one :model/StoredResult :id sr-id)))+ (when-let [sr-id (explorations.db/query-result-stored-result-id eq-id)]+ (explorations.db/stored-result sr-id)))(defn- deserialize-stored-result"Inverse of [[qp/do-with-serialization]] for a stored_result's@@ -98,11 +98,9 @@[eq-ids](mapv(fn [eq-id]- (let [eq (api/check-404 (t2/hydrate (t2/select-one :model/ExplorationQuery :id eq-id)- :segment_name))- eqr (api/check-404 (t2/select-one :model/ExplorationQueryResult- :exploration_query_id eq-id))- sr (api/check-404 (t2/select-one :model/StoredResult :id (:stored_result_id eqr)))+ (let [eq (api/check-404 (t2/hydrate (explorations.db/query eq-id) :segment_name))+ eqr (api/check-404 (explorations.db/query-result eq-id))+ sr (api/check-404 (explorations.db/stored-result (:stored_result_id eqr)))qp-result (api/check-404 (deserialize-stored-result (:result_data sr)))]{:eq eq :eqr eqr :sr sr :qp-result qp-result}))eq-ids))@@ -162,8 +160,7 @@first-eq (:eq (first eq-results))first-sr (:sr (first eq-results))src-card (when-let [card-id (:card_id first-eq)]- (t2/select-one [:model/Card :name :description :display :visualization_settings]- :id card-id))+ (explorations.db/card-presentation card-id))composite-qp (composite/combine eq-results (or visualization-settings {}))dataset-query (:dataset_query first-eq)creator-id (:id creator)]@@ -179,19 +176,18 @@(t2/with-transaction [_conn](let [stored-result-id (if single?(:id first-sr)- (first (t2/insert-returning-pks!- :model/StoredResult- {:result_data composite-bytes- :creator_id creator-id- :database_id (or (:database_id first-sr)- (-> dataset-query :database))- :dataset_query dataset-query- ;; `composite/combine` refreshed :row_count to the- ;; combined row set's size.- :row_count (:row_count composite-qp)- ;; Without this the read gate denies the composite to- ;; every non-superuser. See [[composite-data-access-token]].- :data_access_token (composite-data-access-token eq-results)})))+ (explorations.db/insert-stored-result!+ {:result_data composite-bytes+ :creator_id creator-id+ :database_id (or (:database_id first-sr)+ (-> dataset-query :database))+ :dataset_query dataset-query+ ;; `composite/combine` refreshed :row_count to the+ ;; combined row set's size.+ :row_count (:row_count composite-qp)+ ;; Without this the read gate denies the composite to+ ;; every non-superuser. See [[composite-data-access-token]].+ :data_access_token (composite-data-access-token eq-results)}))card-id (:id (queries/create-card!{:name (or (not-empty (:name first-eq))(not-empty (:name src-card))@@ -208,8 +204,8 @@;; Record the (card -> stored_result) refs for lifecycle/GC tracking. For a combine we;; reference the new composite snapshot plus every source, so a delete of any source;; cascades; for a single-query embed the snapshot *is* the source, so one row covers it.- (t2/insert! :model/StoredResultUse {:stored_result_id stored-result-id :card_id card-id})+ (explorations.db/insert-stored-result-use! {:stored_result_id stored-result-id :card_id card-id})(when-not single?(doseq [{:keys [sr]} eq-results]- (t2/insert! :model/StoredResultUse {:stored_result_id (:id sr) :card_id card-id})))+ (explorations.db/insert-stored-result-use! {:stored_result_id (:id sr) :card_id card-id}))){:card-id card-id :stored-result-id stored-result-id :primary-eq first-eq})))))diff --git a/src/metabase/explorations/models/exploration_thread.clj b/src/metabase/explorations/models/exploration_thread.cljindex f64ac0df7af..b21050f6111 100644--- a/src/metabase/explorations/models/exploration_thread.clj+++ b/src/metabase/explorations/models/exploration_thread.clj@@ -1,6 +1,7 @@(ns metabase.explorations.models.exploration-thread(:require[clojure.edn :as edn]+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.util.log :as log]@@ -44,14 +45,14 @@([instance](mi/can-read? :model/Exploration (:exploration_id instance)))([_model pk]- (when-let [thread (t2/select-one [:model/ExplorationThread :exploration_id] :id pk)]+ (when-let [thread (explorations.db/thread-exploration-id-row pk)](mi/can-read? :model/Exploration (:exploration_id thread)))))(defmethod mi/can-write? :model/ExplorationThread([instance](mi/can-write? :model/Exploration (:exploration_id instance)))([_model pk]- (when-let [thread (t2/select-one [:model/ExplorationThread :exploration_id] :id pk)]+ (when-let [thread (explorations.db/thread-exploration-id-row pk)](mi/can-write? :model/Exploration (:exploration_id thread)))))(methodical/defmethod t2/batched-hydrate [:model/ExplorationThread :timelines]@@ -59,11 +60,7 @@(mi/instances-with-hydrated-datathreads k#(group-by :exploration_thread_id- (t2/hydrate- (t2/select :model/ExplorationThreadTimeline- :exploration_thread_id [:in (map :id threads)]- {:order-by [[:position :asc] [:id :asc]]})- :timeline))+ (t2/hydrate (explorations.db/thread-timelines-for-threads (map :id threads)) :timeline)):id{:default []}))@@ -72,13 +69,6 @@(mi/instances-with-hydrated-datathreads k#(group-by :exploration_thread_id- (t2/hydrate- (t2/select :model/ExplorationQuery- :exploration_thread_id [:in (map :id threads)]- {:order-by [[:position :asc] [:id :asc]]})- :interestingness_score- :contextual_interestingness_score- :row_count- :segment_name))+ (t2/hydrate (explorations.db/queries-for-threads (map :id threads)) :interestingness_score :contextual_interestingness_score :row_count :segment_name)):id{:default []}))diff --git a/src/metabase/explorations/models/exploration_thread_timeline.clj b/src/metabase/explorations/models/exploration_thread_timeline.cljindex 308b1674b3e..e727a04a441 100644--- a/src/metabase/explorations/models/exploration_thread_timeline.clj+++ b/src/metabase/explorations/models/exploration_thread_timeline.clj@@ -1,5 +1,6 @@(ns metabase.explorations.models.exploration-thread-timeline(:require+ [metabase.explorations.db :as explorations.db][metabase.models.interface :as mi][metabase.timeline.core :as timeline][metabase.util.date-2 :as u.date]@@ -24,7 +25,7 @@timelines (when (seq timeline-ids)(timeline/include-events(filterv mi/can-read?- (t2/select :model/Timeline :id [:in timeline-ids]))+ (explorations.db/timelines timeline-ids)){:events/all? false}))](into {} (map (juxt :id identity)) timelines)):timeline_id))@@ -32,12 +33,7 @@(defn selected-names"Names of the timelines selected on `thread-id`, in position order."[thread-id]- (->> (t2/query- {:select [[:t.name :name]]- :from [[:exploration_thread_timeline :ett]]- :left-join [[:timeline :t] [:= :t.id :ett.timeline_id]]- :where [:= :ett.exploration_thread_id thread-id]- :order-by [[:ett.position :asc]]})+ (->> (explorations.db/thread-timeline-names thread-id)(keep :name)))(defn load-timeline-events@@ -48,23 +44,7 @@`{:timeline-id :timeline-name :timeline-description :events [...]}` maps, events sorted bytimestamp ascending."[thread-id]- (let [rows (t2/query- {:select [[:t.id :timeline_id]- [:t.name :timeline_name]- [:t.description :timeline_description]- [:te.id :event_id]- [:te.name :event_name]- [:te.description :event_description]- [:te.timestamp :event_timestamp]- [:te.icon :event_icon]- [:ett.position :position]]- :from [[:exploration_thread_timeline :ett]]- :join [[:timeline :t] [:= :t.id :ett.timeline_id]]- :left-join [[:timeline_event :te] [:and- [:= :te.timeline_id :t.id]- [:= :te.archived false]]]- :where [:= :ett.exploration_thread_id thread-id]- :order-by [[:ett.position :asc] [:te.timestamp :asc]]})]+ (let [rows (explorations.db/thread-timeline-event-rows thread-id)](->> rows(group-by :timeline_id)(sort-by (fn [[_ rs]] (:position (first rs))))diff --git a/src/metabase/explorations/query_plan.clj b/src/metabase/explorations/query_plan.cljindex 615d9a2fc15..17515dfc813 100644--- a/src/metabase/explorations/query_plan.clj+++ b/src/metabase/explorations/query_plan.clj@@ -14,6 +14,7 @@instance, and teaching `pick-planner!` to dispatch to it."(:require[clojure.set :as set]+ [metabase.explorations.db :as explorations.db][metabase.explorations.models.exploration-block :as block][metabase.explorations.query-plan.context :as qp.context][metabase.explorations.query-plan.mechanical :as qp.mechanical]@@ -94,17 +95,12 @@MySQL can't uniquely index): two planners in here at once would both miss and both insert. Safeonly because [[lock-thread-for-planning!]] keeps them out — see there."[[block-id card-id dim-id query-type] position]- (or (t2/select-one-pk :model/ExplorationPage- :exploration_block_id block-id- :card_id card-id- :dimension_id dim-id- :query_type query-type)- (t2/insert-returning-pk! :model/ExplorationPage- {:exploration_block_id block-id- :card_id card-id- :dimension_id dim-id- :query_type query-type- :position position})))+ (or (explorations.db/page-id-for-key block-id card-id dim-id query-type)+ (explorations.db/insert-page! {:exploration_block_id block-id+ :card_id card-id+ :dimension_id dim-id+ :query_type query-type+ :position position})))(defn- reconcile-pages!"Find-or-create a page per distinct [[page-key]] in `rows` (first-seen order within a@@ -124,10 +120,7 @@[page-ids](if (seq page-ids)(let [by-str (into {} (map (juxt str identity)) page-ids)]- (->> (t2/select-fn-set :child_target_id :model/Comment- :target_type "exploration"- :child_target_id [:in (keys by-str)]- :deleted_at nil)+ (->> (explorations.db/live-comment-targets (keys by-str))(into #{} (keep by-str))))#{}))@@ -137,7 +130,7 @@[page-ids](if (seq page-ids);; `(set ...)` since t2 set selectors return nil, not #{}, when nothing matches- (set (t2/select-pks-set :model/ExplorationPage :id [:in page-ids] :starred true))+ (set (explorations.db/starred-page-ids page-ids))#{}))(defn- pages-with-queries@@ -147,7 +140,7 @@wiped first."[page-ids](if (seq page-ids)- (set (t2/select-fn-set :page_id :model/ExplorationQuery :page_id [:in page-ids]))+ (set (explorations.db/page-ids-with-queries page-ids))#{}))(defn- gc-orphan-pages!@@ -157,16 +150,16 @@selection but still user-valued), or when a query still points at it (deleting wouldcascade to the query)."[thread-id used-page-ids]- (let [block-ids (t2/select-pks-vec :model/ExplorationBlock :exploration_thread_id thread-id)+ (let [block-ids (explorations.db/block-ids-for-thread thread-id)orphans (when (seq block-ids)- (->> (t2/select-pks-vec :model/ExplorationPage :exploration_block_id [:in block-ids])+ (->> (explorations.db/page-ids-for-blocks block-ids)(remove (set used-page-ids))))retained (set/union (pages-with-comments orphans)(starred-pages orphans)(pages-with-queries orphans))deletable (remove retained orphans)](when (seq deletable)- (t2/delete! :model/ExplorationPage :id [:in deletable]))))+ (explorations.db/delete-pages! deletable))))(defn- lock-thread-for-planning!"Take a row lock on `thread-id`'s `exploration_thread` row (call inside a transaction) so at most@@ -180,10 +173,7 @@has no unique index to fall back on, so two planners would each create the thread's pages — and apage's id is its identity, so the duplicate strands every comment and star anchored to the loser."[thread-id]- (t2/query {:select [:id]- :from [:exploration_thread]- :where [:= :id thread-id]- :for [:update]}))+ (explorations.db/lock-thread thread-id))(defn- insert-plan-rows!"Materialize each plan item into row recipes, reconcile each to its persisted@@ -225,7 +215,7 @@:no-rows(t2/with-transaction [_conn](lock-thread-for-planning! thread-id)- (if (t2/exists? :model/ExplorationQuery :exploration_thread_id thread-id)+ (if (explorations.db/thread-has-queries? thread-id)(do(log/infof "Thread %d was planned by a concurrent delivery; discarding this planner's %d row(s)"thread-id (count rows))@@ -237,8 +227,7 @@(assoc :page_id (key->page (page-key %)))(dissoc :block_id))rows)]- (t2/insert! :model/ExplorationQuery- (map-indexed (fn [i r] (assoc r :position i)) rows*))+ (explorations.db/insert-queries! (map-indexed (fn [i r] (assoc r :position i)) rows*))(gc-orphan-pages! thread-id (vals key->page))(count rows*)))))))@@ -252,9 +241,8 @@doesn't deadlock."[thread-id](let [now (OffsetDateTime/now)]- (t2/update! :model/ExplorationThread thread-id- {:analysis_started_at now- :completed_at now})))+ (explorations.db/update-thread! thread-id {:analysis_started_at now+ :completed_at now})));; ---------------------------------------------------------------------------;; Transcript persistence@@ -263,8 +251,7 @@(defn- save-transcript+ (explorations.db/update-thread! thread-id {:query_plan_transcript transcript})(catch Throwable e(log/warnf e "Failed to save query-plan transcript for thread %d" thread-id))))@@ -286,22 +273,17 @@(defn- thread-prompt-for[thread-id]- (t2/select-one-fn :prompt :model/ExplorationThread :id thread-id))+ (explorations.db/thread-prompt thread-id))(defn- creator-id-for-thread[thread-id]- (t2/select-one-fn :creator_id :model/Exploration- {:join [:exploration_thread- [:= :exploration_thread.exploration_id :exploration.id]]- :where [:= :exploration_thread.id thread-id]}))+ (explorations.db/exploration-creator-id-for-thread thread-id))(defn- build-planner-ctx"Build the planner-contract ctx the chosen planner consumes. Pure computemodulo the t2 selects for thread / metrics / dims."[thread-id]- (let [thread-blocks (t2/select :model/ExplorationBlock- :exploration_thread_id thread-id- {:order-by [[:position :asc] [:id :asc]]})+ (let [thread-blocks (explorations.db/blocks-for-thread thread-id)metric-dim-ctx (qp.context/metric-and-dim-context thread-blocks);; [block-id metric-id] -> metric-context, so materialization resolves a plan;; item against the same block the planner emitted it under (a metric can live@@ -410,7 +392,7 @@the same terminal state [[generate-query-plan!]] writes when the planner itself fails:transcript and the terminal stamp that stops the client polling."[thread-id message]- (when-not (t2/exists? :model/ExplorationQuery :exploration_thread_id thread-id)+ (when-not (explorations.db/thread-has-queries? thread-id)(let [message (or message "planning gave up after exhausting retries")](record-outcome! thread-id (preamble thread-id :unknown) :error :error message)(mark-thread-terminally-failed! thread-id))))@@ -422,4 +404,4 @@(defn debug-transcript"Return the persisted query-plan transcript for `thread-id`."[thread-id]- (t2/select-one-fn :query_plan_transcript :model/ExplorationThread :id thread-id))+ (explorations.db/thread-transcript thread-id))diff --git a/src/metabase/explorations/query_plan/context.clj b/src/metabase/explorations/query_plan/context.cljindex cbccfa6c279..94de330f2b2 100644--- a/src/metabase/explorations/query_plan/context.clj+++ b/src/metabase/explorations/query_plan/context.clj@@ -14,13 +14,13 @@(:require[clojure.string :as str][metabase.explorations.blocks :as explorations.blocks]+ [metabase.explorations.db :as explorations.db][metabase.explorations.models.exploration-block :as block][metabase.explorations.query-plan.mbql :as qp.mbql][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.metrics.core :as metrics]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(set! *warn-on-reflection* true)@@ -192,10 +192,7 @@[blocks](let [card-ids (distinct (mapcat #(map :card_id (:metrics %)) blocks))cards (when (seq card-ids)- (t2/select-pk->fn identity- [:model/Card :id :name :description :database_id- :dataset_query :card_schema :dimensions :dimension_mappings]- :id [:in card-ids]))+ (explorations.db/metric-cards-by-id card-ids))mp-by-db (memoize (fn [db-id] (lib-be/application-database-metadata-provider db-id)))]{:blocks (mapv #(block-context % cards mp-by-db) blocks)}))@@ -351,12 +348,9 @@`ExplorationBlock`, reached via the row's `ExplorationPage`, not fromper-thread metric/dimension tables. The runner calls this per claimed row."[{:keys [card_id dimension_id segment_id params page_id]}]- (let [card (t2/select-one :model/Card :id card_id)+ (let [card (explorations.db/card card_id)block (when page_id- (t2/select-one :model/ExplorationBlock- {:join [[:exploration_page :p]- [:= :p.exploration_block_id :exploration_block.id]]- :where [:= :p.id page_id]}))+ (explorations.db/block-for-page page_id))metric (some #(when (= card_id (:card_id %)) %) (:metrics block))dim-by-id (u/index-by :dimension-id (:dimensions block))thread-dim (get dim-by-id dimension_id)]diff --git a/src/metabase/explorations/runner.clj b/src/metabase/explorations/runner.cljindex 17f6d7b297a..d860257179d 100644--- a/src/metabase/explorations/runner.clj+++ b/src/metabase/explorations/runner.clj@@ -12,6 +12,7 @@[metabase.analytics-interface.core :as analytics.interface][metabase.analytics.core :as analytics][metabase.contextual-interestingness.core :as contextual-interestingness]+ [metabase.explorations.db :as explorations.db][metabase.explorations.interestingness :as explorations.interestingness][metabase.explorations.query-plan :as explorations.query-plan][metabase.explorations.query-plan.context :as qp.context]@@ -34,16 +35,13 @@(defn- pending-query-depth"Number of `exploration_query` rows currently awaiting execution."[]- (t2/count :model/ExplorationQuery :status "pending"))+ (explorations.db/pending-query-count))(defn- oldest-pending-age-seconds"Age in seconds of the oldest still-pending `exploration_query`, or 0 when the queue is empty.Computed as `now - min(created_at)` so it keeps climbing while the runner is stalled."[]- (if-let [oldest (t2/select-one-fn :created_at :model/ExplorationQuery- {:where [:= :status "pending"]- :order-by [[:created_at :asc]]- :limit 1})]+ (if-let [oldest (explorations.db/oldest-pending-query-created-at)](max 0 (.toSeconds (Duration/between ^OffsetDateTime oldest (OffsetDateTime/now))))0))@@ -63,14 +61,7 @@(defn- runnable-query"Load the `ExplorationQuery` `query-id` if it is still work to do, else nil."[query-id]- (t2/select-one :model/ExplorationQuery- {:select [:eq.*]- :from [[:exploration_query :eq]]- :join [[:exploration_thread :et] [:= :et.id :eq.exploration_thread_id]]- :where [:and- [:= :eq.id query-id]- [:= :eq.status "pending"]- [:= :et.canceled_at nil]]}))+ (explorations.db/runnable-query query-id))(defn- serialize-result"Run `cache.impl/do-with-serialization` against a single QP result, returning the gzipped+nippy@@ -123,8 +114,7 @@(throw (ex-info "Could not build dataset_query for row (discovery returned no values?)"{:row-id (:id row) :variant variant})))(let [token (compute-data-access-token dq (:database_id row))]- (t2/update! :model/ExplorationQuery (:id row)- {:dataset_query dq :name nm :data_access_token token})+ (explorations.db/update-query! (:id row) {:dataset_query dq :name nm :data_access_token token})(assoc row :dataset_query dq :name nm :data_access_token token))))))(defn- safe-chart-config@@ -176,20 +166,7 @@NOW() iff every query on the thread has reached a terminal status (anything other than `pending`).Returns true iff this caller was the one that claimed it"[thread-id]- (pos?- (t2/query-one- {:update :exploration_thread- :set {:analysis_started_at (OffsetDateTime/now)- :completed_at (OffsetDateTime/now)}- :where [:and- [:= :id thread-id]- [:= :analysis_started_at nil]- [:= :canceled_at nil]- [:not-exists ^:allow-subquery {:select [1]- :from [:exploration_query]- :where [:and- [:= :exploration_thread_id thread-id]- [:= :status "pending"]]}]]})))+ (pos? (explorations.db/claim-thread-analysis! thread-id (OffsetDateTime/now))))(defn maybe-complete-thread!"Invoke after any state transition that could be the last unit of work for `thread-id`@@ -207,16 +184,12 @@(defn- exploration-creator-id"Walk EQ → ExplorationThread → Exploration.creator_id for stamping onto the stored_result."[exploration-query]- (t2/select-one-fn :creator_id :model/Exploration- {:join [:exploration_thread- [:= :exploration_thread.exploration_id :exploration.id]]- :where [:= :exploration_thread.id (:exploration_thread_id exploration-query)]}))+ (explorations.db/exploration-creator-id-for-thread (:exploration_thread_id exploration-query)))(defn- exploration-id"Walk EQ → ExplorationThread → Exploration.id for recording the stored_result_use reference."[exploration-query]- (t2/select-one-fn :exploration_id :model/ExplorationThread- :id (:exploration_thread_id exploration-query)))+ (explorations.db/thread-exploration-id (:exploration_thread_id exploration-query)))(defn- variant-note"Human phrase for a chart's breakdown variant + params, or nil for the plain `default`@@ -242,7 +215,7 @@Returns nil for a plain unsegmented default breakdown (nothing to call out)."[row](let [segment-name (when-let [sid (:segment_id row)]- (t2/select-one-fn :name :model/Segment :id sid))+ (explorations.db/segment-name sid))variant (variant-note (:query_type row) (:params row))parts (cond-> []variant (conj variant)@@ -258,7 +231,7 @@charts that won't be scored."[exploration-query]{:card-description (when-let [card-id (:card_id exploration-query)]- (some-> (t2/select-one-fn :description :model/Card :id card-id)+ (some-> (explorations.db/card-description card-id)str/trimnot-empty)):sql (contextual-interestingness/dataset-query->sql (:dataset_query exploration-query))})@@ -284,7 +257,7 @@(if (nil? creator-id)(log/warnf "Skipping contextual interestingness for ExplorationQuery %d: no creator-id on exploration"(:id exploration-query))- (let [prompt (t2/select-one-fn :prompt :model/ExplorationThread :id thread-id)]+ (let [prompt (explorations.db/thread-prompt thread-id)](when-not (str/blank? prompt)(let [{:keys [card-description sql]} (build-score-context exploration-query)](request/with-current-user creator-id@@ -346,34 +319,29 @@[row ^OffsetDateTime started {:keys [creator-id db-id bytes row-count token stats score ctx]}](try(t2/with-transaction [_conn]- (let [sr-id (first- (t2/insert-returning-pks!- :model/StoredResult- {:result_data bytes- :creator_id creator-id- :database_id db-id- :dataset_query (:dataset_query row)- :row_count row-count- :data_access_token token}))]- (t2/insert! :model/ExplorationQueryResult- {:exploration_query_id (:id row)- :stored_result_id sr-id- :chart_stats stats- :interestingness_score score- :contextual_interestingness_score (:score ctx)- :metric_description (:metric-description ctx)- :chart_description (:chart-description ctx)})+ (let [sr-id (explorations.db/insert-stored-result! {:result_data bytes+ :creator_id creator-id+ :database_id db-id+ :dataset_query (:dataset_query row)+ :row_count row-count+ :data_access_token token})]+ (explorations.db/insert-query-result!+ {:exploration_query_id (:id row)+ :stored_result_id sr-id+ :chart_stats stats+ :interestingness_score score+ :contextual_interestingness_score (:score ctx)+ :metric_description (:metric-description ctx)+ :chart_description (:chart-description ctx)});; Record the (exploration -> stored_result) reference for lifecycle/GC tracking.- (t2/insert! :model/StoredResultUse- {:stored_result_id sr-id- :exploration_id (exploration-id row)})- (t2/update! :model/ExplorationQuery (:id row)- {:status "done"- :started_at started- :finished_at (OffsetDateTime/now)})))+ (explorations.db/insert-stored-result-use! {:stored_result_id sr-id+ :exploration_id (exploration-id row)})+ (explorations.db/update-query! (:id row) {:status "done"+ :started_at started+ :finished_at (OffsetDateTime/now)})))true(catch Exception e- (if (t2/exists? :model/ExplorationQueryResult :exploration_query_id (:id row))+ (if (explorations.db/query-result-exists? (:id row))(do (log/infof "ExplorationQuery %d was already completed by a peer; discarding this run's duplicate result"(:id row))false)@@ -404,8 +372,7 @@(when (persist-query-result! row started computed)(record-query-outcome! "done"))(:exploration_thread_id row))))- (t2/select-one-fn :exploration_thread_id :model/ExplorationQuery- :id query-id :status [:in ["done" "error" "canceled"]])))+ (explorations.db/finished-query-thread-id query-id)))(defn fail-query!"Terminally mark `query-id` as `error` with `message`, the user-visible failure state the UI@@ -413,12 +380,8 @@No-ops on a row that is no longer `pending` (a later delivery succeeded, or it was canceled)."[query-id message]- (let [thread-id (t2/select-one-fn :exploration_thread_id :model/ExplorationQuery :id query-id)]- (when (pos? (t2/update! :model/ExplorationQuery- {:id query-id :status "pending"}- {:status "error"- :error_message message- :finished_at (OffsetDateTime/now)}))+ (let [thread-id (explorations.db/query-thread-id query-id)]+ (when (pos? (explorations.db/fail-pending-query! query-id message (OffsetDateTime/now)))(record-query-outcome! "error"))thread-id))@@ -428,16 +391,13 @@saw the rows that existed at cancel time; rows the planner inserted after that are still `pending`on a canceled thread. Flip them so the query table matches its owning thread's terminal state."[thread-id]- (when (t2/exists? :model/ExplorationThread :id thread-id :canceled_at [:not= nil])- (t2/update! :model/ExplorationQuery- {:exploration_thread_id thread-id- :status "pending"}- {:status "canceled"})))+ (when (explorations.db/thread-canceled? thread-id)+ (explorations.db/cancel-pending-queries-for-thread! thread-id)))(defn plan-thread!"Run the LLM planner for `thread-id`, materializing its `ExplorationQuery` rows. Idempotent for MQ."[thread-id]- (let [thread (t2/select-one [:model/ExplorationThread :id :canceled_at :analysis_started_at] :id thread-id)+ (let [thread (explorations.db/thread-planning-state thread-id)planned? (cond;; `restart` deletes and re-creates a thread's work; a message for a thread that;; no longer exists is a no-op.@@ -459,7 +419,7 @@(do (log/infof "Exploration thread %d already completed its analysis; skipping planning" thread-id)false)- (t2/exists? :model/ExplorationQuery :exploration_thread_id thread-id)+ (explorations.db/thread-has-queries? thread-id)(do (log/infof "Exploration thread %d is already planned; skipping" thread-id)false)@@ -485,4 +445,4 @@(defn pending-query-ids"Ids of `thread-id`'s queries still awaiting execution."[thread-id]- (t2/select-pks-vec :model/ExplorationQuery :exploration_thread_id thread-id :status "pending"))+ (explorations.db/pending-query-ids-for-thread thread-id))diff --git a/src/metabase/explorations/task/collect_orphaned_results.clj b/src/metabase/explorations/task/collect_orphaned_results.cljindex 18c7fe2d0c1..29a13ff3b64 100644--- a/src/metabase/explorations/task/collect_orphaned_results.clj+++ b/src/metabase/explorations/task/collect_orphaned_results.clj@@ -30,10 +30,10 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase.explorations.db :as explorations.db][metabase.task-history.core :as task-history][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -57,22 +57,9 @@than [[grace-period-minutes]]."[](mapv :id- (t2/query- {:select [:sr.id]- :from [[:stored_result :sr]]- :where [:and- [:not [:exists ^:allow-subquery {:select [1]- :from [[:exploration_query_result :eqr]]- :where [:= :eqr.stored_result_id :sr.id]}]]- [:not [:exists ^:allow-subquery {:select [1]- :from [[:stored_result_use :sru]]- :where [:and- [:= :sru.stored_result_id :sr.id]- [:not= :sru.card_id nil]]}]]- [:< :sr.created_at (t/minus (t/offset-date-time)- (t/minutes grace-period-minutes))]]- :order-by [[:sr.id :asc]]- :limit batch-size})))+ (explorations.db/orphaned-stored-result-ids (t/minus (t/offset-date-time)+ (t/minutes grace-period-minutes))+ batch-size)))(defn collect-orphaned-results!"Delete every unreachable `stored_result`, in batches. Returns the number collected."@@ -85,7 +72,7 @@total);; Selected and deleted as two statements: MySQL/MariaDB reject deleting from a table that a;; subquery in the same statement reads (error 1093).- (let [deleted (t2/delete! :model/StoredResult :id [:in ids])]+ (let [deleted (explorations.db/delete-stored-results! ids)](if (pos? deleted)(recur (+ total (long deleted)));; Nothing deleted despite finding rows — another writer got there first. Stop ratherdiff --git a/src/metabase/glossary/api.clj b/src/metabase/glossary/api.cljindex 5165f81ce61..881f0188390 100644--- a/src/metabase/glossary/api.clj+++ b/src/metabase/glossary/api.clj@@ -4,7 +4,7 @@[metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.events.core :as events]- [metabase.util.honey-sql-2 :as h2x]+ [metabase.glossary.db :as glossary.db][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -16,14 +16,7 @@"Fetch all glossary entries, optionally filtered by search term."[_route-params{:keys [search]} :- [:maybe [:map [:search {:optional true} [:maybe ms/NonBlankString]]]]]- (let [where (when search- (let [pattern (h2x/like-substring search)]- [:or- [:like [:lower :term] pattern]- [:like [:lower :definition] pattern]]))]- {:data (t2/hydrate (t2/select :model/Glossary (cond-> {:order-by [[:term :asc]]}- where (assoc :where where)))- :creator)}))+ {:data (t2/hydrate (glossary.db/glossary-entries search) :creator)});; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -37,10 +30,10 @@[:term ms/NonBlankString][:definition ms/NonBlankString]]](api/check-data-analyst)- (let [glossary (t2/insert-returning-instance! :model/Glossary- {:term term- :definition definition- :creator_id api/*current-user-id*})]+ (let [glossary (glossary.db/insert-glossary-entry!+ {:term term+ :definition definition+ :creator_id api/*current-user-id*})](events/publish-event! :event/glossary-create{:object glossary:user-id api/*current-user-id*})@@ -58,9 +51,9 @@[:term ms/NonBlankString][:definition ms/NonBlankString]]](api/check-data-analyst)- (let [previous-glossary (api/check-404 (t2/select-one :model/Glossary :id id))]- (t2/update! :model/Glossary id {:term term :definition definition})- (let [glossary (t2/select-one :model/Glossary :id id)]+ (let [previous-glossary (api/check-404 (glossary.db/glossary-entry id))]+ (glossary.db/update-glossary-entry! id term definition)+ (let [glossary (glossary.db/glossary-entry id)](events/publish-event! :event/glossary-update{:object glossary:previous-object previous-glossary@@ -75,8 +68,8 @@"Delete a glossary entry."[{:keys [id]} :- [:map [:id ms/PositiveInt]]](api/check-data-analyst)- (let [glossary (api/check-404 (t2/select-one :model/Glossary :id id))]- (t2/delete! :model/Glossary :id id)+ (let [glossary (api/check-404 (glossary.db/glossary-entry id))]+ (glossary.db/delete-glossary-entry! id)(events/publish-event! :event/glossary-delete{:object glossary:user-id api/*current-user-id*}))diff --git a/src/metabase/glossary/db.clj b/src/metabase/glossary/db.cljnew file mode 100644index 00000000000..2fe42508374--- /dev/null+++ b/src/metabase/glossary/db.clj@@ -0,0 +1,47 @@+(ns metabase.glossary.db+ "Application database queries for the glossary module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn glossary-entries+ "The Glossary entries whose term or definition contains `search` case-insensitively, or every+ entry when `search` is nil, in term order."+ [search]+ (t2/select :model/Glossary+ (cond-> {:order-by [[:term :asc]]}+ search (assoc :where (let [pattern (h2x/like-substring search)]+ [:or+ [:like [:lower :term] pattern]+ [:like [:lower :definition] pattern]])))))++(defn insert-glossary-entry!+ "Insert the Glossary `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Glossary row))++(defn glossary-entry+ "The Glossary entry with `id`, or nil."+ [id]+ (t2/select-one :model/Glossary :id id))++(defn update-glossary-entry!+ "Set the term and definition of the Glossary entry with `id`."+ [id term definition]+ (t2/update! :model/Glossary id {:term term :definition definition}))++(defn delete-glossary-entry!+ "Delete the Glossary entry with `id`."+ [id]+ (t2/delete! :model/Glossary :id id))++(defn users-by-id+ "A map of User id to the id, email, and name of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))++(defn glossary-entry-by-term+ "The Glossary entry for `term`, or nil."+ [term]+ (t2/select-one :model/Glossary :term term))diff --git a/src/metabase/glossary/models/glossary.clj b/src/metabase/glossary/models/glossary.cljindex 6254152cb68..7d52bc1221d 100644--- a/src/metabase/glossary/models/glossary.clj+++ b/src/metabase/glossary/models/glossary.clj@@ -1,5 +1,6 @@(ns metabase.glossary.models.glossary(:require+ [metabase.glossary.db :as glossary.db][metabase.models.serialization :as serdes][metabase.util.malli.schema :as ms][methodical.core :as methodical]@@ -17,8 +18,7 @@(if-not (seq glossary-entries)glossary-entries(let [creator-ids (into #{} (map :creator_id) glossary-entries)- id->creator (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id [:in creator-ids])]+ id->creator (glossary.db/users-by-id creator-ids)](for [entry glossary-entries](assoc entry :creator (get id->creator (:creator_id entry)))))))@@ -36,7 +36,7 @@(defmethod serdes/load-find-local "Glossary"[path]- (t2/select-one :model/Glossary :term (:id (first path))))+ (glossary.db/glossary-entry-by-term (:id (first path))))(defmethod serdes/make-spec "Glossary" [_model-name _opts]{:copy [:term :definition]diff --git a/src/metabase/health_inspector/core.clj b/src/metabase/health_inspector/core.cljindex 51282b105a6..55ea6e6261c 100644--- a/src/metabase/health_inspector/core.clj+++ b/src/metabase/health_inspector/core.clj@@ -4,6 +4,7 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase.health-inspector.db :as health-inspector.db][metabase.health-inspector.settings :as setting][metabase.lib-be.core :as lib-be][metabase.lib.schema :as schema]@@ -11,8 +12,7 @@[metabase.util :as u][metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(set! *warn-on-reflection* true)@@ -31,7 +31,7 @@(defn ^:internal validate-queries"Determine how many saved queries are valid according to the malli schema."[]- (let [queries (t2/reducible-select :report_card {:where [:= :archived false]})+ (let [queries (health-inspector.db/unarchived-cards-reducible){:keys [total valid]} (reduce validate-query {:total 0 :valid 0} queries)ratio (if (zero? total)1@@ -80,9 +80,9 @@a misleading healthy score."[check-name result](when (some? result)- (t2/insert! :health_inspector_runs (-> result- (select-keys [:health :message])- (assoc :check_name (name check-name))))))+ (health-inspector.db/insert-run! (-> result+ (select-keys [:health :message])+ (assoc :check_name (name check-name))))))(def ^:private run-retention-days"Days of health-inspector runs to keep. Metric checks embed changing values (coverage %, ages) in their@@ -92,8 +92,7 @@(defn- delete-old-runs!"Delete health-inspector runs older than [[run-retention-days]]."[]- (t2/delete! :health_inspector_runs- :run_at [:< (t/minus (t/offset-date-time) (t/days run-retention-days))]))+ (health-inspector.db/delete-runs-before! (t/minus (t/offset-date-time) (t/days run-retention-days))))(defn save-report"Run every registered check and persist the results (not-applicable (nil) checks are omitted), then prune@@ -105,10 +104,7 @@(defn- latest-run[check-name]- ;; Tie-break on id: back-to-back inserts can share a run_at, and run_at alone would then pick a- ;; non-deterministic row, breaking the dedup below (id is a monotonic auto-increment PK).- (t2/select-one [:health_inspector_runs :health :message] :check_name (name check-name)- {:order-by [[:run_at :desc] [:id :desc]]}))+ (health-inspector.db/latest-run (name check-name)))(defn save-check-result!"Persist a precomputed check `result` (a `{:health :message}` map, or nil to skip). Skip the write when the@@ -136,7 +132,7 @@(defn list-runs"Return the most recent health inspector runs from the DB."[limit]- (t2/select :health_inspector_runs {:limit limit :order-by [[:run_at :desc]]}))+ (health-inspector.db/latest-runs limit))(task/defjob ^:private ^{org.quartz.DisallowConcurrentExecution true} SaveReport [_](when (setting/health-inspector-enabled)diff --git a/src/metabase/health_inspector/db.clj b/src/metabase/health_inspector/db.cljnew file mode 100644index 00000000000..38e1a8006a4--- /dev/null+++ b/src/metabase/health_inspector/db.clj@@ -0,0 +1,33 @@+(ns metabase.health-inspector.db+ "Application database queries for the health inspector module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn unarchived-cards-reducible+ "A reducible of the unarchived `report_card` rows."+ []+ (t2/reducible-select :report_card {:where [:= :archived false]}))++(defn insert-run!+ "Insert the `health_inspector_runs` `row`."+ [row]+ (t2/insert! :health_inspector_runs row))++(defn delete-runs-before!+ "Delete the `health_inspector_runs` rows run before `run-before`."+ [run-before]+ (t2/delete! :health_inspector_runs :run_at [:< run-before]))++(defn latest-run+ "The `:health` and `:message` of the most recent `health_inspector_runs` row for `check-name`, or nil."+ [check-name]+ ;; Tie-break on id: back-to-back inserts can share a run_at, and run_at alone would then pick a non-deterministic+ ;; row (id is a monotonic auto-increment PK).+ (t2/select-one [:health_inspector_runs :health :message] :check_name check-name+ {:order-by [[:run_at :desc] [:id :desc]]}))++(defn latest-runs+ "The `limit` most recent `health_inspector_runs` rows."+ [limit]+ (t2/select :health_inspector_runs {:limit limit :order-by [[:run_at :desc]]}))diff --git a/src/metabase/indexed_entities/api.clj b/src/metabase/indexed_entities/api.cljindex 7fa9db27e0b..a90627ff91f 100644--- a/src/metabase/indexed_entities/api.clj+++ b/src/metabase/indexed_entities/api.clj@@ -3,13 +3,13 @@[metabase.analytics.core :as analytics][metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.indexed-entities.db :as indexed-entities.db][metabase.indexed-entities.models.model-index :as model-index][metabase.indexed-entities.task.index-values :as task.index-values];; legacy usage, do not use this in new code^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.normalize :as mbql.normalize][metabase.util.i18n :refer [tru]]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(defn- ensure-type"Ensure that the ref exists and is of type required for indexing."@@ -64,7 +64,7 @@:model-id model_id})(task.index-values/add-indexing-job model-index)(model-index/add-values! model-index)- (t2/select-one :model/ModelIndex :id (:id model-index)))))+ (indexed-entities.db/model-index (:id model-index)))));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST API@@ -84,7 +84,7 @@(throw (ex-info (tru "Question {0} is not a model" model_id){:model_id model_id:status-code 400})))- (t2/select :model/ModelIndex :model_id model_id)))+ (indexed-entities.db/model-indexes-for-model model_id)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -94,7 +94,7 @@"Retrieve ModelIndex."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (let [model-index (api/check-404 (t2/select-one :model/ModelIndex :id id))+ (let [model-index (api/check-404 (indexed-entities.db/model-index id))model (api/read-check :model/Card (:model_id model-index))](when-not (= (:type model) :model)(throw (ex-info (tru "Question {0} is not a model" id)@@ -110,6 +110,6 @@"Delete ModelIndex."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (api/let-404 [model-index (t2/select-one :model/ModelIndex :id id)]+ (api/let-404 [model-index (indexed-entities.db/model-index id)](api/write-check :model/Card (:model_id model-index))- (t2/delete! :model/ModelIndex id)))+ (indexed-entities.db/delete-model-index! id)))diff --git a/src/metabase/indexed_entities/db.clj b/src/metabase/indexed_entities/db.cljnew file mode 100644index 00000000000..41b5d4f6f47--- /dev/null+++ b/src/metabase/indexed_entities/db.clj@@ -0,0 +1,74 @@+(ns metabase.indexed-entities.db+ "Application database queries for the indexed entities module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn model-index+ "The ModelIndex with `id`, or nil."+ [id]+ (t2/select-one :model/ModelIndex :id id))++(defn model-indexes-for-model+ "The ModelIndexes of the model Card with `model-id`."+ [model-id]+ (t2/select :model/ModelIndex :model_id model-id))++(defn all-model-indexes+ "Every ModelIndex."+ []+ (t2/select :model/ModelIndex))++(defn model-indexes-except+ "The ModelIndexes whose id is not in `ids`."+ [ids]+ (t2/select :model/ModelIndex :id [:not-in ids]))++(defn delete-model-index!+ "Delete the ModelIndex with `id`."+ [id]+ (t2/delete! :model/ModelIndex id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn model-index-values+ "The ModelIndexValues of the ModelIndex with `model-index-id`."+ [model-index-id]+ (t2/select :model/ModelIndexValue :model_index_id model-index-id))++(defn model-index-values-reducible+ "A reducible of the ModelIndexValues of the ModelIndex with `model-index-id`."+ [model-index-id]+ (t2/reducible-select :model/ModelIndexValue :model_index_id model-index-id))++(defn mark-model-index-error!+ "Record `error-message` on the ModelIndex with `id` and stamp its indexing time."+ [id error-message]+ (t2/update! :model/ModelIndex id {:state "error"+ :error error-message+ :indexed_at :%now}))++(defn mark-model-index-indexed!+ "Set the ModelIndex with `id` to `state`, clear its error, and stamp its indexing time."+ [id state]+ (t2/update! :model/ModelIndex id {:indexed_at :%now+ :error nil+ :state state}))++(defn delete-model-index-values!+ "Delete the ModelIndexValues of the ModelIndex with `model-index-id` for the model primary keys `model-pks`."+ [model-index-id model-pks]+ (t2/delete! :model/ModelIndexValue :model_index_id model-index-id :model_pk [:in model-pks]))++(defn insert-model-index-values!+ "Insert the ModelIndexValue `rows`."+ [rows]+ (t2/insert! :model/ModelIndexValue rows))++(defn insert-model-index!+ "Insert the ModelIndex `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/ModelIndex [row]))diff --git a/src/metabase/indexed_entities/models/model_index.clj b/src/metabase/indexed_entities/models/model_index.cljindex 9672fdfb500..8d669dc58b9 100644--- a/src/metabase/indexed_entities/models/model_index.clj+++ b/src/metabase/indexed_entities/models/model_index.clj@@ -2,6 +2,7 @@(:require[clojure.set :as set][clojure.string :as str]+ [metabase.indexed-entities.db :as indexed-entities.db];; legacy usage, do not use this in new code^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.normalize :as mbql.normalize];; model-index pk/value refs are stored as legacy field refs; validated against the legacy schema@@ -80,7 +81,7 @@(mu/defn ^:private fetch-values[model-index :- ::model-index]- (let [model (t2/select-one :model/Card :id (:model_id model-index))+ (let [model (indexed-entities.db/card (:model_id model-index))fix (mu/fn [field-ref :- some?base-type :- ::lib.schema.common/base-type];; stored value/pk refs are legacy MBQL; normalize as legacy before use@@ -124,12 +125,9 @@(let [[error-message values-to-index] (fetch-values model-index)current-index-values (into #{}(map (juxt :model_pk :name))- (t2/select :model/ModelIndexValue- :model_index_id (:id model-index)))]+ (indexed-entities.db/model-index-values (:id model-index)))](if-not (str/blank? error-message)- (t2/update! :model/ModelIndex (:id model-index) {:state "error"- :error error-message- :indexed_at :%now})+ (indexed-entities.db/mark-model-index-error! (:id model-index) error-message)(try(t2/with-transaction [_conn](let [{:keys [additions deletions]} (find-changes {:current-index current-index-values@@ -139,32 +137,25 @@:let [search-model-ids (map (fn [[pk]](str (:id model-index) ":" pk))deletions-part)]]- (t2/delete! :model/ModelIndexValue- :model_index_id (:id model-index)- :model_pk [:in (->> deletions-part (map first))])+ (indexed-entities.db/delete-model-index-values! (:id model-index) (->> deletions-part (map first)))(search/delete! :model/ModelIndexValue search-model-ids)))(when (seq additions)(doseq [additions-part (partition-all 10000 additions)]- (t2/insert! :model/ModelIndexValue- (map (fn [[id v]]- {:name v- :model_pk id- :model_index_id (:id model-index)})- additions-part)))))- (t2/update! :model/ModelIndex (:id model-index)- {:indexed_at :%now- :error nil- :state (if (> (count values-to-index) max-indexed-values)- "overflow"- "indexed")}))- (run! search/update! (t2/reducible-select :model/ModelIndexValue :model_index_id (:id model-index)))+ (indexed-entities.db/insert-model-index-values!+ (map (fn [[id v]]+ {:name v+ :model_pk id+ :model_index_id (:id model-index)})+ additions-part)))))+ (indexed-entities.db/mark-model-index-indexed! (:id model-index)+ (if (> (count values-to-index) max-indexed-values)+ "overflow"+ "indexed")))+ (run! search/update! (indexed-entities.db/model-index-values-reducible (:id model-index)))(catch Exception e(log/errorf "Error saving model-index values for model-index: %d, model: %d: %s"(:id model-index) (:model_id model-index) (ex-message e))- (t2/update! :model/ModelIndex (:id model-index)- {:state "error"- :error (ex-message e)- :indexed_at :%now}))))))+ (indexed-entities.db/mark-model-index-error! (:id model-index) (ex-message e)))))));;;; creation@@ -176,14 +167,13 @@(defn create"Create a model index"[{:keys [model-id pk-ref value-ref creator-id]}]- (t2/insert-returning-instance! :model/ModelIndex- [{:model_id model-id- ;; todo: sanitize these?- :pk_ref pk-ref- :value_ref value-ref- :schedule (default-schedule)- :state "initial"- :creator_id creator-id}]))+ (indexed-entities.db/insert-model-index! {:model_id model-id+ ;; todo: sanitize these?+ :pk_ref pk-ref+ :value_ref value-ref+ :schedule (default-schedule)+ :state "initial"+ :creator_id creator-id}));;;; ------------------------------------------------- Search ----------------------------------------------------------diff --git a/src/metabase/indexed_entities/task/index_values.clj b/src/metabase/indexed_entities/task/index_values.cljindex b4e465edbe8..9bc421c5645 100644--- a/src/metabase/indexed_entities/task/index_values.clj+++ b/src/metabase/indexed_entities/task/index_values.clj@@ -5,12 +5,12 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][metabase.driver :as driver]+ [metabase.indexed-entities.db :as indexed-entities.db][metabase.indexed-entities.models.model-index :as model-index][metabase.query-processor.timezone :as qp.timezone][metabase.task.core :as task][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.util TimeZone)(org.quartz ObjectAlreadyExistsException)))@@ -41,14 +41,14 @@"Refresh the index on a model. Note, if the index should be removed (no longer a model, archived,etc, (see [[should-deindex?]])) will delete the indexing job."[model-index-id]- (let [model-index (t2/select-one :model/ModelIndex :id model-index-id)+ (let [model-index (indexed-entities.db/model-index model-index-id)model (when model-index- (t2/select-one :model/Card :id (:model_id model-index)))]+ (indexed-entities.db/card (:model_id model-index)))](if (should-deindex? model model-index)(u/ignore-exceptions(let [trigger-key (model-index-trigger-key model-index-id)](task/delete-trigger! trigger-key)- (t2/delete! :model/ModelIndex model-index-id)))+ (indexed-entities.db/delete-model-index! model-index-id)))(model-index/add-values! model-index))))(task/defjob ^{org.quartz.DisallowConcurrentExecution true@@ -114,8 +114,8 @@(log/warnf "Error fetching existing triggers from Quartz, will recreate all triggers: %s" (ex-message e))#{}))missing-trigger-model-indexes (if (seq existing-trigger-model-index-ids)- (t2/select :model/ModelIndex :id [:not-in existing-trigger-model-index-ids])- (t2/select :model/ModelIndex))]+ (indexed-entities.db/model-indexes-except existing-trigger-model-index-ids)+ (indexed-entities.db/all-model-indexes))](when (seq missing-trigger-model-indexes)(log/infof "Found %d model index(es) without triggers, recreating..."(count missing-trigger-model-indexes))diff --git a/src/metabase/indexes/db.clj b/src/metabase/indexes/db.cljnew file mode 100644index 00000000000..f54564a0503--- /dev/null+++ b/src/metabase/indexes/db.clj@@ -0,0 +1,69 @@+(ns metabase.indexes.db+ "Application database queries for the indexes module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn table-indexes-for-transform+ "The TableIndexes of the Transform with `transform-id`, in id order."+ [transform-id]+ (t2/select :model/TableIndex :transform_id transform-id {:order-by [[:id :asc]]}))++(defn applicable-table-indexes-for-transform+ "The TableIndexes of the Transform with `transform-id` that are not pending deletion, in name order."+ [transform-id]+ (t2/select :model/TableIndex+ :transform_id transform-id+ :status [:not= :delete-pending]+ {:order-by [[:index_name :asc]]}))++(defn running-table-indexes+ "The running TableIndexes among `ids` of the Transform with `transform-id`, in id order."+ [transform-id ids]+ (t2/select :model/TableIndex+ :transform_id transform-id+ :id [:in ids]+ :status :running+ {:order-by [[:id :asc]]}))++(defn delete-pending-table-indexes+ "The TableIndexes of the Transform with `transform-id` that are pending deletion, in id order."+ [transform-id]+ (t2/select :model/TableIndex+ :transform_id transform-id+ :status :delete-pending+ {:order-by [[:id :asc]]}))++(defn applicable-table-index+ "The TableIndex with `id` if it is not pending deletion, or nil."+ [id]+ (t2/select-one :model/TableIndex :id id :status [:not= :delete-pending]))++(defn table-index-with-status-exists?+ "Whether the Transform with `transform-id` has a TableIndex in one of `statuses`."+ [transform-id statuses]+ (t2/exists? :model/TableIndex :transform_id transform-id :status [:in statuses]))++(defn mark-table-indexes-running!+ "Set the TableIndexes among `ids` whose status is in `from-statuses` to running."+ [ids from-statuses]+ (t2/update! :model/TableIndex {:id [:in ids] :status [:in from-statuses]} {:status :running}))++(defn mark-running-table-indexes-failed!+ "Set the running TableIndexes among `ids` to failed with `error-message`."+ [ids error-message]+ (t2/update! :model/TableIndex+ {:id [:in ids] :status :running}+ {:status :failed+ :error_message error-message+ :last_executed_at :%now}))++(defn mark-table-indexes-update-pending!+ "Set the TableIndexes with `ids` to update-pending and clear their error."+ [ids]+ (t2/update! :model/TableIndex {:id [:in ids]} {:status :update-pending, :error_message nil}))++(defn table-index-exists-for-transform?+ "Whether the Transform with `transform-id` has a TableIndex named `index-name`."+ [transform-id index-name]+ (t2/exists? :model/TableIndex :transform_id transform-id :index_name index-name))diff --git a/src/metabase/indexes/models/table_index.clj b/src/metabase/indexes/models/table_index.cljindex 98618700487..7ec1eead1f0 100644--- a/src/metabase/indexes/models/table_index.clj+++ b/src/metabase/indexes/models/table_index.clj@@ -8,6 +8,7 @@`:structured` and `:status` are validated at the transform layer (on read and write), so every writer is covered."(:require+ [metabase.indexes.db :as indexes.db][metabase.indexes.schema :as schema][metabase.models.interface :as mi][metabase.models.serialization :as serdes]@@ -79,17 +80,12 @@(defn select-for-transform"All index request rows for `transform-id`, ordered for the index manager list."[transform-id]- (t2/select :model/TableIndex- :transform_id transform-id- {:order-by [[:id :asc]]}))+ (indexes.db/table-indexes-for-transform transform-id))(defn select-applicable-for-transform"Rows whose structured definitions should be applied to `transform-id`'s target table."[transform-id]- (t2/select :model/TableIndex- :transform_id transform-id- :status [:not= :delete-pending]- {:order-by [[:index_name :asc]]}))+ (indexes.db/applicable-table-indexes-for-transform transform-id))(defn select-for-verification"Rows the current execution can update while verifying indexes.@@ -100,27 +96,20 @@[transform-id index-request-ids](concat(when (seq index-request-ids)- (t2/select :model/TableIndex- :transform_id transform-id- :id [:in index-request-ids]- :status :running- {:order-by [[:id :asc]]}))- (t2/select :model/TableIndex- :transform_id transform-id- :status :delete-pending- {:order-by [[:id :asc]]})))+ (indexes.db/running-table-indexes transform-id index-request-ids))+ (indexes.db/delete-pending-table-indexes transform-id)))(defn select-applicable-by-id"Fetch a single applicable index request by id."[id]- (t2/select-one :model/TableIndex :id id :status [:not= :delete-pending]))+ (indexes.db/applicable-table-index id))(defn pending-changes-for-transform?"True when `transform-id` has index changes that require a full rebuild to apply."[transform-id](boolean(when transform-id- (t2/exists? :model/TableIndex :transform_id transform-id :status [:in rebuild-forcing-statuses]))))+ (indexes.db/table-index-with-status-exists? transform-id rebuild-forcing-statuses))))(defn mark-runnable-indexes-running!"Mark hydrated index requests that this run will apply as running.@@ -129,20 +118,14 @@[index-request-ids](let [ids (set index-request-ids)](when (seq ids)- (t2/update! :model/TableIndex- {:id [:in ids] :status [:in runnable-statuses]}- {:status :running}))+ (indexes.db/mark-table-indexes-running! ids runnable-statuses))ids))(defn mark-unverified-running-indexes-failed!"Mark rows from [[mark-runnable-indexes-running!]] that are still running as failed."[ids message](when (seq ids)- (t2/update! :model/TableIndex- {:id [:in ids] :status :running}- {:status :failed- :error_message message- :last_executed_at :%now})))+ (indexes.db/mark-running-table-indexes-failed! ids message)))(defn mark-for-revalidation!"Flip `transform-id`'s applicable index requests to `:update-pending` and clear stale errors, so the next run@@ -150,16 +133,12 @@[transform-id](when transform-id(when-let [ids (seq (map :id (select-applicable-for-transform transform-id)))]- (t2/update! :model/TableIndex- {:id [:in ids]}- {:status :update-pending, :error_message nil}))))+ (indexes.db/mark-table-indexes-update-pending! ids))))(defn exists-for-transform?"True when `transform-id` already has a request for `index-name`."[transform-id index-name]- (t2/exists? :model/TableIndex- :transform_id transform-id- :index_name index-name))+ (indexes.db/table-index-exists-for-transform? transform-id index-name));; Inlined into the owning transform's serialization (see the Transform make-spec's `:indexes`). Only the index;; definition travels; lifecycle is local, so an imported index starts fresh as `:create-pending`. `:structured` holdsdiff --git a/src/metabase/indexes_rest/api.clj b/src/metabase/indexes_rest/api.cljindex 5e0f8a84d98..7041ef81a6d 100644--- a/src/metabase/indexes_rest/api.clj+++ b/src/metabase/indexes_rest/api.clj@@ -7,6 +7,7 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.indexes-rest.db :as indexes-rest.db][metabase.indexes.models.table-index :as table-index][metabase.indexes.reconcile :as reconcile][metabase.indexes.schema :as schema]@@ -70,7 +71,7 @@database-id (transforms-base.i/target-db-id transform){:keys [schema] table-name :name} (:target transform)managed (table-index/select-for-transform transform-id)- warehouse (or (reconcile/fetch-warehouse-indexes (t2/select-one :model/Database database-id)+ warehouse (or (reconcile/fetch-warehouse-indexes (indexes-rest.db/database database-id)schema table-name)[])]{:data (reconcile/merge-indexes managed warehouse)}))@@ -78,7 +79,7 @@(api.macros/defendpoint :get "/request/:id" :- RequestIndex"Fetch a single index request (e.g. to poll its status)."[{:keys [id]} :- [:map [:id ms/PositiveInt]]]- (doto (api/check-404 (t2/select-one :model/TableIndex :id id))+ (doto (api/check-404 (indexes-rest.db/table-index id))(read-check-owner!)))(api.macros/defendpoint :post "/request" :- RequestIndex@@ -95,11 +96,11 @@;; (transform_id, index_name) is unique; reject a duplicate cleanly instead of hitting the constraint.(api/check-400 (not (table-index/exists-for-transform? transform_id idx-name)) duplicate)(try- (t2/insert-returning-instance! :model/TableIndex- {:transform_id transform_id- :index_name idx-name- :structured structured- :created_by api/*current-user-id*})+ (indexes-rest.db/insert-table-index!+ {:transform_id transform_id+ :index_name idx-name+ :structured structured+ :created_by api/*current-user-id*})(catch Exception e;; the pre-check races a concurrent create; if the row exists now, surface the same 400(api/check-400 (not (table-index/exists-for-transform? transform_id idx-name)) duplicate)@@ -125,8 +126,8 @@(assert-stable-key! existing structured);; toucan2 has no instance-returning update, so re-select; in a tx so we return exactly what we wrote.(t2/with-transaction [_conn]- (t2/update! :model/TableIndex id {:structured structured})- (t2/select-one :model/TableIndex :id id))))+ (indexes-rest.db/set-table-index-structured! id structured)+ (indexes-rest.db/table-index id))))#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :delete "/request/:id"@@ -135,5 +136,5 @@[{:keys [id]} :- [:map [:id ms/PositiveInt]]](let [existing (api/check-404 (table-index/select-applicable-by-id id))](write-check-owner! existing)- (t2/update! :model/TableIndex id {:status :delete-pending}))+ (indexes-rest.db/set-table-index-status! id :delete-pending))api/generic-204-no-content)diff --git a/src/metabase/indexes_rest/db.clj b/src/metabase/indexes_rest/db.cljnew file mode 100644index 00000000000..874e600cc28--- /dev/null+++ b/src/metabase/indexes_rest/db.clj@@ -0,0 +1,30 @@+(ns metabase.indexes-rest.db+ "Application database queries for the indexes REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn table-index+ "The TableIndex with `id`, or nil."+ [id]+ (t2/select-one :model/TableIndex :id id))++(defn insert-table-index!+ "Insert the TableIndex `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/TableIndex row))++(defn set-table-index-structured!+ "Set the `structured` definition of the TableIndex with `id`."+ [id structured]+ (t2/update! :model/TableIndex id {:structured structured}))++(defn set-table-index-status!+ "Set the `status` of the TableIndex with `id`."+ [id status]+ (t2/update! :model/TableIndex id {:status status}))diff --git a/src/metabase/internal_stats/data_apps.clj b/src/metabase/internal_stats/data_apps.cljindex 36dd4328649..458bf9b8499 100644--- a/src/metabase/internal_stats/data_apps.clj+++ b/src/metabase/internal_stats/data_apps.clj@@ -1,9 +1,9 @@(ns metabase.internal-stats.data-apps(:require- [toucan2.core :as t2]))+ [metabase.internal-stats.db :as internal-stats.db]))(defn data-app-stats"How many data apps this instance actually serves: enabled and synced withouterror (`sync_error IS NULL`), matching what the UI treats as an openable app."[]- {:data-app-count (t2/count :data_app :enabled true :sync_error nil)})+ {:data-app-count (internal-stats.db/enabled-data-app-count)})diff --git a/src/metabase/internal_stats/db.clj b/src/metabase/internal_stats/db.cljnew file mode 100644index 00000000000..e2c76f79b55--- /dev/null+++ b/src/metabase/internal_stats/db.clj@@ -0,0 +1,232 @@+(ns metabase.internal-stats.db+ "Application database queries for the internal stats module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.internal-stats.util :as u]+ [metabase.models.interface :as mi]+ [toucan2.core :as t2]))++(defn enabled-data-app-count+ "The number of enabled data apps without a sync error."+ []+ (t2/count :data_app :enabled true :sync_error nil))++(defn embedded-dashboard-count+ "The number of unarchived Dashboards with embedding enabled."+ []+ (t2/count :model/Dashboard :enable_embedding true :archived false))++(defn embedded-question-count+ "The number of unarchived question Cards with embedding enabled."+ []+ (t2/count :model/Card :enable_embedding true :archived false :type :question))++(defn proxied-ai-usage-tokens-by-model+ "The model and total tokens of the proxied AiUsageLog rows on `date`, grouped by model."+ [date]+ (t2/select [:model/AiUsageLog :model [:%sum.total_tokens :tokens]]+ {:where [:and+ :ai_proxied+ [:= [:cast :created_at :date] [:cast date :date]]]+ :group-by [:model]}))++(defn proxied-ai-usage-tokens-on+ "The total tokens of the proxied AiUsageLog rows on `date`, or nil."+ [date]+ (t2/select-one-fn :sum+ [:model/AiUsageLog [:%sum.total_tokens :sum]]+ {:where [:and+ :ai_proxied+ [:= [:cast :created_at :date] [:cast date :date]]]}))++(defn proxied-metabot-user-message-count-on+ "The number of proxied, unforked user MetabotMessages on `date`."+ [date]+ (t2/select-one-fn :cnt+ [:model/MetabotMessage [:%count.id :cnt]]+ :role "user"+ :forked_from_message_id nil+ {:where [:and+ :ai_proxied+ [:= [:cast :created_at :date] [:cast date :date]]]}))++(defn proxied-metabot-user-count-on+ "The `:cnt` of distinct Users with proxied, unforked MetabotMessages on `date`."+ [date]+ ;; New rows stamp `metabot_message.user_id`; legacy rows fall back to the conversation's user.+ (t2/query-one {:select [[[:count [:distinct [:coalesce :m.user_id :c.user_id]]] :cnt]]+ :from [[:metabot_message :m]]+ :join [[:metabot_conversation :c] [:= :c.id :m.conversation_id]]+ :where [:and+ :ai_proxied+ [:= :m.forked_from_message_id nil]+ [:= [:cast :m.created_at :date] [:cast date :date]]]}))++(def ^:private sdk-embed-condition+ [:= :embedding_client "embedding-sdk-react"])++(def ^:private simple-embed-condition+ [:= :embedding_client "embedding-simple"])++(def ^:private interactive-embed-condition+ [:or+ [:= :embedding_client "embedding-iframe-full-app"]+ ;; legacy for backwards compatibility+ [:and [:= :embedding_client "embedding-iframe"]+ [:!= :executor_id nil]]])++(def ^:private static-embed-condition+ [:or+ [:= :embedding_client "embedding-iframe-static"]+ ;; legacy for backwards compatibility+ [:and [:= :embedding_client "embedding-iframe"]+ [:= :executor_id nil]]])++(def ^:private public-link-condition+ [:or+ [:= :embedding_client "embedding-public"]+ [:like :context "public-%"]])++(def ^:private query-execution-statistics+ [:model/QueryExecution+ [(u/count-case sdk-embed-condition) :sdk_embed]+ [(u/count-case interactive-embed-condition) :interactive_embed]+ [(u/count-case static-embed-condition) :static_embed]+ [(u/count-case public-link-condition) :public_link]+ [(u/count-case simple-embed-condition) :simple_embed]+ ;; fallthru: if a row does NOT match the above, it will match this condition and be counted internal.+ ;; COALESCE needed because when embedding_client IS NULL, the OR of equality checks returns NULL+ ;; (not FALSE), and NOT(NULL) = NULL which would skip the row instead of counting it.+ [(u/count-case [:not [:coalesce [:or sdk-embed-condition+ interactive-embed-condition+ simple-embed-condition+ static-embed-condition+ public-link-condition]+ [:inline false]]]) :internal]])++(defn query-execution-statistics-all-time+ "The QueryExecution counts per embedding client over all time."+ []+ (t2/select-one query-execution-statistics))++(defn query-execution-statistics-since+ "The QueryExecution counts per embedding client for executions started after `started-after`."+ [started-after]+ (t2/select-one query-execution-statistics {:where [:> :started_at started-after]}))++(defn query-execution-statistics-on+ "The QueryExecution counts per embedding client for executions started on the day of `date`."+ [date]+ (t2/select-one query-execution-statistics {:where [:= [:cast :started_at :date] [:cast date :date]]}))++(defn- and-not-nil+ ([not-nil-field]+ (and-not-nil nil not-nil-field))+ ([case-boolean not-nil-field]+ (cond->> [:!= not-nil-field nil]+ case-boolean (conj [:and case-boolean]))))++(defn- card-has-params+ []+ (condp = (mdb/db-type)+ :mysql [:json_contains_path+ :dataset_query+ ^:allow-raw-sql [:inline "one"]+ ^:allow-raw-sql [:inline "$.native.\"template-tags\".*"]]+ :postgres [:jsonb_path_exists+ [:cast :dataset_query :jsonb]+ ^:allow-raw-sql [:inline "$.native.\"template-tags\" ? (exists(@.*))"]]))++(defn- contains-embedding-param+ [param]+ (condp = (mdb/db-type)+ :mysql [:!= [:json_search+ :embedding_params+ ^:allow-raw-sql [:inline "one"]+ param]+ nil]+ :postgres [:jsonb_path_exists+ [:cast :embedding_params :jsonb]+ ^:allow-raw-sql [:inline "$.* ? (@ == $val)"]+ [:jsonb_build_object ^:allow-raw-sql [:inline "val"] param]]))++(def ^:private embedding-on [:= :enable_embedding [:inline true]])++(defn question-statistics-all-time+ "Aggregate counts of unarchived, non-internal Cards over all time: totals, native vs GUI, dashboard+ questions, embedded, publicly shared, and (where the app db supports JSON path queries) counts+ broken down by template-tag parameters and embedding-parameter locking."+ []+ (let [json-supported? (contains? #{:mysql :mariadb :postgres} (mdb/db-type))]+ (t2/select-one+ (into [:model/Card]+ (cond-> [[:%count.* :total]+ [(u/count-case [:= "native" :query_type])+ :native]+ [(u/count-case [:!= "native" :query_type])+ :gui]+ [(u/count-case [:!= :dashboard_id nil])+ :is_dashboard_question]+ [(u/count-case [:= :enable_embedding [:inline true]])+ :total_embedded]+ [(u/count-case (and-not-nil :public_uuid))+ :total_public]]+ ;; json_exists/contains which we use to query json encoded data stored in text+ ;; columns is not supported on h2 databases, so we exclude these stats when+ ;; the app db is h2.+ json-supported? (conj+ [(u/count-case (card-has-params))+ :with_params]+ [(u/count-case (and-not-nil (card-has-params) :public_uuid))+ :with_params_public]+ [(u/count-case [:and embedding-on (card-has-params)])+ :with_params_embedded]+ [(u/count-case [:and (contains-embedding-param "enabled")+ embedding-on])+ :with_enabled_params]+ [(u/count-case [:and (contains-embedding-param "locked")+ embedding-on])+ :with_locked_params]+ [(u/count-case [:and (contains-embedding-param "disabled")+ embedding-on])+ :with_disabled_params])))+ {:where (mi/exclude-internal-content-hsql :model/Card)})))++(defn active-personal-user-email-domain-count+ "The `:count` of distinct email domains of active personal Users."+ []+ (let [domain-expr (condp contains? (mdb/db-type)+ #{:postgres} [:split_part :email "@" [:inline 2]]+ #{:h2 :mysql} [:substring :email [:locate "@" :email]])]+ (t2/query-one {:select [[:%count.* :count]]+ :from [[^:allow-subquery+ {:select-distinct [[domain-expr]]+ :from [:core_user]+ :where [:and+ [:= :is_active true]+ [:= :type "personal"]]} :distinct_emails]]})))++(defn active-jwt-user-count+ "The number of active personal Users whose SSO source is JWT."+ []+ ;; Because this count is needed *during* token checks, it uses `t2/table-name` to avoid the `after-select` method on+ ;; users, which calls an EE method that needs ... a token check :|+ (t2/count (t2/table-name :model/User) :is_active true :sso_source "jwt" :type "personal"))++(defn active-tenant-user-count+ "The number of active personal Users belonging to a Tenant."+ []+ ;; Because this count is needed *during* token checks, it uses `t2/table-name` to avoid the `after-select` method on+ ;; users, which calls an EE method that needs ... a token check :|+ (t2/count (t2/table-name :model/User) :is_active true :tenant_id [:not= nil] :type "personal"))++(defn tenants-with-active-users-count+ "The `:count` of Tenants with at least one active personal User."+ []+ (t2/query-one {:select [[[:count [:distinct :tenant_id]] :count]]+ :from [(t2/table-name :model/User)]+ :where [:and+ [:= :is_active true]+ [:= :type "personal"]+ [:not= :tenant_id nil]]}))diff --git a/src/metabase/internal_stats/embedding.clj b/src/metabase/internal_stats/embedding.cljindex d93d0a210a2..c989c743312 100644--- a/src/metabase/internal_stats/embedding.clj+++ b/src/metabase/internal_stats/embedding.clj@@ -1,13 +1,13 @@(ns metabase.internal-stats.embedding(:require- [toucan2.core :as t2]))+ [metabase.internal-stats.db :as internal-stats.db]))(defn embedding-dashboard-count"Count dashboards enabled for embedding"[]- (t2/count :model/Dashboard :enable_embedding true :archived false))+ (internal-stats.db/embedded-dashboard-count))(defn embedding-question-count"Count question cards enabled for embedding"[]- (t2/count :model/Card :enable_embedding true :archived false :type :question))+ (internal-stats.db/embedded-question-count))diff --git a/src/metabase/internal_stats/metabot.clj b/src/metabase/internal_stats/metabot.cljindex 96f57caf4a1..ebaa72036b7 100644--- a/src/metabase/internal_stats/metabot.clj+++ b/src/metabase/internal_stats/metabot.clj@@ -2,16 +2,12 @@(:require[clojure.string :as str][java-time.api :as t]- [toucan2.core :as t2]))+ [metabase.internal-stats.db :as internal-stats.db]))(defn- usage-by-model"Aggregate combined tokens by provider:model for a given UTC date."[date-utc]- (let [rows (t2/select [:model/AiUsageLog :model [:%sum.total_tokens :tokens]]- {:where [:and- :ai_proxied- [:= [:cast :created_at :date] [:cast date-utc :date]]]- :group-by [:model]})]+ (let [rows (internal-stats.db/proxied-ai-usage-tokens-by-model date-utc)](->> (for [{:keys [model tokens]} rows:let [k (-> model(str/replace-first "metabase/" "")@@ -27,36 +23,18 @@[](let [today-utc (t/offset-date-time (t/zone-offset "+00"))yesterday-utc (t/minus today-utc (t/days 1))- user-id-expr [:coalesce :m.user_id :c.user_id]- tokens (or (t2/select-one-fn :sum- [:model/AiUsageLog [:%sum.total_tokens :sum]]- {:where [:and- :ai_proxied- [:= [:cast :created_at :date] [:cast yesterday-utc :date]]]})- 0)+ tokens (or (internal-stats.db/proxied-ai-usage-tokens-on yesterday-utc) 0)rolling-usage (usage-by-model today-utc)](when (or (pos? tokens) (seq rolling-usage))(cond-> {}(pos? tokens)(merge {:metabot-tokens (long tokens):metabot-usage (usage-by-model yesterday-utc)- :metabot-queries (t2/select-one-fn :cnt- [:model/MetabotMessage [:%count.id :cnt]]- :role "user"- :forked_from_message_id nil- {:where [:and- :ai_proxied- [:= [:cast :created_at :date] [:cast yesterday-utc :date]]]})+ :metabot-queries (internal-stats.db/proxied-metabot-user-message-count-on yesterday-utc);; New rows stamp `metabot_message.user_id`; legacy rows fall back;; to `metabot_conversation.user_id` so historical usage doesn't;; disappear until old messages are backfilled.- :metabot-users (:cnt (t2/query-one {:select [[[:count [:distinct user-id-expr]] :cnt]]- :from [[:metabot_message :m]]- :join [[:metabot_conversation :c] [:= :c.id :m.conversation_id]]- :where [:and- :ai_proxied- [:= :m.forked_from_message_id nil]- [:= [:cast :m.created_at :date] [:cast yesterday-utc :date]]]}))+ :metabot-users (:cnt (internal-stats.db/proxied-metabot-user-count-on yesterday-utc)):metabot-usage-date (str (t/local-date yesterday-utc))})(seq rolling-usage)(merge {:metabot-rolling-usage rolling-usagediff --git a/src/metabase/internal_stats/query_executions.clj b/src/metabase/internal_stats/query_executions.cljindex ad6cd156097..ea855dbad58 100644--- a/src/metabase/internal_stats/query_executions.clj+++ b/src/metabase/internal_stats/query_executions.clj@@ -1,57 +1,14 @@(ns metabase.internal-stats.query-executions(:require[java-time.api :as t]- [metabase.internal-stats.util :as u]- [toucan2.core :as t2]))--(def ^:private sdk-embed-condition- [:= :embedding_client "embedding-sdk-react"])--(def ^:private simple-embed-condition- [:= :embedding_client "embedding-simple"])--(def ^:private interactive-embed-condition- [:or- [:= :embedding_client "embedding-iframe-full-app"]- ;; legacy for backwards compatibility- [:and [:= :embedding_client "embedding-iframe"]- [:!= :executor_id nil]]])--(def ^:private static-embed-condition- [:or- [:= :embedding_client "embedding-iframe-static"]- ;; legacy for backwards compatibility- [:and [:= :embedding_client "embedding-iframe"]- [:= :executor_id nil]]])--(def ^:private public-link-condition- [:or- [:= :embedding_client "embedding-public"]- [:like :context "public-%"]])--(def ^:private query-execution-statistics- [:model/QueryExecution- [(u/count-case sdk-embed-condition) :sdk_embed]- [(u/count-case interactive-embed-condition) :interactive_embed]- [(u/count-case static-embed-condition) :static_embed]- [(u/count-case public-link-condition) :public_link]- [(u/count-case simple-embed-condition) :simple_embed]- ;; fallthru: if a row does NOT match the above, it will match this condition and be counted internal.- ;; COALESCE needed because when embedding_client IS NULL, the OR of equality checks returns NULL- ;; (not FALSE), and NOT(NULL) = NULL which would skip the row instead of counting it.- [(u/count-case [:not [:coalesce [:or sdk-embed-condition- interactive-embed-condition- simple-embed-condition- static-embed-condition- public-link-condition]- [:inline false]]]) :internal]])+ [metabase.internal-stats.db :as internal-stats.db]))(defn query-executions-all-time-and-last-24h"Calculate query executions for the entire available history and over the last 24 hours from now."[]- (let [qe (t2/select-one query-execution-statistics)+ (let [qe (internal-stats.db/query-execution-statistics-all-time)one-day-ago (t/minus (t/offset-date-time) (t/days 1))- qe-24h (t2/select-one query-execution-statistics {:where [:> :started_at one-day-ago]})]+ qe-24h (internal-stats.db/query-execution-statistics-since one-day-ago)]{:query-executions qe:query-executions-24h qe-24h}))@@ -59,7 +16,6 @@"Calculate query executions over a window of the the previous UTC day 00:00-23:59"[](let [yesterday-utc (t/minus (t/offset-date-time (t/zone-offset "+00")) (t/days 1))]- (-> (t2/select-one query-execution-statistics- {:where [:= [:cast :started_at :date] [:cast yesterday-utc :date]]})+ (-> (internal-stats.db/query-execution-statistics-on yesterday-utc)(dissoc :row_count)(update-keys #(keyword (str "query_executions_" (name %)))))))diff --git a/src/metabase/internal_stats/questions.clj b/src/metabase/internal_stats/questions.cljindex 0a881f5bf05..db6c4c572f6 100644--- a/src/metabase/internal_stats/questions.clj+++ b/src/metabase/internal_stats/questions.clj@@ -1,76 +1,8 @@(ns metabase.internal-stats.questions(:require- [metabase.app-db.core :as db]- [metabase.internal-stats.util :as u]- [metabase.models.interface :as mi]- [toucan2.core :as t2]))--(defn- and-not-nil- ([not-nil-field]- (and-not-nil nil not-nil-field))- ([case-boolean not-nil-field]- (cond->> [:!= not-nil-field nil]- case-boolean (conj [:and case-boolean]))))--(defn- card-has-params- []- (condp = (db/db-type)- :mysql [:json_contains_path- :dataset_query- ^:allow-raw-sql [:inline "one"]- ^:allow-raw-sql [:inline "$.native.\"template-tags\".*"]]- :postgres [:jsonb_path_exists- [:cast :dataset_query :jsonb]- ^:allow-raw-sql [:inline "$.native.\"template-tags\" ? (exists(@.*))"]]))--(defn- contains-embedding-param- [param]- (condp = (db/db-type)- :mysql [:!= [:json_search- :embedding_params- ^:allow-raw-sql [:inline "one"]- param]- nil]- :postgres [:jsonb_path_exists- [:cast :embedding_params :jsonb]- ^:allow-raw-sql [:inline "$.* ? (@ == $val)"]- [:jsonb_build_object ^:allow-raw-sql [:inline "val"] param]]))--(def ^:private embedding-on [:= :enable_embedding [:inline true]])+ [metabase.internal-stats.db :as internal-stats.db]))(defn question-statistics-all-time"Get metrics based on questions "[]- (let [json-supported? (contains? #{:mysql :mariadb :postgres} (db/db-type))]- (t2/select-one (cond-> [:model/Card- [:%count.* :total]- [(u/count-case [:= "native" :query_type])- :native]- [(u/count-case [:!= "native" :query_type])- :gui]- [(u/count-case [:!= :dashboard_id nil])- :is_dashboard_question]- [(u/count-case [:= :enable_embedding [:inline true]])- :total_embedded]- [(u/count-case (and-not-nil :public_uuid))- :total_public]]- ;; json_exists/contains which we use to query json encoded data stored in text- ;; columns is not supported on h2 databases, so we exclude these stats when- ;; the app db is h2.- json-supported? (conj- [(u/count-case (card-has-params))- :with_params]- [(u/count-case (and-not-nil (card-has-params) :public_uuid))- :with_params_public]- [(u/count-case [:and embedding-on (card-has-params)])- :with_params_embedded]- [(u/count-case [:and (contains-embedding-param "enabled")- embedding-on])- :with_enabled_params]- [(u/count-case [:and (contains-embedding-param "locked")- embedding-on])- :with_locked_params]- [(u/count-case [:and (contains-embedding-param "disabled")- embedding-on])- :with_disabled_params]))- {:where (mi/exclude-internal-content-hsql :model/Card)})))+ (internal-stats.db/question-statistics-all-time))diff --git a/src/metabase/internal_stats/users.clj b/src/metabase/internal_stats/users.cljindex 2b39d547f87..2ec8d92f884 100644--- a/src/metabase/internal_stats/users.clj+++ b/src/metabase/internal_stats/users.clj@@ -1,41 +1,23 @@(ns metabase.internal-stats.users(:require- [metabase.app-db.core :as db]- [toucan2.core :as t2]))+ [metabase.internal-stats.db :as internal-stats.db]))(defn email-domain-count"Count all unique normalized domains found in active user emails"[]- (:count (t2/query-one {:select [[:%count.* :count]]- :from [[^:allow-subquery- {:select-distinct (condp contains? (db/db-type)- #{:postgres} [[[:split_part :email "@" [:inline 2]]]]- #{:h2 :mysql} [[[:substring :email [:locate "@" :email]]]])- :from [:core_user]- :where [:and- [:= :is_active true]- [:= :type "personal"]]} :distinct_emails]]})))+ (:count (internal-stats.db/active-personal-user-email-domain-count)))(defn external-users-count"Number of users with sso-source: JWT as a proxy for tenant users of embedded views"[]- ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid the `after-select` method on- ;; users, which calls an EE method that needs ... a token check :|- (t2/count (t2/table-name :model/User) :is_active true :sso_source "jwt" :type "personal"))+ (internal-stats.db/active-jwt-user-count))(defn tenant-users-count"Number of active users that belong to a tenant."[]- ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid the `after-select` method on- ;; users, which calls an EE method that needs ... a token check :|- (t2/count (t2/table-name :model/User) :is_active true :tenant_id [:not= nil] :type "personal"))+ (internal-stats.db/active-tenant-user-count))(defn tenants-with-active-users-count"Number of tenants that have at least one active user."[]- (:count (t2/query-one {:select [[[:count [:distinct :tenant_id]] :count]]- :from [(t2/table-name :model/User)]- :where [:and- [:= :is_active true]- [:= :type "personal"]- [:not= :tenant_id nil]]})))+ (:count (internal-stats.db/tenants-with-active-users-count)))diff --git a/src/metabase/lib/metadata/protocols.cljc b/src/metabase/lib/metadata/protocols.cljcindex 52fe690e96a..cdd1f25a3e1 100644--- a/src/metabase/lib/metadata/protocols.cljc+++ b/src/metabase/lib/metadata/protocols.cljc@@ -67,7 +67,7 @@metadata providers other than [[metabase.lib-be.metadata.jvm/application-database-metadata-provider]], whichimplements equivalent filter logic in SQL.- This should match [[metabase.lib-be.metadata.jvm/metadata-spec->honey-sql]] as closely as+ This should match [[metabase.lib-be.db/metadata-where]] as closely aspossible."[{metadata-type :lib/type, id-set :id, name-set :name, :keys [table-ids card-ids include-sensitive?], :as _metadata-spec} :- ::metadata-spec](let [active-only? (not (or id-set name-set))diff --git a/src/metabase/lib_be/db.clj b/src/metabase/lib_be/db.cljnew file mode 100644index 00000000000..e6a393397e9--- /dev/null+++ b/src/metabase/lib_be/db.clj@@ -0,0 +1,166 @@+(ns metabase.lib-be.db+ "Application database queries for the lib backend module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [metabase.lib.metadata.protocols :as lib.metadata.protocols]+ [metabase.lib.schema.id :as lib.schema.id]+ [metabase.util.malli :as mu]+ [toucan2.core :as t2]))++(defn card-database-ids+ "The `:id`, `:database_id`, and `:card_schema` of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :database_id :card_schema] :id [:in card-ids]))++(defn database+ "The `:metadata/database` with `database-id`, or nil."+ [database-id]+ (t2/select-one :metadata/database database-id))++;;; ----------------------------------------------- Lib metadata -----------------------------------------------+;;;+;;; Each `:metadata/*` type below is a distinct Toucan 2 model. `metadata-where` is a private helper shared by the+;;; per-type functions; it is never exposed, so callers always pick the model by calling the right function.++(defn- db-id-key [metadata-type]+ (case metadata-type+ :metadata/table :db_id+ :metadata/column :table/db_id+ :metadata/card :card/database_id+ :metadata/metric :database_id+ :metadata/segment :table/db_id+ :metadata/measure :table/db_id+ :metadata/native-query-snippet nil+ :metadata/transform nil))++(defn- id-key [metadata-type]+ (case metadata-type+ :metadata/table :id+ :metadata/column :field/id+ :metadata/card :card/id+ :metadata/metric :id+ :metadata/segment :segment/id+ :metadata/measure :measure/id+ :metadata/native-query-snippet :id+ :metadata/transform :id))++(defn- name-key [metadata-type]+ (case metadata-type+ :metadata/table :name+ :metadata/column :field/name+ :metadata/card :card/name+ :metadata/metric :name+ :metadata/segment :segment/name+ :metadata/measure :measure/name+ :metadata/native-query-snippet :name+ :metadata/transform :name))++(defn- table-id-key [metadata-type]+ ;; types not in the case statement do not support Table ID+ (case metadata-type+ :metadata/column :field/table_id+ :metadata/metric :table_id+ :metadata/segment :segment/table_id+ :metadata/measure :measure/table_id))++(defn- card-id-key [metadata-type]+ ;; types not in the case statement do not support Card ID+ (case metadata-type+ :metadata/metric :source_card_id))++(defn- active-only-where [metadata-type include-sensitive?]+ (case metadata-type+ :metadata/table+ [:and+ [:= :active true]+ [:or+ [:= :visibility_type nil]+ [:not-in :visibility_type ["hidden" "technical" "cruft"]]]]++ :metadata/column+ (let [excluded-visibility-types (cond-> ["retired"]+ (not include-sensitive?) (conj "sensitive"))]+ [:and+ [:= :field/active true]+ [:or+ [:= :field/visibility_type nil]+ [:not-in :field/visibility_type excluded-visibility-types]]])++ :metadata/card+ [:= :card/archived false]++ :metadata/metric+ [:= :archived false]++ :metadata/segment+ [:= :segment/archived false]++ :metadata/measure+ [:= :measure/archived false]++ #_else+ nil))++(mu/defn- metadata-where :- [:map {:closed true} [:where {:optional true} vector?]]+ "The `:where` map picking out the `metadata-type` rows for `database-id`, narrowed by `metadata-spec`'s `:id`,+ `:name`, `:table-ids`, and `:card-ids` (whichever apply to `metadata-type`), or restricted to active/visible+ rows when none of `:id`/`:name` is given (`:include-sensitive?` controlling whether sensitive columns count+ as active). This should match [[metabase.lib.metadata.protocols/default-spec-filter-xform]] as closely as+ possible."+ [metadata-type :- ::lib.metadata.protocols/metadata-type-excluding-database+ database-id :- ::lib.schema.id/database+ {id-set :id, name-set :name, :keys [table-ids card-ids include-sensitive?]} :- ::lib.metadata.protocols/metadata-spec]+ (let [database-id-key (db-id-key metadata-type)+ active-only? (not (or id-set name-set))+ metric? (= metadata-type :metadata/metric)+ where-clauses (cond-> []+ database-id-key (conj [:= database-id-key database-id])+ id-set (conj [:in (id-key metadata-type) id-set])+ name-set (conj [:in (name-key metadata-type) name-set])+ table-ids (conj [:in (table-id-key metadata-type) table-ids])+ card-ids (conj [:in (card-id-key metadata-type) card-ids])+ active-only? (conj (active-only-where metadata-type include-sensitive?))+ metric? (conj [:= :type "metric"])+ (and metric? table-ids) (conj [:= :source_card_id nil]))]+ (reduce sql.helpers/where {} where-clauses)))++(defn tables+ "The `:metadata/table` rows for `database-id` picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/table (metadata-where :metadata/table database-id metadata-spec)))++(defn columns+ "The `:metadata/column` rows for `database-id` picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/column (metadata-where :metadata/column database-id metadata-spec)))++(defn cards+ "The `:metadata/card` rows for `database-id` picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/card (metadata-where :metadata/card database-id metadata-spec)))++(defn metrics+ "The `:metadata/metric` rows for `database-id` picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/metric (metadata-where :metadata/metric database-id metadata-spec)))++(defn segments+ "The `:metadata/segment` rows for `database-id` picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/segment (metadata-where :metadata/segment database-id metadata-spec)))++(defn measures+ "The `:metadata/measure` rows for `database-id` picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/measure (metadata-where :metadata/measure database-id metadata-spec)))++(defn native-query-snippets+ "The `:metadata/native-query-snippet` rows picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/native-query-snippet (metadata-where :metadata/native-query-snippet database-id metadata-spec)))++(defn transforms+ "The `:metadata/transform` rows picked out by `metadata-spec`."+ [database-id metadata-spec]+ (t2/select :metadata/transform (metadata-where :metadata/transform database-id metadata-spec)))diff --git a/src/metabase/lib_be/metadata/bootstrap.clj b/src/metabase/lib_be/metadata/bootstrap.cljindex 74e3b34f2e1..129964590c7 100644--- a/src/metabase/lib_be/metadata/bootstrap.clj+++ b/src/metabase/lib_be/metadata/bootstrap.clj@@ -1,5 +1,6 @@(ns metabase.lib-be.metadata.bootstrap(:require+ [metabase.lib-be.db :as lib-be.db][metabase.lib.core :as lib][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.lib.schema.id :as lib.schema.id]@@ -8,7 +9,7 @@[metabase.util.i18n :as i18n][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.performance :as perf]))(mu/defn- source-card-id-for-mbql5-query :- [:maybe ::lib.schema.id/card][query :- :map]@@ -28,14 +29,12 @@(defn- bootstrap-metadatas [{metadata-type :lib/type, id-set :id, :as _metadata-spec}](when (and (seq id-set)(= metadata-type :metadata/card))- (t2/select-fn-vec- (fn [card]- {:lib/type :metadata/card- :id (:id card)- :name (format "Card #%d" (:id card))- :database-id (:database_id card)})- [:model/Card :id :database_id :card_schema]- :id [:in (set id-set)])))+ (perf/mapv (fn [card]+ {:lib/type :metadata/card+ :id (:id card)+ :name (format "Card #%d" (:id card))+ :database-id (:database_id card)})+ (lib-be.db/card-database-ids (set id-set)))))(deftype ^:private BootstrapMetadataProvider []lib.metadata.protocols/MetadataProviderdiff --git a/src/metabase/lib_be/metadata/jvm.clj b/src/metabase/lib_be/metadata/jvm.cljindex 71e2221a6c4..0a6ece26e98 100644--- a/src/metabase/lib_be/metadata/jvm.clj+++ b/src/metabase/lib_be/metadata/jvm.clj@@ -6,7 +6,7 @@[clojure.core.cache :as cache][clojure.core.cache.wrapped :as cache.wrapped][clojure.string :as str]- [honey.sql.helpers :as sql.helpers]+ [metabase.lib-be.db :as lib-be.db][metabase.lib.metadata.cached-provider :as lib.metadata.cached-provider][metabase.lib.metadata.invocation-tracker :as lib.metadata.invocation-tracker][metabase.lib.metadata.protocols :as lib.metadata.protocols]@@ -429,120 +429,26 @@`lib.metadata.protocols/database`UncachedApplicationDatabaseMetadataProvider){})))- (t2/select-one :metadata/database database-id))--(defn- db-id-key [metadata-type]- (case metadata-type- :metadata/table :db_id- :metadata/column :table/db_id- :metadata/card :card/database_id- :metadata/metric :database_id- :metadata/segment :table/db_id- :metadata/measure :table/db_id- :metadata/native-query-snippet nil- :metadata/transform nil))--(defn- id-key [metadata-type]- (case metadata-type- :metadata/table :id- :metadata/column :field/id- :metadata/card :card/id- :metadata/metric :id- :metadata/segment :segment/id- :metadata/measure :measure/id- :metadata/native-query-snippet :id- :metadata/transform :id))--(defn- name-key [metadata-type]- (case metadata-type- :metadata/table :name- :metadata/column :field/name- :metadata/card :card/name- :metadata/metric :name- :metadata/segment :segment/name- :metadata/measure :measure/name- :metadata/native-query-snippet :name- :metadata/transform :name))--(defn- table-id-key [metadata-type]- ;; types not in the case statement do not support Table ID- (case metadata-type- :metadata/column :field/table_id- :metadata/metric :table_id- :metadata/segment :segment/table_id- :metadata/measure :measure/table_id))--(defn- card-id-key [metadata-type]- ;; types not in the case statement do not support Card ID- (case metadata-type- :metadata/metric :source_card_id))--(defn- active-only-honeysql-filter [metadata-type {:keys [include-sensitive?]}]- (case metadata-type- :metadata/table- [:and- [:= :active true]- [:or- [:= :visibility_type nil]- [:not-in :visibility_type ["hidden" "technical" "cruft"]]]]-- :metadata/column- (let [excluded-visibility-types (cond-> ["retired"]- (not include-sensitive?) (conj "sensitive"))]- [:and- [:= :field/active true]- [:or- [:= :field/visibility_type nil]- [:not-in :field/visibility_type excluded-visibility-types]]])-- :metadata/card- [:= :card/archived false]-- :metadata/metric- [:= :archived false]-- :metadata/segment- [:= :segment/archived false]-- :metadata/measure- [:= :measure/archived false]-- #_else- nil))--(mu/defn- metadata-spec->honey-sql :- [:map- {:closed true}- [:where {:optional true} vector?]]- "This should match [[metabase.lib.metadata.protocols/default-spec-filter-xform]] as closely as possible."- [database-id :- ::lib.schema.id/database- {metadata-type :lib/type, id-set :id, name-set :name, :keys [table-ids card-ids include-sensitive?], :as _metadata-spec} :- ::lib.metadata.protocols/metadata-spec]- (let [database-id-key (db-id-key metadata-type)- active-only? (not (or id-set name-set))- metric? (= metadata-type :metadata/metric)- where-clauses (cond-> []- database-id-key (conj [:= database-id-key database-id])- id-set (conj [:in (id-key metadata-type) id-set])- name-set (conj [:in (name-key metadata-type) name-set])- table-ids (conj [:in (table-id-key metadata-type) table-ids])- card-ids (conj [:in (card-id-key metadata-type) card-ids])- active-only? (conj (active-only-honeysql-filter metadata-type {:include-sensitive? include-sensitive?}))- metric? (conj [:= :type "metric"])- (and metric? table-ids) (conj [:= :source_card_id nil]))]- (reduce- sql.helpers/where- {}- where-clauses)))+ (lib-be.db/database database-id))(mu/defn- metadatas[database-id :- ::lib.schema.id/database{metadata-type :lib/type, :as metadata-spec} :- ::lib.metadata.protocols/metadata-spec]- (let [query (metadata-spec->honey-sql database-id metadata-spec)]- (lib.util/recover- (fn [] (t2/select metadata-type query))- (fn [e]- (throw (ex-info "Error fetching metadata with spec"- {:metadata-spec metadata-spec, :query query}- e))))))+ (lib.util/recover+ (fn []+ (case metadata-type+ :metadata/table (lib-be.db/tables database-id metadata-spec)+ :metadata/column (lib-be.db/columns database-id metadata-spec)+ :metadata/card (lib-be.db/cards database-id metadata-spec)+ :metadata/metric (lib-be.db/metrics database-id metadata-spec)+ :metadata/segment (lib-be.db/segments database-id metadata-spec)+ :metadata/measure (lib-be.db/measures database-id metadata-spec)+ :metadata/native-query-snippet (lib-be.db/native-query-snippets database-id metadata-spec)+ :metadata/transform (lib-be.db/transforms database-id metadata-spec)))+ (fn [e]+ (throw (ex-info "Error fetching metadata with spec"+ {:metadata-spec metadata-spec}+ e)))))(p/deftype+ UncachedApplicationDatabaseMetadataProvider [database-id]lib.metadata.protocols/MetadataProviderdiff --git a/src/metabase/lib_metric/db.clj b/src/metabase/lib_metric/db.cljnew file mode 100644index 00000000000..ad4d9c1b000--- /dev/null+++ b/src/metabase/lib_metric/db.clj@@ -0,0 +1,57 @@+(ns metabase.lib-metric.db+ "Application database queries for the lib metric module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [toucan2.core :as t2]))++(defn fields+ "The Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field :id [:in field-ids]))++(defn card-table-and-database-id+ "The `:table_id` and `:database_id` of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :table_id :database_id] card-id))++(defn table-database-id+ "The Database id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id :model/Table table-id))++(defn- metric-where+ "The `:where` map for the metric Cards picked out by `metadata-spec` (its `:id`, `:name`,+ `:table-ids`, and `:card-ids` keys), or unarchived ones when neither `:id` nor `:name` is given."+ [{id-set :id, name-set :name, :keys [table-ids card-ids]}]+ (let [active-only? (not (or id-set name-set))]+ (reduce sql.helpers/where {}+ (cond-> [[:= :type "metric"]]+ id-set (conj [:in :id id-set])+ name-set (conj [:in :name name-set])+ table-ids (conj [:in :table_id table-ids])+ table-ids (conj [:= :source_card_id nil])+ card-ids (conj [:in :source_card_id card-ids])+ active-only? (conj [:= :archived false])))))++(defn metrics+ "The metric Cards (`:metadata/metric`) picked out by `metadata-spec`."+ [metadata-spec]+ (t2/select :metadata/metric (metric-where metadata-spec)))++(defn- measure-where+ "The `:where` map for the `:metadata/measure` rows picked out by `metadata-spec` (its `:id`, `:name`, and+ `:table-ids` keys), or unarchived ones when neither `:id` nor `:name` is given."+ [{id-set :id, name-set :name, :keys [table-ids]}]+ (let [active-only? (not (or id-set name-set))]+ (reduce sql.helpers/where {}+ (cond-> []+ id-set (conj [:in :measure/id id-set])+ name-set (conj [:in :measure/name name-set])+ table-ids (conj [:in :measure/table_id table-ids])+ active-only? (conj [:= :measure/archived false])))))++(defn measures+ "The `:metadata/measure` rows picked out by `metadata-spec`."+ [metadata-spec]+ (t2/select :metadata/measure (measure-where metadata-spec)))diff --git a/src/metabase/lib_metric/dimension/jvm.clj b/src/metabase/lib_metric/dimension/jvm.cljindex ff79905f55f..1df7c545909 100644--- a/src/metabase/lib_metric/dimension/jvm.clj+++ b/src/metabase/lib_metric/dimension/jvm.clj@@ -4,11 +4,11 @@via a direct database lookup, which is only available on the JVM."(:require[metabase.lib-be.core :as lib-be]+ [metabase.lib-metric.db :as lib-metric.db][metabase.lib-metric.metadata.provider :as lib-metric.provider][metabase.lib.core :as lib][metabase.lib.util :as lib.util]- [metabase.util.performance :as perf]- [toucan2.core :as t2])+ [metabase.util.performance :as perf])(:import (java.util UUID)))(set! *warn-on-reflection* true)@@ -25,7 +25,7 @@[(:id field)(lib/infer-has-field-values(lib-be/instance->metadata field :metadata/column))]))- (t2/select :model/Field :id [:in col-ids])))]+ (lib-metric.db/fields col-ids)))](perf/mapv (fn [col](if-let [hfv (get field-values-map (:id col))](assoc col :has-field-values hfv)@@ -92,7 +92,7 @@(lib-metric.provider/database-provider-for-table mp table-id))(when-let [card-id (lib.util/source-card-id query-with-mp)](when-let [{:keys [table_id database_id]}- (t2/select-one [:model/Card :table_id :database_id] card-id)]+ (lib-metric.db/card-table-and-database-id card-id)](or (when table_id(lib-metric.provider/database-provider-for-table mp table_id))(when database_iddiff --git a/src/metabase/lib_metric/metadata/jvm.clj b/src/metabase/lib_metric/metadata/jvm.cljindex 6726b113818..667f6e4f158 100644--- a/src/metabase/lib_metric/metadata/jvm.clj+++ b/src/metabase/lib_metric/metadata/jvm.clj@@ -5,17 +5,16 @@It fetches metrics from the Card table (type='metric') without database scoping,and routes table/column metadata requests to database-specific providers."(:require- [honey.sql.helpers :as sql.helpers][medley.core :as m][metabase.lib-be.core :as lib-be]+ [metabase.lib-metric.db :as lib-metric.db][metabase.lib-metric.dimension :as lib-metric.dimension][metabase.lib-metric.dimension.jvm :as lib-metric.dimension.jvm][metabase.lib-metric.metadata.provider :as provider][metabase.lib.metadata.protocols :as lib.metadata.protocols][metabase.settings.core :as setting][metabase.util.malli :as mu]- [metabase.util.memoize :as memoize]- [toucan2.core :as t2]))+ [metabase.util.memoize :as memoize]))(set! *warn-on-reflection* true)@@ -24,34 +23,19 @@[](memoize/lru(fn [table-id]- (t2/select-one-fn :db_id :model/Table table-id))+ (lib-metric.db/table-database-id table-id)):lru/threshold 1000))-(defn- metric-spec->honey-sql- "Build HoneySQL WHERE clause for fetching metrics.- Metrics are Cards with type='metric' - not scoped to any database."- [{id-set :id, name-set :name, :keys [table-ids card-ids], :as _metadata-spec}]- (let [active-only? (not (or id-set name-set))- where-clauses (cond-> [[:= :type "metric"]]- id-set (conj [:in :id id-set])- name-set (conj [:in :name name-set])- table-ids (conj [:in :table_id table-ids])- table-ids (conj [:= :source_card_id nil])- card-ids (conj [:in :source_card_id card-ids])- active-only? (conj [:= :archived false]))]- (reduce sql.helpers/where {} where-clauses)))-(defn- fetch-metrics"Fetch metrics matching spec, not scoped to any database.Returns metrics as metadata objects with :lib/type :metadata/metric."[metadata-spec]- (let [query (metric-spec->honey-sql metadata-spec)]- (try- (t2/select :metadata/metric query)- (catch Throwable e- (throw (ex-info "Error fetching metrics with spec"- {:metadata-spec metadata-spec, :query query}- e))))))+ (try+ (lib-metric.db/metrics metadata-spec)+ (catch Throwable e+ (throw (ex-info "Error fetching metrics with spec"+ {:metadata-spec metadata-spec}+ e)))));;; ------------------------------------------------- Dimension Fetching -------------------------------------------------@@ -74,27 +58,15 @@(get mappings-by-dim-id (:id dim))(assoc :dimension-mapping (get mappings-by-dim-id (:id dim))))))))-(defn- measure-spec->honey-sql- "Build HoneySQL WHERE clause for fetching measures."- [{id-set :id, name-set :name, :keys [table-ids], :as _metadata-spec}]- (let [active-only? (not (or id-set name-set))- where-clauses (cond-> []- id-set (conj [:in :measure/id id-set])- name-set (conj [:in :measure/name name-set])- table-ids (conj [:in :measure/table_id table-ids])- active-only? (conj [:= :measure/archived false]))]- (reduce sql.helpers/where {} where-clauses)))-(defn- fetch-measures-for-dimensions"Fetch measures matching spec for dimension extraction."[metadata-spec]- (let [query (measure-spec->honey-sql metadata-spec)]- (try- (t2/select :metadata/measure query)- (catch Throwable e- (throw (ex-info "Error fetching measures for dimensions"- {:metadata-spec metadata-spec, :query query}- e))))))+ (try+ (lib-metric.db/measures metadata-spec)+ (catch Throwable e+ (throw (ex-info "Error fetching measures for dimensions"+ {:metadata-spec metadata-spec}+ e)))))(defn- fetch-dimensions"Fetch dimensions by aggregating from metrics and measures.diff --git a/src/metabase/llm/api.clj b/src/metabase/llm/api.cljindex 1576562dec2..b15c4995b86 100644--- a/src/metabase/llm/api.clj+++ b/src/metabase/llm/api.clj@@ -12,14 +12,14 @@[metabase.llm.anthropic :as llm.anthropic][metabase.llm.api.provider][metabase.llm.context :as llm.context]+ [metabase.llm.db :as llm.db][metabase.llm.settings :as llm.settings][metabase.metabot.core :as metabot][metabase.request.core :as request][metabase.util :as u][metabase.util.i18n :refer [tru]][stencil.core :as stencil]- [throttle.core :as throttle]- [toucan2.core :as t2])+ [throttle.core :as throttle])(:import(java.time LocalDateTime)(java.time.format DateTimeFormatter)))@@ -41,7 +41,7 @@"Get the engine keyword for a database."[database-id](when database-id- (t2/select-one-fn :engine :model/Database :id database-id)))+ (llm.db/database-engine database-id)))(def ^:private load-dialect-instructions"Load dialect-specific instructions from resources, if available.diff --git a/src/metabase/llm/context.clj b/src/metabase/llm/context.cljindex 0e6b728ea68..a53882e3e37 100644--- a/src/metabase/llm/context.clj+++ b/src/metabase/llm/context.clj@@ -7,16 +7,15 @@[metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.llm.db :as llm.db][metabase.metabot.metadata-perms :as metabot.perms][metabase.models.interface :as mi][metabase.parameters.field-values :as params.field-values][metabase.request.core :as request][metabase.sql-tools.core :as sql-tools][metabase.sync.core :as sync]- [metabase.util :as u][metabase.util.log :as log]- [metabase.warehouse-schema.models.field-values :as field-values]- [toucan2.core :as t2])+ [metabase.warehouse-schema.models.field-values :as field-values])(:import(java.io StringWriter Writer)))@@ -43,17 +42,6 @@(parse-long id-str)))set)))-(defn- table-match-clause- "Build a WHERE clause to match a table by name and optionally schema.- When schema is present, matches both; otherwise matches just the table name."- [{:keys [schema table]}]- (let [table-lower (u/lower-case-en table)]- (if schema- [:and- [:= [:lower :name] table-lower]- [:= [:lower :schema] (u/lower-case-en schema)]]- [:= [:lower :name] table-lower])))-(defn extract-tables-from-sql"Extract table IDs from a raw SQL string.@@ -67,15 +55,10 @@[database-id sql-string](if (and database-id (seq sql-string))(try- (let [driver (t2/select-one-fn :engine :model/Database :id database-id)+ (let [driver (llm.db/database-engine database-id)tables (sql-tools/referenced-tables-raw driver sql-string)](if (seq tables)- (let [match-clauses (mapv table-match-clause tables)- matched-tables (t2/select :model/Table- {:where [:and- [:= :db_id database-id]- [:= :active true]- (into [:or] match-clauses)]})]+ (let [matched-tables (llm.db/active-tables-matching database-id tables)](into #{} (map :id) matched-tables))#{}))(catch Exception e@@ -104,28 +87,14 @@Returns a map of table-id -> table record."[database-id table-ids](when (seq table-ids)- (let [{:keys [clause with]} (mi/visible-filter-clause- :model/Table :id- {:user-id api/*current-user-id*- :is-superuser? api/*is-superuser?*}- {:perms/view-data :unrestricted- :perms/create-queries :query-builder-and-native})- tables (t2/select :model/Table- :id [:in table-ids]- :db_id database-id- :active true- :visibility_type nil- (cond-> {:where clause}- with (assoc :with with)))]+ (let [tables (llm.db/visible-tables table-ids database-id api/*current-user-id* api/*is-superuser?*)](into {} (map (juxt :id identity)) tables))))(defn get-accessible-card-ids"Return readable, non-archived Card IDs from `card-ids`."[card-ids](when (seq card-ids)- (->> (t2/select :model/Card- :id [:in card-ids]- :archived false)+ (->> (llm.db/unarchived-cards card-ids)(filter mi/can-read?)(map :id)set)))@@ -194,7 +163,7 @@(let [;; Grouped by the persisted Field's own table_id, not the caller-supplied column's;; :table-id, consistent with the permission checks elsewhere in this namespace.fields (filter field-values/field-should-have-field-values?- (t2/select :model/Field :id [:in field-ids]))+ (llm.db/fields field-ids)){restricted true, unrestricted false} (group-by #(contains? restricted-table-ids (:table_id %)) fields)capped-fields (concat unrestricted (cap-restricted-fields (group-by :table_id restricted)))](into {}@@ -214,8 +183,7 @@(keep :fk_target_field_id)set)](when (seq target-ids)- (let [fields (t2/select [:model/Field :id :name :table_id]- :id [:in target-ids])+ (let [fields (llm.db/field-names-and-tables target-ids)table-ids (into #{} (map :table_id) fields)accessible-tables (fetch-accessible-tables database-id table-ids)sandbox-restricted (metabot.perms/sandbox-restricted-fields table-ids)]@@ -247,11 +215,11 @@(filter pos-int?)set)](when (seq missing-fp-ids)- (let [fields (t2/select :model/Field :id [:in missing-fp-ids])]+ (let [fields (llm.db/fields missing-fp-ids)](doseq [field fields];; Run with admin perms to match behavior during normal sync.(request/as-admin (sync/refingerprint-field! field)))- (t2/select-pk->fn :fingerprint :model/Field :id [:in missing-fp-ids])))))+ (llm.db/field-fingerprints missing-fp-ids)))));;; ------------------------------------------- Fingerprint Formatting -------------------------------------------diff --git a/src/metabase/llm/db.clj b/src/metabase/llm/db.cljnew file mode 100644index 00000000000..99592620f6b--- /dev/null+++ b/src/metabase/llm/db.clj@@ -0,0 +1,70 @@+(ns metabase.llm.db+ "Application database queries for the LLM module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.models.interface :as mi]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn database-engine+ "The engine of the Database with `database-id`, or nil."+ [database-id]+ (t2/select-one-fn :engine :model/Database :id database-id))++(defn- table-match-clause+ "Match a Table by name and, when given, schema, both case-insensitively."+ [{:keys [schema table]}]+ (let [table-lower (u/lower-case-en table)]+ (if schema+ [:and+ [:= [:lower :name] table-lower]+ [:= [:lower :schema] (u/lower-case-en schema)]]+ [:= [:lower :name] table-lower])))++(defn active-tables-matching+ "The active Tables of the Database with `database-id` matching one of `tables` (each a map of `:table` and+ optional `:schema`), by case-insensitive name/schema."+ [database-id tables]+ (t2/select :model/Table+ {:where [:and+ [:= :db_id database-id]+ [:= :active true]+ (into [:or] (map table-match-clause) tables)]}))++(defn visible-tables+ "The active, visible Tables among `table-ids` of the Database with `database-id` that `user-id` (or a+ superuser) can access for querying, requiring unrestricted view-data and query-builder-or-native create+ permissions."+ [table-ids database-id user-id superuser?]+ (let [{:keys [clause with]} (mi/visible-filter-clause+ :model/Table :id+ {:user-id user-id, :is-superuser? superuser?}+ {:perms/view-data :unrestricted+ :perms/create-queries :query-builder-and-native})]+ (t2/select :model/Table+ :id [:in table-ids]+ :db_id database-id+ :active true+ :visibility_type nil+ (cond-> {:where clause}+ with (assoc :with with)))))++(defn unarchived-cards+ "The unarchived Cards with `card-ids`."+ [card-ids]+ (t2/select :model/Card :id [:in card-ids] :archived false))++(defn fields+ "The Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field :id [:in field-ids]))++(defn field-names-and-tables+ "The id, name, and Table id of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :name :table_id] :id [:in field-ids]))++(defn field-fingerprints+ "A map of Field id to fingerprint for the Fields with `field-ids`."+ [field-ids]+ (t2/select-pk->fn :fingerprint :model/Field :id [:in field-ids]))diff --git a/src/metabase/login_history/api.clj b/src/metabase/login_history/api.cljindex c4b1a7d3af9..c328200c102 100644--- a/src/metabase/login_history/api.clj+++ b/src/metabase/login_history/api.clj@@ -2,9 +2,9 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.login-history.db :as login-history.db][metabase.login-history.models.login-history :as login-history]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(defn login-history"Return complete login history (sorted by most-recent -> least-recent) for `user-or-id`"@@ -13,9 +13,7 @@;; nice to be able to see every log in that's every happened with an account. Maybe we should page this, or page the;; API endpoint?(login-history/human-friendly-infos- (t2/select [:model/LoginHistory :timestamp :session_id :device_description :ip_address]- :user_id (u/the-id user-or-id)- {:order-by [[:timestamp :desc]]})))+ (login-history.db/login-history-for-user (u/the-id user-or-id))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/login_history/db.clj b/src/metabase/login_history/db.cljnew file mode 100644index 00000000000..527b885c633--- /dev/null+++ b/src/metabase/login_history/db.clj@@ -0,0 +1,47 @@+(ns metabase.login-history.db+ "Application database queries for the login history module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn login-history-for-user+ "The timestamp, session id, device description, and IP address of the LoginHistory of the User with `user-id`,+ newest first."+ [user-id]+ (t2/select [:model/LoginHistory :timestamp :session_id :device_description :ip_address]+ :user_id user-id+ {:order-by [[:timestamp :desc]]}))++(defn insert-login-history!+ "Insert the LoginHistory `row`."+ [row]+ (t2/insert! :model/LoginHistory row))++(defn login-history-ids-for-user+ "Up to `limit` LoginHistory ids of the User with `user-id`."+ [user-id limit]+ (t2/select [:model/LoginHistory :id] :user_id user-id {:limit limit}))++(defn login-history-ids-for-user-device+ "Up to `limit` LoginHistory ids of the User with `user-id` on the device with `device-id`."+ [user-id device-id limit]+ (t2/select [:model/LoginHistory :id] :user_id user-id, :device_id device-id, {:limit limit}))++(defn first-device-login-count-since+ "The number of LoginHistory rows of the User with `user-id` in the last `window-hours` that are the first+ login on their device."+ [user-id window-hours]+ (t2/count :model/LoginHistory+ {:where [:and+ [:= :user_id user-id]+ [:> :timestamp (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- window-hours) :hour)]+ [:not [:exists+ ^:allow-subquery+ {:select [1]+ :from [[:login_history :lh2]]+ :where [:and+ [:= :lh2.user_id :login_history.user_id]+ [:= :lh2.device_id :login_history.device_id]+ [:< :lh2.id :login_history.id]]}]]]}))diff --git a/src/metabase/login_history/models/login_history.clj b/src/metabase/login_history/models/login_history.cljindex c5ce9a5a8da..bc00393e41c 100644--- a/src/metabase/login_history/models/login_history.clj+++ b/src/metabase/login_history/models/login_history.clj@@ -1,11 +1,10 @@(ns metabase.login-history.models.login-history(:require[java-time.api :as t]- [metabase.app-db.core :as mdb]+ [metabase.login-history.db :as login-history.db][metabase.login-history.settings :as login-history.settings][metabase.request.core :as request][metabase.util.date-2 :as u.date]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :as i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]@@ -54,7 +53,7 @@(let [login-history (merge {:user_id user-id:session_id session-id}(dissoc device-info :embedded :token_exchange))]- (t2/insert! :model/LoginHistory login-history)+ (login-history.db/insert-login-history! login-history)login-history))(t2/define-after-select :model/LoginHistory@@ -67,14 +66,14 @@(defn first-login-ever?"Return true if this is the first login ever for the given user-id."[{user-id :user_id}]- (some-> (t2/select [:model/LoginHistory :id] :user_id user-id {:limit 2})+ (some-> (login-history.db/login-history-ids-for-user user-id 2)count(= 1)))(defn first-login-on-this-device?"Return true if this is the first login for the given user-id on the device"[{user-id :user_id, device-id :device_id}]- (some-> (t2/select [:model/LoginHistory :id] :user_id user-id, :device_id device-id, {:limit 2})+ (some-> (login-history.db/login-history-ids-for-user-device user-id device-id 2)count(= 1)))@@ -86,21 +85,8 @@window. Over-counts first-login-ever rows (those never email) — safe direction for abreaker."[user-id]- (let [cutoff (h2x/add-interval-honeysql-form- (mdb/db-type) :%now (- new-device-email-rate-limit-window-hours) :hour)]- (> (t2/count :model/LoginHistory- {:where [:and- [:= :user_id user-id]- [:> :timestamp cutoff]- [:not [:exists- ^:allow-subquery- {:select [1]- :from [[:login_history :lh2]]- :where [:and- [:= :lh2.user_id :login_history.user_id]- [:= :lh2.device_id :login_history.device_id]- [:< :lh2.id :login_history.id]]}]]]})- (login-history.settings/new-device-email-rate-limit-cap))))+ (> (login-history.db/first-device-login-count-since user-id new-device-email-rate-limit-window-hours)+ (login-history.settings/new-device-email-rate-limit-cap)))(t2/define-before-update :model/LoginHistory [_login-history](throw (RuntimeException. (tru "You can''t update a LoginHistory after it has been created."))))diff --git a/src/metabase/mcp/callback_api.clj b/src/metabase/mcp/callback_api.cljindex 0500a0771c1..c8ee2f5625f 100644--- a/src/metabase/mcp/callback_api.clj+++ b/src/metabase/mcp/callback_api.clj@@ -8,12 +8,12 @@[clojure.string :as str][metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.mcp.db :as mcp.db][metabase.mcp.session :as mcp.session][metabase.mcp.validation :as mcp.validation][metabase.metabot.config :as metabot.config][metabase.util.i18n :refer [tru]]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(defn- mcp-session-id-from-headers[request]@@ -43,13 +43,13 @@(defn- persist-mcp-feedback![{:keys [feedback conversation_data]}]- (t2/insert! :model/McpFeedback- {:user_id api/*current-user-id*- :positive (:positive feedback)- :issue_type (:issue_type feedback)- :freeform_feedback (:freeform_feedback feedback)- :prompt (:prompt conversation_data)- :query (:query conversation_data)}))+ (mcp.db/insert-feedback!+ {:user_id api/*current-user-id*+ :positive (:positive feedback)+ :issue_type (:issue_type feedback)+ :freeform_feedback (:freeform_feedback feedback)+ :prompt (:prompt conversation_data)+ :query (:query conversation_data)}))#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/drills"diff --git a/src/metabase/mcp/db.clj b/src/metabase/mcp/db.cljnew file mode 100644index 00000000000..16227ccf50e--- /dev/null+++ b/src/metabase/mcp/db.clj@@ -0,0 +1,44 @@+(ns metabase.mcp.db+ "Application database queries for the MCP module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn insert-feedback!+ "Insert the McpFeedback `row`."+ [row]+ (t2/insert! :model/McpFeedback row))++(defn session-user-id+ "The id of the User owning the `core_session` with `key-hashed`, or nil."+ [key-hashed]+ (t2/select-one-fn :user_id :core_session :key_hashed key-hashed))++(defn insert-query-handle!+ "Insert the McpQueryHandle `row`."+ [row]+ (t2/insert! :model/McpQueryHandle row))++(defn query-handle-for-user+ "The McpQueryHandle with `handle-id` whose session belongs to the User with `user-id`, or nil."+ [handle-id user-id]+ (t2/select-one :model/McpQueryHandle+ {:select [:mqh.*]+ :from [[:mcp_query_handle :mqh]]+ :join [[:core_session :cs] [:= :cs.id :mqh.core_session_id]]+ :where [:and+ [:= :mqh.id handle-id]+ [:= :cs.user_id user-id]]}))++(defn delete-session-for-user!+ "Delete the `core_session` with `key-hashed` if it belongs to the User with `user-id`."+ [key-hashed user-id]+ (t2/query {:delete-from :core_session+ :where [:and+ [:= :key_hashed key-hashed]+ [:= :user_id user-id]]}))++(defn delete-query-handles-for-mcp-session!+ "Delete the McpQueryHandles of the MCP session `mcp-session-id`."+ [mcp-session-id]+ (t2/delete! :model/McpQueryHandle :mcp_session_id mcp-session-id))diff --git a/src/metabase/mcp/session.clj b/src/metabase/mcp/session.cljindex bbb59d0c838..c170d2e4416 100644--- a/src/metabase/mcp/session.clj+++ b/src/metabase/mcp/session.clj@@ -14,13 +14,13 @@(:require[clojure.string :as str][metabase.app-db.core :as app-db]+ [metabase.mcp.db :as mcp.db][metabase.mcp.models.mcp-query-handle][metabase.mcp.settings :as mcp.settings][metabase.session.core :as session][metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2])+ [metabase.util.malli.registry :as mr])(:import(java.nio ByteBuffer)(java.nio.charset StandardCharsets)@@ -315,7 +315,7 @@(i.e. no ownership to violate), or if the existing row belongs to `user-id`."[session-id user-id](let [key-hashed (session/hash-session-key (derive-embedding-session-key session-id))- owner (t2/select-one-fn :user_id :core_session :key_hashed key-hashed)]+ owner (mcp.db/session-user-id key-hashed)](or (nil? owner) (= owner user-id))));;; -------------------------------------------- Query Handle Store -----------------------------------------------@@ -342,12 +342,12 @@;; filters on for cross-session ownership.(let [core-session-id (:id (get-or-create-embedding-session! mcp-session-id user-id))handle-id (str (UUID/randomUUID))]- (t2/insert! :model/McpQueryHandle- (cond-> {:id handle-id- :mcp_session_id mcp-session-id- :core_session_id core-session-id- :encoded_query encoded-query}- prompt (assoc :prompt prompt)))+ (mcp.db/insert-query-handle!+ (cond-> {:id handle-id+ :mcp_session_id mcp-session-id+ :core_session_id core-session-id+ :encoded_query encoded-query}+ prompt (assoc :prompt prompt)))handle-id)))(defn- handle-id?@@ -365,13 +365,7 @@(when (and user-id (handle-id? handle-id));; Single round-trip: join `mcp_query_handle` to `core_session` and filter on;; `core_session.user_id`, so ownership is enforced in the WHERE clause.- (let [row (t2/select-one :model/McpQueryHandle- {:select [:mqh.*]- :from [[:mcp_query_handle :mqh]]- :join [[:core_session :cs] [:= :cs.id :mqh.core_session_id]]- :where [:and- [:= :mqh.id handle-id]- [:= :cs.user_id user-id]]})]+ (let [row (mcp.db/query-handle-for-user handle-id user-id)](when (and row (not= mcp-session-id (:mcp_session_id row)))(log/debugf "MCP handle %s resolved across sessions for user %s"handle-id user-id))@@ -402,8 +396,5 @@[session-id user-id](assert-session-id! session-id)(let [key-hashed (session/hash-session-key (derive-embedding-session-key session-id))]- (t2/query {:delete-from :core_session- :where [:and- [:= :key_hashed key-hashed]- [:= :user_id user-id]]})- (t2/delete! :model/McpQueryHandle :mcp_session_id session-id)))+ (mcp.db/delete-session-for-user! key-hashed user-id)+ (mcp.db/delete-query-handles-for-mcp-session! session-id)))diff --git a/src/metabase/measures/api.clj b/src/metabase/measures/api.cljindex b7d60798f64..00550d242ed 100644--- a/src/metabase/measures/api.clj+++ b/src/metabase/measures/api.clj@@ -5,6 +5,7 @@[metabase.api.macros :as api.macros][metabase.events.core :as events][metabase.lib.core :as lib]+ [metabase.measures.db :as measures.db][metabase.measures.schema :as measures.schema][metabase.metrics.core :as metrics][metabase.models.interface :as mi]@@ -52,19 +53,15 @@(let [table-id (definition-table-id definition)](api/create-check :model/Measure (assoc body :table_id table-id))(let [measure (api/check-500- (first (t2/insert-returning-instances! :model/Measure- :creator_id api/*current-user-id*- :name name- :description description- :definition definition)))]+ (measures.db/insert-measure! api/*current-user-id* name description definition))](events/publish-event! :event/measure-create {:object measure :user-id api/*current-user-id*})(t2/hydrate measure :creator))))(mu/defn- hydrated-measure [id :- ms/PositiveIntinclude-orphaned? :- :boolean]- (api/read-check (t2/select-one :model/Measure :id id))+ (api/read-check (measures.db/measure id))(metrics/sync-dimensions! :metadata/measure id)- (cond-> (-> (t2/hydrate (t2/select-one :model/Measure :id id) :creator)+ (cond-> (-> (t2/hydrate (measures.db/measure id) :creator)metrics/filter-dimensions-for-user)(not include-orphaned?) metrics/without-orphaned-dimensions))@@ -91,10 +88,10 @@(api.macros/defendpoint :get "/" :- [:sequential ::measure]"Fetch *all* `Measures`."[]- (let [measures (t2/select :model/Measure, :archived false, {:order-by [[:%lower.name :asc]]})+ (let [measures (measures.db/unarchived-measures)table-ids (into #{} (keep :table_id) measures)](perms/prime-table-perms-cache {:db-ids (when (seq table-ids)- (t2/select-fn-set :db_id :model/Table :id [:in table-ids]))+ (measures.db/table-database-ids table-ids)):table-ids table-ids})(->> (t2/hydrate (filterv mi/can-read? measures) :creator :definition_description)(mapv with-api-dimensions))))@@ -118,7 +115,7 @@(when (not= new-table-id (:table_id existing))(api/create-check :model/Measure {:table_id new-table-id}))))(when changes- (t2/update! :model/Measure id changes))+ (measures.db/update-measure! id changes))(u/prog1 (hydrated-measure id false)(events/publish-event! :event/measure-update{:object <> :user-id api/*current-user-id* :revision-message revision_message}))))diff --git a/src/metabase/measures/db.clj b/src/metabase/measures/db.cljnew file mode 100644index 00000000000..de84c9e972c--- /dev/null+++ b/src/metabase/measures/db.clj@@ -0,0 +1,54 @@+(ns metabase.measures.db+ "Application database queries for the measures module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn insert-measure!+ "Insert a Measure and return the inserted instance."+ [creator-id measure-name description definition]+ (t2/insert-returning-instance! :model/Measure+ :creator_id creator-id+ :name measure-name+ :description description+ :definition definition))++(defn measure+ "The Measure with `id`, or nil."+ [id]+ (t2/select-one :model/Measure :id id))++(defn unarchived-measures+ "The unarchived Measures, in case-insensitive name order."+ []+ (t2/select :model/Measure, :archived false, {:order-by [[:%lower.name :asc]]}))++(defn table-database-ids+ "The set of Database ids of the Tables with `table-ids`."+ [table-ids]+ (t2/select-fn-set :db_id :model/Table :id [:in table-ids]))++(defn update-measure!+ "Apply `changes` to the Measure with `id`."+ [id changes]+ (t2/update! :model/Measure id changes))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn table-perms-columns+ "The Database id, schema, and id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one [:model/Table :db_id :schema :id] :id table-id))++(defn collections+ "The Collections with `collection-ids`."+ [collection-ids]+ (t2/select :model/Collection :id [:in collection-ids]))++(defn set-measure-dimensions!+ "Set the dimensions and dimension mappings of the Measure with `id`."+ [id dimensions dimension-mappings]+ (t2/update! :model/Measure id {:dimensions dimensions, :dimension_mappings dimension-mappings}))diff --git a/src/metabase/measures/models/measure.clj b/src/metabase/measures/models/measure.cljindex 1f825f2e4a9..90167713c7c 100644--- a/src/metabase/measures/models/measure.clj+++ b/src/metabase/measures/models/measure.clj@@ -9,6 +9,7 @@[metabase.lib.schema :as lib.schema][metabase.lib.schema.common :as lib.schema.common][metabase.lib.schema.measure :as lib.schema.measure]+ [metabase.measures.db :as measures.db][metabase.metrics.core :as metrics][metabase.models.interface :as mi][metabase.models.serialization :as serdes]@@ -56,17 +57,17 @@(defmethod mi/can-read? :model/Measure([instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (measures.db/table (:table_id instance)))](mi/can-read? table)))- ([model pk]- (mi/can-read? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-read? (measures.db/measure pk))));; Measures can be written by superusers or data analysts with unrestricted view data permissions,;; but only if the parent table is editable (not in a remote-synced collection in read-only mode).(defmethod mi/can-write? :model/Measure([instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (measures.db/table (:table_id instance)))](and (or api/*is-superuser?*(and api/*is-data-analyst?*(perms/user-has-permission-for-table?@@ -76,15 +77,15 @@(:db_id table)(u/the-id table))))(remote-sync/table-editable? table))))- ([model pk]- (mi/can-write? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-write? (measures.db/measure pk))));; Measures can be created by superusers, but only if the parent table is editable;; (not in a remote-synced collection in read-only mode).(defmethod mi/can-create? :model/Measure[_model instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (measures.db/table (:table_id instance)))](and (or api/*is-superuser?*(and api/*is-data-analyst?*(perms/user-has-permission-for-table?@@ -109,7 +110,7 @@collection-synced-map (if (seq collection-ids)(into {}(map (juxt :id :is_remote_synced))- (t2/select :model/Collection :id [:in collection-ids]))+ (measures.db/collections collection-ids)){});; Associate collection info with each measure's tablemeasures-with-collection (for [measure measures-with-tables@@ -151,7 +152,7 @@(defmethod mi/perms-objects-set :model/Measure[measure read-or-write](let [table (or (:table measure)- (t2/select-one ['Table :db_id :schema :id] :id (u/the-id (:table_id measure))))]+ (measures.db/table-perms-columns (u/the-id (:table_id measure))))](mi/perms-objects-set table read-or-write)))(defn- normalize-definition-from-db@@ -239,6 +240,4 @@(defmethod metrics/save-dimensions! :metadata/measure[measure dimensions dimension-mappings](when-let [measure-id (:id measure)]- (t2/update! :model/Measure measure-id- {:dimensions dimensions- :dimension_mappings dimension-mappings})))+ (measures.db/set-measure-dimensions! measure-id dimensions dimension-mappings)))diff --git a/src/metabase/metabot/agent/links.clj b/src/metabase/metabot/agent/links.cljindex e2b370bae6a..b735fa7285e 100644--- a/src/metabase/metabot/agent/links.clj+++ b/src/metabase/metabot/agent/links.clj@@ -9,11 +9,11 @@[metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.schema]+ [metabase.metabot.db :as metabot.db][metabase.system.core :as system][metabase.util :as u][metabase.util.json :as json]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -146,7 +146,7 @@(do(log/warn "Invalid table id for link resolution" {:table-id table-id})nil)- (if-let [db-id (t2/select-one-fn :db_id :model/Table :id parsed-id)]+ (if-let [db-id (metabot.db/table-database-id parsed-id)](let [mp (lib-be/application-database-metadata-provider db-id)table (lib.metadata/table mp parsed-id)query (lib/query mp table)]diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.cljindex 7b3cefe62b9..6e655473b59 100644--- a/src/metabase/metabot/api.clj+++ b/src/metabase/metabot/api.clj@@ -21,6 +21,7 @@[metabase.metabot.config :as metabot.config][metabase.metabot.context :as metabot.context][metabase.metabot.conversation-title :as conversation-title]+ [metabase.metabot.db :as metabot.db][metabase.metabot.envelope :as metabot.envelope][metabase.metabot.feedback :as metabot.feedback][metabase.metabot.persistence :as metabot.persistence]@@ -36,8 +37,7 @@[metabase.util.i18n :refer [tru]][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import(java.io OutputStream)))@@ -50,7 +50,7 @@can originate one. Permissions are participation-based — a conversation canhave multiple participants (e.g. multiple users in a shared Slack thread)."[conversation-id]- (when-let [conversation (t2/select-one :model/MetabotConversation :id conversation-id)]+ (when-let [conversation (metabot.db/conversation conversation-id)](api/check-403 (mi/can-read? conversation))))(defn- make-out-of-sync-fndiff --git a/src/metabase/metabot/api/conversations.clj b/src/metabase/metabot/api/conversations.cljindex 9df11bfd0ad..f00e2870e47 100644--- a/src/metabase/metabot/api/conversations.clj+++ b/src/metabase/metabot/api/conversations.clj@@ -13,6 +13,7 @@[metabase.events.core :as events][metabase.lib-be.schema :as lib-be.schema][metabase.metabot.conversation-title :as conversation-title]+ [metabase.metabot.db :as metabot.db][metabase.metabot.persistence :as metabot.persistence][metabase.metabot.schema :as metabot.schema][metabase.queries.core :as queries]@@ -115,59 +116,6 @@(def ^:private default-limit 50)(def ^:private default-offset 0)-(defn- participation-clause- "Match conversations visible in history for `user-id`.-- New rows participate via `metabot_message.user_id`; legacy rows created before- message authors were stamped fall back to the conversation originator."- [user-id]- (let [participation-exists [:exists ^:allow-subquery {:select [[[:inline 1]]]- :from [[:metabot_message :participation_message]]- :where [:and- [:= :participation_message.conversation_id :c.id]- [:= :participation_message.user_id user-id]]}]]- [:or- [:= :c.user_id user-id]- participation-exists]))--(defn- last-live-message-profile-id-subquery- []- ^:allow-subquery- {:select [:last_message.profile_id]- :from [[:metabot_message :last_message]]- :where [:and- [:= :last_message.conversation_id :c.id]- [:= :last_message.deleted_at nil]]- :order-by [[:last_message.created_at :desc] [:last_message.id :desc]]- :limit 1})--(defn- live-message-count-subquery- []- ^:allow-subquery- {:select [[[:count :*]]]- :from [[:metabot_message :counted_message]]- :where [:and- [:= :counted_message.conversation_id :c.id]- [:= :counted_message.deleted_at nil]]})--(defn- last-live-message-at-subquery- []- ^:allow-subquery- {:select [[[:max :recent_message.created_at]]]- :from [[:metabot_message :recent_message]]- :where [:and- [:= :recent_message.conversation_id :c.id]- [:= :recent_message.deleted_at nil]]})--(defn- activity-at-expression- []- [:greatest :c.created_at [:coalesce (last-live-message-at-subquery) :c.created_at]])--(defn- list-where-clause- [user-id profile-id]- (cond-> [:and (participation-clause user-id)]- profile-id (conj [:= (last-live-message-profile-id-subquery) profile-id])))-;;; ---------------------------------------- Endpoints ----------------------------------------(api.macros/defendpoint :get "/" :- ListConversationsResponse@@ -182,25 +130,13 @@(let [user-id (api/check-404 api/*current-user-id*)limit (or (request/limit) default-limit)offset (or (request/offset) default-offset)- where (list-where-clause user-id profile_id)- total (:count (t2/query-one {:select [[[:count :*] :count]]- :from [[:metabot_conversation :c]]- :where where}))+ total (metabot.db/conversation-count user-id profile_id);; Aggregates are per-row correlated subqueries so pagination stays on the outer;; `metabot_conversation` scan rather than grouping every message the user owns.;; Participation is defined by message authorship, not deletion state, so;; soft-deleted messages still count. Legacy rows fall back to;; `metabot_conversation.user_id`.- rows (t2/select :model/MetabotConversation- {:select [:c.id :c.created_at :c.title :c.user_id :c.forked_from_conversation_id- [(live-message-count-subquery) :message_count]- [(last-live-message-at-subquery) :last_message_at]- [(last-live-message-profile-id-subquery) :profile_id]]- :from [[:metabot_conversation :c]]- :where where- :order-by [[(activity-at-expression) :desc] [:c.id :asc]]- :limit limit- :offset offset})]+ rows (metabot.db/conversations-page user-id profile_id limit offset)]{:data (mapv #(-> %(select-keys [:created_at :title :user_id :profile_id :message_count :last_message_at:forked_from_conversation_id])@@ -238,7 +174,7 @@[{:keys [id]} :- ConversationIdParams_query-params{:keys [message_id]} :- ForkConversationBody]- (let [conversation (api/check-404 (t2/select-one [:model/MetabotConversation :id :user_id] :id id))]+ (let [conversation (api/check-404 (metabot.db/conversation-id-and-user-id id))](api/check-403 (= (:user_id conversation) api/*current-user-id*))(let [new-conversation-id (metabot.persistence/fork-conversation! id message_id api/*current-user-id*)](api/check-400 (some? new-conversation-id)@@ -284,9 +220,7 @@(update :visualization_settings #(or % {}))){:id api/*current-user-id*}:delay-event)- (t2/update! (t2/table-name :model/Card) (:id <>)- {:metabot_conversation_id id- :metabot_chart_id chart_id})))]+ (metabot.db/link-card-to-conversation! (:id <>) id chart_id)))](events/publish-event! :event/card-create{:object created :user-id api/*current-user-id*})(assoc createddiff --git a/src/metabase/metabot/api/metabot.clj b/src/metabase/metabot/api/metabot.cljindex 9c008c278f7..173815c7b01 100644--- a/src/metabase/metabot/api/metabot.clj+++ b/src/metabase/metabot/api/metabot.clj@@ -5,6 +5,7 @@[metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.app-db.core :as mdb]+ [metabase.metabot.db :as metabot.db][metabase.metabot.suggested-prompts :as metabot.suggested-prompts][metabase.metabot.task.suggested-prompts-refresh :as metabot.suggested-prompts-refresh][metabase.metabot.tools.util :as metabot.tools.u]@@ -25,7 +26,7 @@"List configured metabot instances"[](api/check-superuser)- {:items (t2/select :model/Metabot {:order-by [[:name :asc]]})})+ {:items (metabot.db/metabots-by-name)});; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -35,7 +36,7 @@"Retrieve one metabot instance"[{:keys [id]} :- [:map [:id pos-int?]]](api/check-superuser)- (api/check-404 (t2/select-one :model/Metabot :id id)))+ (api/check-404 (metabot.db/metabot id)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -49,18 +50,18 @@[:use_verified_content {:optional true} :boolean][:collection_id {:optional true} [:maybe pos-int?]]]](api/check-superuser)- (api/check-404 (t2/exists? :model/Metabot :id id))- (let [old-metabot (t2/select-one :model/Metabot :id id)]+ (api/check-404 (metabot.db/metabot-exists? id))+ (let [old-metabot (metabot.db/metabot id)];; Prevent enabling verified content without the premium feature(when (:use_verified_content metabot-updates)(premium-features/assert-has-feature :content-verification (tru "Content verification")))(let [old-vals (select-keys old-metabot (keys metabot-updates))](when (not= old-vals metabot-updates)- (t2/update! :model/Metabot id metabot-updates)+ (metabot.db/update-metabot! id metabot-updates);; Content scope changed, so the suggested prompts are stale. Regenerate in the background so;; the toggle returns instantly; the job re-reads the saved scope and debounces rapid toggles.(metabot.suggested-prompts-refresh/schedule-refresh! id))- (t2/select-one :model/Metabot :id id))))+ (metabot.db/metabot id))))(api.macros/defendpoint :post "/:id/prompt-suggestions/regenerate":- [:multi {:dispatch :status}@@ -79,7 +80,7 @@[{:keys [id]} :- [:map [:id pos-int?]]](api/check-superuser)(t2/with-transaction [_conn]- (api/check-404 (t2/exists? :model/Metabot :id id))+ (api/check-404 (metabot.db/metabot-exists? id))(metabot.usage/check-metabase-managed-free-limit!)(metabot.suggested-prompts/delete-all-metabot-prompts id)(metabot.suggested-prompts/generate-sample-prompts id)))@@ -113,23 +114,16 @@[:= :metabot_prompt.metabot_id id]]}model (update :where conj [:= :card.type model])model_id (update :where conj [:= :card.id model_id]))- total (t2/count :model/MetabotPrompt base-query)+ total (metabot.db/prompt-count-where base-query)order-by (if sample[[[rand-fn]]][[:card.name :asc][:id :asc]])- prompts (t2/select [:model/MetabotPrompt- :id- :prompt- :model- [:card_id :model_id]- [:card.name :model_name]- :created_at- :updated_at]- (cond-> base-query- true (assoc :order-by order-by)- (request/limit) (assoc :limit (request/limit))- offset (assoc :offset offset)))]+ prompts (metabot.db/prompts-where+ (cond-> base-query+ true (assoc :order-by order-by)+ (request/limit) (assoc :limit (request/limit))+ offset (assoc :offset offset)))]{:prompts prompts:limit (request/limit):offset offset@@ -156,9 +150,7 @@[:id pos-int?][:prompt-id pos-int?]]](api/check-superuser)- (t2/delete! :model/MetabotPrompt {:where [:and- [:= :id prompt-id]- [:= :metabot_id id]]})+ (metabot.db/delete-metabot-prompt! id prompt-id)api/generic-204-no-content)(def ^{:arglists '([request respond raise])} routesdiff --git a/src/metabase/metabot/config.clj b/src/metabase/metabot/config.cljindex c697f69362a..9bca205591b 100644--- a/src/metabase/metabot/config.clj+++ b/src/metabase/metabot/config.clj@@ -3,8 +3,8 @@[medley.core :as m][metabase.api.common :as api][metabase.llm.settings :as llm.settings]- [metabase.metabot.settings :as metabot.settings]- [toucan2.core :as t2]))+ [metabase.metabot.db :as metabot.db]+ [metabase.metabot.settings :as metabot.settings]))(def internal-metabot-id"The ID of the internal Metabot instance."@@ -59,7 +59,7 @@Returns nil if no entry can be found.The provided ID can be a UUID from [[metabot-config]] or an entity_id of a Metabot instance."[metabot-id]- (t2/select-one-pk :model/Metabot :entity_id (get-in metabot-config [metabot-id :entity-id] metabot-id)))+ (metabot.db/metabot-id-by-entity-id (get-in metabot-config [metabot-id :entity-id] metabot-id)))(defn resolve-dynamic-metabot-id"Resolve dynamic metabot ID with logical fall backsdiff --git a/src/metabase/metabot/context.clj b/src/metabase/metabot/context.cljindex fb6862fbb07..80f6dacfc76 100644--- a/src/metabase/metabot/context.clj+++ b/src/metabase/metabot/context.clj@@ -10,6 +10,7 @@[metabase.lib.core :as lib][metabase.metabot.config :as metabot.config][metabase.metabot.curation :as curation]+ [metabase.metabot.db :as metabot.db][metabase.metabot.metadata-perms :as metabot.perms][metabase.metabot.settings :as metabot.settings][metabase.metabot.table-utils :as table-utils]@@ -18,8 +19,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import(java.time OffsetDateTime)(java.time.format DateTimeFormatter)))@@ -202,11 +202,7 @@which is too restrictive for MBQL viewing context enrichment."[[database-id table-ids]](try- (let [raw-tables (t2/select [:model/Table :id :name :schema :description]- :db_id database-id- :id [:in table-ids]- :active true- :visibility_type nil)+ (let [raw-tables (metabot.db/visible-table-summaries database-id table-ids)queryable-ids (metabot.perms/queryable-table-ids (map :id raw-tables))](into [](comp (filter (comp queryable-ids :id))@@ -266,10 +262,9 @@"Look up the metabot row for the given UUID/entity-id, mirroring the resolution used by `metabase.metabot.tools.search`."[metabot-id](when metabot-id- (t2/select-one :model/Metabot- :entity_id (get-in metabot.config/metabot-config- [metabot-id :entity-id]- metabot-id))))+ (metabot.db/metabot-by-entity-id (get-in metabot.config/metabot-config+ [metabot-id :entity-id]+ metabot-id))))(defn- filter-recents-to-curated"Keep only recents that are curated (verified, official-collection, library/published, or authoritative).diff --git a/src/metabase/metabot/curation.clj b/src/metabase/metabot/curation.cljindex 6f4fbf91289..79e421a572c 100644--- a/src/metabase/metabot/curation.clj+++ b/src/metabase/metabot/curation.clj@@ -9,7 +9,7 @@(:require[metabase.collections.curation :as curation][metabase.collections.models.collection :as collection]- [toucan2.core :as t2]))+ [metabase.metabot.db :as metabot.db]))(def ^:private report-card-models"Search-model strings backed by `report_card`, moderated as \"card\"."@@ -20,18 +20,14 @@[ids item-type](if (empty? ids)#{}- (t2/select-fn-set :moderated_item_id :model/ModerationReview- :moderated_item_id [:in ids]- :moderated_item_type item-type- :most_recent true- :status "verified")))+ (metabot.db/verified-item-ids ids item-type)))(defn- collection-info"`collection-id → {:authority_level :location :type}` for the given ids."[coll-ids](when (seq coll-ids)- (t2/select-pk->fn #(select-keys % [:authority_level :location :type])- :model/Collection :id [:in coll-ids])))+ (update-vals (metabot.db/collection-curation-info-by-id coll-ids)+ #(select-keys % [:authority_level :location :type]))))(defn- root-collection-type-of[coll-id->info coll-id]@@ -43,7 +39,9 @@(defn- moderatable-curation-signals"`[id signal-map]` pairs for collection-housed, moderatable models (report_card-backed and dashboards)."[search-model t2-model item-type ids]- (let [rows (t2/select [t2-model :id :collection_id] :id [:in ids])+ (let [rows (case t2-model+ :model/Card (metabot.db/card-collection-ids ids)+ :model/Dashboard (metabot.db/dashboard-collection-ids ids))coll (collection-info (into #{} (keep :collection_id) rows))verified (verified-item-ids ids item-type)](for [{:keys [id collection_id]} rows]@@ -62,7 +60,7 @@curated? coerce is_published consistently (only true/1 count)."[ids](for [{:keys [id is_published data_layer data_authority]}- (t2/select [:model/Table :id :is_published :data_layer :data_authority] :id [:in ids])]+ (metabot.db/table-curation-rows ids)][id {:model "table":is_published is_published:data_layer data_layerdiff --git a/src/metabase/metabot/db.clj b/src/metabase/metabot/db.cljnew file mode 100644index 00000000000..2b441d126d8--- /dev/null+++ b/src/metabase/metabot/db.clj@@ -0,0 +1,743 @@+(ns metabase.metabot.db+ "Application database queries for the metabot module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods,+ and transactions."+ (:require+ [toucan2.core :as t2]))++;;; ------------------------------------------------- Metabot -------------------------------------------------++(defn metabot+ "The Metabot with `metabot-id`, or nil."+ [metabot-id]+ (t2/select-one :model/Metabot :id metabot-id))++(defn metabot-by-entity-id+ "The Metabot with `entity-id`, or nil."+ [entity-id]+ (t2/select-one :model/Metabot :entity_id entity-id))++(defn metabot-id-by-entity-id+ "The ID of the Metabot with `entity-id`, or nil."+ [entity-id]+ (t2/select-one-pk :model/Metabot :entity_id entity-id))++(defn metabots-by-name+ "Every Metabot, ordered by name."+ []+ (t2/select :model/Metabot {:order-by [[:name :asc]]}))++(defn metabot-exists?+ "Whether a Metabot with `metabot-id` exists."+ [metabot-id]+ (t2/exists? :model/Metabot :id metabot-id))++(defn update-metabot!+ "Apply `changes` to the Metabot with `metabot-id`."+ [metabot-id changes]+ (t2/update! :model/Metabot metabot-id changes))++;;; --------------------------------------------- Metabot prompts ---------------------------------------------++(defn prompts-for-metabots+ "The MetabotPrompts of the Metabots with `metabot-ids`."+ [metabot-ids]+ (t2/select :model/MetabotPrompt {:where [:in :metabot_id metabot-ids]}))++(defn prompts-where+ "The prompt, model, and Card columns of the MetabotPrompts matching the Honey SQL `query`."+ [query]+ (t2/select [:model/MetabotPrompt+ :id+ :prompt+ :model+ [:card_id :model_id]+ [:card.name :model_name]+ :created_at+ :updated_at]+ query))++(defn prompt-count-where+ "The number of MetabotPrompts matching the Honey SQL `query`."+ [query]+ (t2/count :model/MetabotPrompt query))++(defn prompt-count-for-metabot+ "The number of MetabotPrompts of the Metabot with `metabot-id`."+ [metabot-id]+ (t2/count :model/MetabotPrompt :metabot_id metabot-id))++(defn insert-prompts!+ "Insert the MetabotPrompt `rows`."+ [rows]+ (t2/insert! :model/MetabotPrompt rows))++(defn delete-metabot-prompt!+ "Delete the MetabotPrompt with `prompt-id` belonging to the Metabot with `metabot-id`."+ [metabot-id prompt-id]+ (t2/delete! :model/MetabotPrompt {:where [:and+ [:= :id prompt-id]+ [:= :metabot_id metabot-id]]}))++(defn delete-prompts-for-metabot!+ "Delete the MetabotPrompts of the Metabot with `metabot-id`."+ [metabot-id]+ (t2/delete! :model/MetabotPrompt {:where [:= :metabot_id metabot-id]}))++;;; ----------------------------------------------- Conversations -----------------------------------------------++(defn conversation+ "The MetabotConversation with `conversation-id`, or nil."+ [conversation-id]+ (t2/select-one :model/MetabotConversation :id conversation-id))++(defn conversation-id-and-user-id+ "The ID and originator of the MetabotConversation with `conversation-id`, or nil."+ [conversation-id]+ (t2/select-one [:model/MetabotConversation :id :user_id] :id conversation-id))++(defn conversation-title+ "The title of the MetabotConversation with `conversation-id`."+ [conversation-id]+ (t2/select-one-fn :title :model/MetabotConversation :id conversation-id))++(defn lock-conversation+ "The MetabotConversation with `conversation-id`, locked for update."+ [conversation-id]+ (t2/select-one :model/MetabotConversation :id conversation-id {:for :update}))++(defn- participation-clause+ "Match conversations visible in history for `user-id`.++ New rows participate via `metabot_message.user_id`; legacy rows created before message authors were stamped fall+ back to the conversation originator."+ [user-id]+ [:or+ [:= :c.user_id user-id]+ [:exists ^:allow-subquery {:select [[[:inline 1]]]+ :from [[:metabot_message :participation_message]]+ :where [:and+ [:= :participation_message.conversation_id :c.id]+ [:= :participation_message.user_id user-id]]}]])++(defn- last-live-message-profile-id-subquery+ []+ ^:allow-subquery+ {:select [:last_message.profile_id]+ :from [[:metabot_message :last_message]]+ :where [:and+ [:= :last_message.conversation_id :c.id]+ [:= :last_message.deleted_at nil]]+ :order-by [[:last_message.created_at :desc] [:last_message.id :desc]]+ :limit 1})++(defn- live-message-count-subquery+ []+ ^:allow-subquery+ {:select [[[:count :*]]]+ :from [[:metabot_message :counted_message]]+ :where [:and+ [:= :counted_message.conversation_id :c.id]+ [:= :counted_message.deleted_at nil]]})++(defn- last-live-message-at-subquery+ []+ ^:allow-subquery+ {:select [[[:max :recent_message.created_at]]]+ :from [[:metabot_message :recent_message]]+ :where [:and+ [:= :recent_message.conversation_id :c.id]+ [:= :recent_message.deleted_at nil]]})++(defn- activity-at-expression+ []+ [:greatest :c.created_at [:coalesce (last-live-message-at-subquery) :c.created_at]])++(defn- conversations-list-where+ [user-id profile-id]+ (cond-> [:and (participation-clause user-id)]+ profile-id (conj [:= (last-live-message-profile-id-subquery) profile-id])))++(defn conversations-page+ "A page of up to `limit` (offset by `offset`) MetabotConversations visible in the history of the User with+ `user-id`, most-recent-activity first, optionally narrowed to the last live message's `profile-id`."+ [user-id profile-id limit offset]+ (t2/select :model/MetabotConversation+ {:select [:c.id :c.created_at :c.title :c.user_id :c.forked_from_conversation_id+ [(live-message-count-subquery) :message_count]+ [(last-live-message-at-subquery) :last_message_at]+ [(last-live-message-profile-id-subquery) :profile_id]]+ :from [[:metabot_conversation :c]]+ :where (conversations-list-where user-id profile-id)+ :order-by [[(activity-at-expression) :desc] [:c.id :asc]]+ :limit limit+ :offset offset}))++(defn conversation-count+ "The number of MetabotConversations visible in the history of the User with `user-id`, optionally narrowed to the+ last live message's `profile-id`."+ [user-id profile-id]+ (:count (t2/query-one {:select [[[:count :*] :count]]+ :from [[:metabot_conversation :c]]+ :where (conversations-list-where user-id profile-id)})))++(defn titleless-conversation-ids+ "Up to `limit` IDs of the MetabotConversations without a title, whose ID is greater than `after-id` (or every one,+ when `after-id` is nil), in ID order."+ [after-id limit]+ (t2/select-fn-vec :id :model/MetabotConversation+ {:where [:and [:= :title nil] (when after-id [:> :id after-id])]+ :order-by [[:id :asc]]+ :limit limit}))++(defn insert-conversation!+ "Insert `conversation`."+ [conversation]+ (t2/insert! :model/MetabotConversation conversation))++(defn set-conversation-title-if-missing!+ "Set the title of the MetabotConversation with `conversation-id` if it has none."+ [conversation-id title]+ (t2/update! :model/MetabotConversation {:id conversation-id, :title nil} {:title title}))++(defn delete-conversations-created-before!+ "Delete the MetabotConversations created before `cutoff`, returning the number deleted."+ [cutoff]+ (t2/delete! :model/MetabotConversation {:where [:< :created_at cutoff]}))++;;; -------------------------------------------------- Messages --------------------------------------------------++(defn participant?+ "Whether the User with `user-id` has sent a message in the MetabotConversation with `conversation-id`."+ [conversation-id user-id]+ (t2/exists? :model/MetabotMessage :conversation_id conversation-id :user_id user-id))++(defn message-by-external-id+ "The ID and conversation of the MetabotMessage with `external-id`, or nil."+ [external-id]+ (t2/select-one [:model/MetabotMessage :id :conversation_id] :external_id external-id))++(defn live-messages+ "The non-deleted MetabotMessages of the MetabotConversation with `conversation-id`, in reader order."+ [conversation-id]+ (t2/select :model/MetabotMessage+ :conversation_id conversation-id+ :deleted_at nil+ {:order-by [[:created_at :asc] [:id :asc]]}))++(defn opening-messages+ "The first `limit` non-deleted MetabotMessages of the MetabotConversation with `conversation-id`, in reader order."+ [conversation-id limit]+ (t2/select :model/MetabotMessage+ :conversation_id conversation-id+ :deleted_at nil+ {:order-by [[:created_at :asc] [:id :asc]]+ :limit limit}))++(defn leaf-assistant-message+ "The most recent non-deleted assistant MetabotMessage of the MetabotConversation with `conversation-id`, or nil."+ [conversation-id]+ (t2/select-one :model/MetabotMessage+ {:where [:and+ [:= :conversation_id conversation-id]+ [:= :deleted_at nil]+ [:= :role "assistant"]]+ :order-by [[:created_at :desc] [:id :desc]]}))++(defn insert-message-returning-pk!+ "Insert `message` and return its ID."+ [message]+ (t2/insert-returning-pk! :model/MetabotMessage message))++(defn insert-messages!+ "Insert one MetabotMessage map or a sequence of them."+ [messages]+ (t2/insert! :model/MetabotMessage messages))++(defn update-message!+ "Apply `changes` to the MetabotMessage with `message-id`."+ [message-id changes]+ (t2/update! :model/MetabotMessage message-id changes))++(defn soft-delete-messages-where!+ "Soft-delete the MetabotMessages matching the Toucan `conditions` on behalf of `deleted-by-user-id`, returning the+ number of rows updated."+ [conditions deleted-by-user-id]+ (t2/update! :model/MetabotMessage conditions {:deleted_at [:now]+ :deleted_by_user_id deleted-by-user-id}))++(defn insert-used-tables!+ "Insert the MetabotUsedTable `rows`."+ [rows]+ (t2/insert! :model/MetabotUsedTable rows))++;;; ------------------------------------------------ Databases ------------------------------------------------++(defn database-summary+ "The ID, name, description, and engine of the Database with `database-id`."+ [database-id]+ (t2/select-one [:model/Database :id :name :description :engine] database-id))++(defn database-with-columns+ "The `columns` of the Database with `database-id`."+ [columns database-id]+ (t2/select-one columns database-id))++(defn database-exists?+ "Whether a Database with `database-id` exists."+ [database-id]+ (t2/exists? :model/Database :id database-id))++(defn database-ids-by-name+ "The IDs of the Databases named `database-name`."+ [database-name]+ (t2/select-pks-vec :model/Database :name database-name))++(defn database-engines-and-names+ "A map of ID to the engine and name of the Databases with `database-ids`."+ [database-ids]+ (t2/select-pk->fn identity [:model/Database :id :engine :name] :id [:in database-ids]))++(defn destination-database-ids+ "The IDs of the routing destination Databases among `database-ids`."+ [database-ids]+ (t2/select-fn-set :id :model/Database :id [:in database-ids] :router_database_id [:not= nil]))++(defn non-audit-databases+ "The ID, name, engine, description, and audit flag of every non-audit, non-destination Database, ordered by name."+ []+ (t2/select [:model/Database :id :name :engine :description :is_audit]+ :is_audit false+ :router_database_id nil+ {:order-by [[:%lower.name :asc]]}))++;;; ------------------------------------------------- Tables -------------------------------------------------++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn active-table-with-columns+ "The `columns` of the active Table with `table-id`, or nil."+ [columns table-id]+ (t2/select-one columns :id table-id :active true))++(defn table-database-id+ "The Database ID of the Table with `table-id`."+ [table-id]+ (t2/select-one-fn :db_id :model/Table :id table-id))++(defn tables-by-id+ "A map of ID to Table for `table-ids`."+ [table-ids]+ (t2/select-fn->fn :id identity :model/Table :id [:in table-ids]))++(defn table-summaries+ "The ID, names, schema, Database ID, and description of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :name :display_name :schema :db_id :description] :id [:in table-ids]))++(defn table-schema-rows+ "The ID, name, schema, and Database ID of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :name :schema :db_id] :id [:in table-ids]))++(defn table-curation-rows+ "The ID, published flag, data layer, and data authority of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :is_published :data_layer :data_authority] :id [:in table-ids]))++(defn visible-table-summaries+ "The ID, name, schema, and description of the active, unhidden Tables among `table-ids` in the Database with+ `database-id`."+ [database-id table-ids]+ (t2/select [:model/Table :id :name :schema :description]+ :db_id database-id+ :id [:in table-ids]+ :active true+ :visibility_type nil))++(defn visible-table-summaries-where+ "The ID, name, schema, and description of the active, unhidden Tables among `table-ids` in the Database with+ `database-id` matching the Honey SQL `query`."+ [database-id table-ids query]+ (t2/select [:model/Table :id :name :schema :description]+ :db_id database-id+ :id [:in table-ids]+ :active true+ :visibility_type nil+ query))++(defn visible-tables-reducible+ "Reducible ID, name, schema, and description of the active, unhidden Tables in the Database with `database-id`+ matching the Honey SQL `query`."+ [database-id query]+ (t2/reducible-select [:model/Table :id :name :schema :description]+ :db_id database-id+ :active true+ :visibility_type nil+ query))++(defn most-viewed-tables-where+ "The ID, Database ID, name, schema, and description of the active, unhidden Tables in the Database with+ `database-id` matching the Honey SQL `query`."+ [database-id query]+ (t2/select [:model/Table :id :db_id :name :schema :description]+ :db_id database-id+ :active true+ :visibility_type nil+ query))++(defn table-names+ "Up to `limit` IDs, names, and schemas of the active, unhidden Tables in the Database with `database-id`."+ [database-id limit]+ (t2/select [:model/Table :id :name :schema]+ :db_id database-id+ :active true+ :visibility_type nil+ {:limit limit}))++(defn active-tables-for-database+ "The presentable columns of the active Tables in the Database with `database-id`, ordered by schema and name."+ [database-id]+ (t2/select [:model/Table :id :name :display_name :schema :db_id :description]+ :db_id database-id+ :active true+ {:order-by [[:%lower.schema :asc] [:%lower.name :asc]]}))++(defn active-tables-in-schema+ "The presentable columns of the active Tables in `schema` of the Database with `database-id`, ordered by name."+ [database-id schema]+ (t2/select [:model/Table :id :name :display_name :schema :db_id :description]+ :db_id database-id+ :schema schema+ :active true+ {:order-by [[:%lower.name :asc]]}))++(defn active-schemas-for-database+ "The distinct `:schema` rows of the active Tables in the Database with `database-id`, ordered by schema."+ [database-id]+ (t2/query {:select-distinct [:schema]+ :from [:metabase_table]+ :where [:and [:= :db_id database-id] [:= :active true]]+ :order-by [[:schema :asc]]}))++(defn query-table-reference-where+ "The first Table ID, name, and schema matching the Honey SQL `where`, as a query table reference."+ [where]+ (t2/select-one :model/QueryTable+ {:select [[:t.id :table-id] [:t.name :table] [:t.schema :schema]]+ :from [[(t2/table-name :model/Table) :t]]+ :where where}))++(defn query-table-references-where+ "The Table IDs, names, and schemas matching the Honey SQL `where`, as query table references."+ [where]+ (t2/select :model/QueryTable+ {:select [[:t.id :table-id] [:t.name :table] [:t.schema :schema]]+ :from [[(t2/table-name :model/Table) :t]]+ :where where}))++;;; ------------------------------------------------- Fields -------------------------------------------------++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field :id field-id))++(defn field-fingerprint+ "The fingerprint of the Field with `field-id`."+ [field-id]+ (t2/select-one-fn :fingerprint :model/Field :id field-id))++(defn field-table-ids+ "A map of Field ID to Table ID for `field-ids`."+ [field-ids]+ (t2/select-fn->fn :id :table_id [:model/Field :id :table_id] :id [:in field-ids]))++;;; -------------------------------------------------- Cards --------------------------------------------------++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn card-by-entity-id+ "The Card with `entity-id`, or nil."+ [entity-id]+ (t2/select-one :model/Card :entity_id entity-id))++(defn card-of-type+ "The Card with `card-id` if it is of `type`, or nil."+ [card-id type]+ (t2/select-one :model/Card :id card-id :type type))++(defn card-type-row+ "The ID, type, and schema of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :id :type :card_schema] :id card-id))++(defn cards-where+ "The Cards matching the Honey SQL `query`."+ [query]+ (t2/select :model/Card query))++(defn card-entity-ids+ "A map of Card ID to entity ID for `card-ids`."+ [card-ids]+ (t2/select-pk->fn :entity_id :model/Card :id [:in card-ids]))++(defn card-table-ids+ "A map of Card ID to Table ID for `card-ids`."+ [card-ids]+ (t2/select-pk->fn :table_id :model/Card :id [:in card-ids]))++(defn card-search-rows+ "The searchable columns of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :name :description :database_id :collection_id :card_schema :type] :id [:in card-ids]))++(defn unarchived-card-summaries+ "The presentable columns of the unarchived Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :name :type :description :card_schema :collection_id :database_id :table_id]+ :id [:in card-ids]+ :archived false))++(defn cards-in-collection+ "The presentable columns of the unarchived Cards in the Collection with `collection-id`, ordered by name."+ [collection-id]+ (t2/select [:model/Card :id :name :type :description :card_schema :collection_id :database_id :table_id]+ {:where [:and [:= :collection_id collection-id] [:= :archived false]]+ :order-by [[:%lower.name :asc]]}))++(defn cards-for-table+ "The presentable columns of the unarchived Cards on the Table with `table-id`, ordered by name."+ [table-id]+ (t2/select [:model/Card :id :name :type :description :card_schema :collection_id :database_id :table_id]+ :table_id table-id+ :archived false+ {:order-by [[:%lower.name :asc]]}))++(defn models-for-database+ "The presentable columns of the unarchived model Cards on the Database with `database-id`, ordered by name."+ [database-id]+ (t2/select [:model/Card :id :name :type :description :card_schema :collection_id :database_id :table_id]+ :type :model+ :database_id database-id+ :archived false+ {:order-by [[:%lower.name :asc]]}))++(defn saved-cards-for-conversation+ "The ID and chart ID of the unarchived Cards saved from the MetabotConversation with `conversation-id`, in ID order."+ [conversation-id]+ (t2/select [:model/Card :id :metabot_chart_id]+ :metabot_conversation_id conversation-id+ :archived false+ {:order-by [[:id :asc]]}))++(defn link-card-to-conversation!+ "Record that the Card with `card-id` was saved from the MetabotConversation with `conversation-id` as `chart-id`."+ [card-id conversation-id chart-id]+ (t2/update! (t2/table-name :model/Card) card-id {:metabot_conversation_id conversation-id+ :metabot_chart_id chart-id}))++;;; ----------------------------------------------- Collections -----------------------------------------------++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn collection-name+ "The name of the Collection with `collection-id`."+ [collection-id]+ (t2/select-one-fn :name :model/Collection :id collection-id))++(defn collection-descriptions+ "A map of Collection ID to description for `collection-ids`."+ [collection-ids]+ (t2/select-pk->fn :description :model/Collection :id [:in collection-ids]))++(defn collection-summaries+ "The ID, name, and authority level of the Collections with `collection-ids`."+ [collection-ids]+ (t2/select [:model/Collection :id :name :authority_level] :id [:in collection-ids]))++(defn collection-curation-info-by-id+ "A map of ID to the ID, authority level, location, and type of the Collections with `collection-ids`."+ [collection-ids]+ (t2/select-pk->fn identity [:model/Collection :id :authority_level :location :type] :id [:in collection-ids]))++(defn navigable-collections+ "The presentable columns of the non-trash Collections in the default namespace, ordered by location and name.+ Restricted to top-level Collections unless `include-nested?`."+ [include-nested?]+ (t2/select [:model/Collection :id :name :location :authority_level :description :personal_owner_id]+ {:where (cond-> [:and+ [:= :archived false]+ [:= :namespace nil]+ [:or [:= :type nil] [:!= :type "trash"]]]+ (not include-nested?) (conj [:= :location "/"]))+ :order-by [[:location :asc] [:%lower.name :asc]]}))++(defn unarchived-collections-at-location+ "The presentable columns of the unarchived Collections directly at `location`, ordered by name."+ [location]+ (t2/select [:model/Collection :id :name :location :authority_level :description :personal_owner_id]+ :location location+ :archived false+ {:order-by [[:%lower.name :asc]]}))++(defn root-collections-of-types+ "The top-level Collections whose type is one of `types`."+ [types]+ (t2/select :model/Collection :type [:in types] :location "/"))++;;; ---------------------------------------------- Other models ----------------------------------------------++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard dashboard-id))++(defn dashboard-summary+ "The ID, description, name, and Collection ID of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one [:model/Dashboard :id :description :name :collection_id] dashboard-id))++(defn dashboard-name+ "The name of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-one-fn :name :model/Dashboard :id dashboard-id))++(defn dashboards-in-collection+ "The ID, name, description, and Collection ID of the unarchived Dashboards in the Collection with+ `collection-id`, ordered by name."+ [collection-id]+ (t2/select [:model/Dashboard :id :name :description :collection_id]+ :collection_id collection-id+ :archived false+ {:order-by [[:%lower.name :asc]]}))++(defn dashboard-tabs+ "The ID and name of the DashboardTabs of the Dashboard with `dashboard-id`, in position order."+ [dashboard-id]+ (t2/select [:model/DashboardTab :id :name] :dashboard_id dashboard-id {:order-by [[:position :asc] [:id :asc]]}))++(defn dashcards+ "The ID, Card, action, tab, and settings of the DashboardCards of the Dashboard with `dashboard-id`, in grid+ order."+ [dashboard-id]+ (t2/select [:model/DashboardCard :id :card_id :action_id :dashboard_tab_id :visualization_settings]+ :dashboard_id dashboard-id+ {:order-by [[:row :asc] [:col :asc]]}))++(defn documents-in-collection+ "The ID, name, Collection ID, and exploration of the unarchived, non-exploration Documents in the Collection with+ `collection-id`, ordered by name."+ [collection-id]+ (t2/select [:model/Document :id :name :collection_id :exploration_id]+ :collection_id collection-id+ :archived false+ :exploration_id nil+ {:order-by [[:%lower.name :asc]]}))++(defn unarchived-documents+ "The unarchived Documents with `document-ids`."+ [document-ids]+ (t2/select :model/Document :id [:in document-ids] :archived false))++(defn transforms+ "The Transforms with `transform-ids`."+ [transform-ids]+ (t2/select :model/Transform :id [:in transform-ids]))++(defn transforms-for-source-database+ "The ID, name, description, source Database, and source of the Transforms reading from the Database with+ `database-id`, ordered by name."+ [database-id]+ (t2/select [:model/Transform :id :name :description :source_database_id :source]+ :source_database_id database-id+ {:order-by [[:%lower.name :asc]]}))++(defn verified-item-ids+ "The subset of `item-ids` of `item-type` whose most recent moderation review is verified."+ [item-ids item-type]+ (t2/select-fn-set :moderated_item_id :model/ModerationReview+ :moderated_item_id [:in item-ids]+ :moderated_item_type item-type+ :most_recent true+ :status "verified"))++(defn latest-review-status-row+ "The `:status` row of the most recent moderation review of the item with `item-id` of `item-type`, or nil."+ [item-id item-type]+ (t2/select-one [:model/ModerationReview :status]+ :moderated_item_id item-id+ :moderated_item_type item-type+ :most_recent true+ {:order-by [[:id :desc]]}))++(defn glossary-count+ "The number of Glossary entries."+ []+ (t2/count :model/Glossary))++(defn glossary-definitions+ "A map of term to definition for the first `limit` Glossary entries ordered by `order-column` descending."+ [order-column limit]+ (t2/select-fn->fn :term :definition :model/Glossary+ {:order-by [[order-column :desc]]+ :limit limit}))++(defn user-summary+ "The ID, email, and names of the User with `user-id`."+ [user-id]+ (t2/select-one [:model/User :id :email :first_name :last_name] user-id))++(defn user-summaries-by-id+ "A map of ID to the ID, email, and names of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))++(defn card-collection-ids+ "The ID and Collection ID of the Cards with `ids`."+ [ids]+ (t2/select [:model/Card :id :collection_id] :id [:in ids]))++(defn dashboard-collection-ids+ "The ID and Collection ID of the Dashboards with `ids`."+ [ids]+ (t2/select [:model/Dashboard :id :collection_id] :id [:in ids]))++(defn measure-table-id+ "The Table ID of the Measure with `id`, or nil."+ [id]+ (t2/select-one-fn :table_id :model/Measure :id id))++(defn segment-table-id+ "The Table ID of the Segment with `id`, or nil."+ [id]+ (t2/select-one-fn :table_id :model/Segment :id id))++(defn measure-entity-id+ "The entity ID of the Measure with `id`."+ [id]+ (t2/select-one-fn :entity_id :model/Measure :id id))++(defn segment-entity-id+ "The entity ID of the Segment with `id`."+ [id]+ (t2/select-one-fn :entity_id :model/Segment :id id))++(defn measures+ "The ID, name, description, Table ID, and entity ID of the Measures with `ids`."+ [ids]+ (t2/select [:model/Measure :id :name :description :table_id :entity_id] :id [:in ids]))++(defn segments+ "The ID, name, description, Table ID, and entity ID of the Segments with `ids`."+ [ids]+ (t2/select [:model/Segment :id :name :description :table_id :entity_id] :id [:in ids]))diff --git a/src/metabase/metabot/feedback.clj b/src/metabase/metabot/feedback.cljindex 1737549487c..babd98c5c40 100644--- a/src/metabase/metabot/feedback.clj+++ b/src/metabase/metabot/feedback.clj@@ -3,8 +3,8 @@(:require[metabase.api.common :as api][metabase.app-db.core :as app-db]- [metabase.models.interface :as mi]- [toucan2.core :as t2]))+ [metabase.metabot.db :as metabot.db]+ [metabase.models.interface :as mi]))(set! *warn-on-reflection* true)@@ -14,11 +14,9 @@Throws 404 if the message is missing, the conversation is missing, or thecurrent user cannot read the conversation (superuser / originator / participant)."[external-id]- (let [message (t2/select-one [:model/MetabotMessage :id :conversation_id]- :external_id external-id)+ (let [message (metabot.db/message-by-external-id external-id)_ (api/check-404 message)- conversation (t2/select-one [:model/MetabotConversation :id :user_id]- :id (:conversation_id message))+ conversation (metabot.db/conversation-id-and-user-id (:conversation_id message))_ (api/check-404 conversation)_ (api/check-404 (mi/can-read? conversation))](assoc message :conversation conversation)))diff --git a/src/metabase/metabot/metadata_perms.clj b/src/metabase/metabot/metadata_perms.cljindex 666a660338a..df6f90135d8 100644--- a/src/metabase/metabot/metadata_perms.clj+++ b/src/metabase/metabot/metadata_perms.clj@@ -1,11 +1,11 @@(ns metabase.metabot.metadata-perms(:require[metabase.api.common :as api]+ [metabase.metabot.db :as metabot.db][metabase.metrics.core :as metrics][metabase.models.interface :as mi][metabase.permissions.core :as perms]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -37,7 +37,7 @@(defn- table-rows[table-ids](memoized :table-row table-ids- (fn [ids] (t2/select-fn->fn :id identity :model/Table :id [:in ids]))+ metabot.db/tables-by-idnil))(defn- permitted-table-ids@@ -127,6 +127,6 @@"Returns a `{field-id table-id}` map for the given `field-ids`."[field-ids](->> (memoized :field-table field-ids- (fn [ids] (t2/select-fn->fn :id :table_id [:model/Field :id :table_id] :id [:in ids]))+ metabot.db/field-table-idsnil)(into {} (remove #(nil? (val %))))))diff --git a/src/metabase/metabot/models/metabot.clj b/src/metabase/metabot/models/metabot.cljindex a5e0e3f90e9..de52a0ae2ea 100644--- a/src/metabase/metabot/models/metabot.clj+++ b/src/metabase/metabot/models/metabot.clj@@ -1,5 +1,6 @@(ns metabase.metabot.models.metabot(:require+ [metabase.metabot.db :as metabot.db][metabase.models.interface :as mi][metabase.models.serialization :as serdes][methodical.core :as methodical]@@ -31,7 +32,7 @@(mi/instances-with-hydrated-datametabots k#(group-by :metabot_id- (t2/select :model/MetabotPrompt {:where [:in :metabot_id (map :id metabots)]}))+ (metabot.db/prompts-for-metabots (map :id metabots))):id{:default []}))diff --git a/src/metabase/metabot/models/metabot_conversation.clj b/src/metabase/metabot/models/metabot_conversation.cljindex a793ecaf789..7063a180b2a 100644--- a/src/metabase/metabot/models/metabot_conversation.clj+++ b/src/metabase/metabot/models/metabot_conversation.clj@@ -1,6 +1,7 @@(ns metabase.metabot.models.metabot-conversation(:require[metabase.api.common :as api]+ [metabase.metabot.db :as metabot.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -16,9 +17,7 @@"True if `user-id` has sent at least one message in `conversation-id`."[conversation-id user-id](when (and conversation-id user-id)- (t2/exists? :model/MetabotMessage- :conversation_id conversation-id- :user_id user-id)))+ (metabot.db/participant? conversation-id user-id)))(defmethod mi/can-read? :model/MetabotConversation;; Access: superuser, or originator (first-writer, set on insert and never@@ -32,7 +31,7 @@(or (= originator-id user-id)(participant? conversation-id user-id))))))([_model pk]- (when-let [instance (t2/select-one [:model/MetabotConversation :id :user_id] :id pk)]+ (when-let [instance (metabot.db/conversation-id-and-user-id pk)](mi/can-read? instance))))(methodical/defmethod t2/batched-hydrate [:model/MetabotConversation :user]@@ -41,7 +40,5 @@[_model k conversations](mi/instances-with-hydrated-dataconversations k- #(t2/select-pk->fn (fn [u] (select-keys u [:id :email :first_name :last_name]))- [:model/User :id :email :first_name :last_name]- :id (keep :user_id conversations))+ #(metabot.db/user-summaries-by-id (keep :user_id conversations)):user_id {:default nil}))diff --git a/src/metabase/metabot/models/metabot_feedback.clj b/src/metabase/metabot/models/metabot_feedback.cljindex 2e5afa9999d..ef5d6d943f3 100644--- a/src/metabase/metabot/models/metabot_feedback.clj+++ b/src/metabase/metabot/models/metabot_feedback.clj@@ -1,6 +1,7 @@(ns metabase.metabot.models.metabot-feedback"Persist Metabot message feedback"(:require+ [metabase.metabot.db :as metabot.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -15,7 +16,5 @@[_model k feedbacks](mi/instances-with-hydrated-datafeedbacks k- #(t2/select-pk->fn (fn [u] (select-keys u [:id :email :first_name :last_name]))- [:model/User :id :email :first_name :last_name]- :id (keep :user_id feedbacks))+ #(metabot.db/user-summaries-by-id (keep :user_id feedbacks)):user_id {:default nil}))diff --git a/src/metabase/metabot/models/metabot_prompt.clj b/src/metabase/metabot/models/metabot_prompt.cljindex b64cb3d09cd..6a29dde8a5b 100644--- a/src/metabase/metabot/models/metabot_prompt.clj+++ b/src/metabase/metabot/models/metabot_prompt.clj@@ -1,5 +1,6 @@(ns metabase.metabot.models.metabot-prompt(:require+ [metabase.metabot.db :as metabot.db][metabase.models.interface :as mi][metabase.models.serialization :as serdes][methodical.core :as methodical]@@ -21,7 +22,7 @@;;; ------------------------------------------------- Serialization -------------------------------------------------(defmethod serdes/generate-path "MetabotPrompt" [_ entity]- (conj (serdes/generate-path "Metabot" (t2/select-one :model/Metabot (:metabot_id entity)))+ (conj (serdes/generate-path "Metabot" (metabot.db/metabot (:metabot_id entity)))(serdes/infer-self-path "MetabotPrompt" entity)))(defmethod serdes/deserialization-dependencies "MetabotPrompt" [prompt]diff --git a/src/metabase/metabot/models/metabot_source_feedback.clj b/src/metabase/metabot/models/metabot_source_feedback.cljindex aaa31fdab81..a215b292ae2 100644--- a/src/metabase/metabot/models/metabot_source_feedback.clj+++ b/src/metabase/metabot/models/metabot_source_feedback.clj@@ -1,6 +1,7 @@(ns metabase.metabot.models.metabot-source-feedback"Persist Metabot source feedback"(:require+ [metabase.metabot.db :as metabot.db][metabase.models.interface :as mi][methodical.core :as methodical][toucan2.core :as t2]))@@ -33,7 +34,5 @@[_model k feedbacks](mi/instances-with-hydrated-datafeedbacks k- #(t2/select-pk->fn (fn [u] (select-keys u [:id :email :first_name :last_name]))- [:model/User :id :email :first_name :last_name]- :id (keep :user_id feedbacks))+ #(metabot.db/user-summaries-by-id (keep :user_id feedbacks)):user_id {:default nil}))diff --git a/src/metabase/metabot/persistence.clj b/src/metabase/metabot/persistence.cljindex 1606e27e493..c3ea40eff11 100644--- a/src/metabase/metabot/persistence.clj+++ b/src/metabase/metabot/persistence.clj@@ -8,6 +8,7 @@[metabase.llm.provider :as llm.provider][metabase.metabot.agent.memory :as memory][metabase.metabot.agent.streaming :as streaming]+ [metabase.metabot.db :as metabot.db][metabase.metabot.schema :as metabot.schema][metabase.metabot.schema.migrate-v1-to-v2 :as migrate][metabase.metabot.schema.v2 :as schema.v2]@@ -179,27 +180,20 @@(defn live-messages"A conversation's non-deleted messages in reader order (created_at, id)."[conversation-id]- (t2/select :model/MetabotMessage- :conversation_id conversation-id- :deleted_at nil- {:order-by [[:created_at :asc] [:id :asc]]}))+ (metabot.db/live-messages conversation-id))(def ^:private opening-message-limit 10)(defn opening-messages"A conversation's first few non-deleted messages in reader order."[conversation-id]- (t2/select :model/MetabotMessage- :conversation_id conversation-id- :deleted_at nil- {:order-by [[:created_at :asc] [:id :asc]]- :limit opening-message-limit}))+ (metabot.db/opening-messages conversation-id opening-message-limit))(defmacro with-conversation-lock"Run `body` in a transaction holding a `FOR UPDATE` lock on the conversation row."[conversation-id & body]`(t2/with-transaction [_conn#]- (t2/select-one :model/MetabotConversation :id ~conversation-id {:for :update})+ (metabot.db/lock-conversation ~conversation-id)~@body))(defn soft-delete-messages!@@ -208,16 +202,13 @@must be non-empty — an empty map would match every message."[conditions deleted-by-user-id]{:pre [(seq conditions)]}- (t2/update! :model/MetabotMessage conditions- {:deleted_at [:now]- :deleted_by_user_id deleted-by-user-id}))+ (metabot.db/soft-delete-messages-where! conditions deleted-by-user-id))(defn- insert-assistant-placeholder!"Insert a turn's in-flight assistant row (`:finished` nil until[[finalize-assistant-turn!]] resolves it); returns its pk."[conversation-id profile-id external-id ai-proxy? & {:keys [user-id channel-id]}]- (t2/insert-returning-pk!- :model/MetabotMessage+ (metabot.db/insert-message-returning-pk!(cond-> {:conversation_id conversation-id:data []:data_version schema.v2/current-data-version@@ -307,19 +298,19 @@(assoc :slack_channel_id channel-id)(and slack-thread-ts (nil? (:slack_thread_ts existing)))(assoc :slack_thread_ts slack-thread-ts))))- (t2/insert! :model/MetabotMessage- (cond-> {:conversation_id conversation-id- :data (schema.v2/check-message-data "metabot_message.data"- [{:type "text" :text (:content user-message)}])- :data_version schema.v2/current-data-version- :role :user- :profile_id profile-id- :external_id user-external-id- :total_tokens 0- :ai_proxied (boolean ai-proxy?)}- originator-id (assoc :user_id originator-id)- channel-id (assoc :channel_id channel-id)- slack-msg-id (assoc :slack_msg_id slack-msg-id)))+ (metabot.db/insert-messages!+ (cond-> {:conversation_id conversation-id+ :data (schema.v2/check-message-data "metabot_message.data"+ [{:type "text" :text (:content user-message)}])+ :data_version schema.v2/current-data-version+ :role :user+ :profile_id profile-id+ :external_id user-external-id+ :total_tokens 0+ :ai_proxied (boolean ai-proxy?)}+ originator-id (assoc :user_id originator-id)+ channel-id (assoc :channel_id channel-id)+ slack-msg-id (assoc :slack_msg_id slack-msg-id)))(let [pk (insert-assistant-placeholder! conversation-id profile-id assistant-external-id ai-proxy?:user-id user-id:channel-id channel-id)]@@ -404,18 +395,18 @@(analytics/observe! :metabase-metabot/message-persist-bytes{:profile-id (or profile-id "unknown")}(u/string-byte-count (json/encode content)))- (t2/update! :model/MetabotMessage assistant-msg-id- (cond-> {:data content- :data_version schema.v2/current-data-version- :usage usage- :total_tokens (->> (vals usage)- (map #(+ (:prompt %) (:completion %)))- (reduce + 0))- :finished (boolean finished?)- :error (safe-encode-error error)}- turn-state (assoc :state turn-state)- slack-msg-id (assoc :slack_msg_id slack-msg-id)- channel-id (assoc :channel_id channel-id)))+ (metabot.db/update-message! assistant-msg-id+ (cond-> {:data content+ :data_version schema.v2/current-data-version+ :usage usage+ :total_tokens (->> (vals usage)+ (map #(+ (:prompt %) (:completion %)))+ (reduce + 0))+ :finished (boolean finished?)+ :error (safe-encode-error error)}+ turn-state (assoc :state turn-state)+ slack-msg-id (assoc :slack_msg_id slack-msg-id)+ channel-id (assoc :channel_id channel-id)));; Hand the (potentially slow) used-table extraction + insert off to a background worker *after* the message;; UPDATE commits, so it neither blocks nor fails the turn. The assistant row already exists, so its;; `message_id` FK is valid even before the UPDATE completes.@@ -425,12 +416,7 @@"The conversation's most recent, non-deleted assistant message, or nil.Filters to :assistant so a deleted trailing reply doesn't fall back to a user row."[conversation-id]- (t2/select-one :model/MetabotMessage- {:where [:and- [:= :conversation_id conversation-id]- [:= :deleted_at nil]- [:= :role "assistant"]]- :order-by [[:created_at :desc] [:id :desc]]}))+ (metabot.db/leaf-assistant-message conversation-id))(defn leaf-external-id"The [[leaf-message]]'s `external_id`, or nil."@@ -545,21 +531,19 @@"Backfill slack_msg_id on a MetabotMessage by primary key."[msg-id slack-msg-id](when (and msg-id slack-msg-id)- (t2/update! :model/MetabotMessage msg-id {:slack_msg_id slack-msg-id})))+ (metabot.db/update-message! msg-id {:slack_msg_id slack-msg-id})))(defn set-conversation-title-if-missing!"Set a conversation title only when it has not already been generated."[conversation-id title](when (and conversation-id (not (str/blank? title)))- (t2/update! :model/MetabotConversation- {:id conversation-id :title nil}- {:title title})))+ (metabot.db/set-conversation-title-if-missing! conversation-id title)))(defn conversation-title"Return the current persisted title for a conversation."[conversation-id](when conversation-id- (t2/select-one-fn :title :model/MetabotConversation :id conversation-id)))+ (metabot.db/conversation-title conversation-id)));;; ---------------------------------------- Chat message conversion ----------------------------------------@@ -799,7 +783,7 @@conversation participants may not be able to read; readers resolve names throughthe permission-checked card API."[conversation-id]- (when-let [conv (t2/select-one :model/MetabotConversation :id conversation-id)]+ (when-let [conv (metabot.db/conversation conversation-id)](let [messages (live-messages conversation-id)]{:conversation_id (:id conv):created_at (:created_at conv)@@ -810,10 +794,7 @@:saved_entities (mapv (fn [{:keys [id metabot_chart_id]}]{:card_id id:chart_id metabot_chart_id})- (t2/select [:model/Card :id :metabot_chart_id]- :metabot_conversation_id conversation-id- :archived false- {:order-by [[:id :asc]]}))+ (metabot.db/saved-cards-for-conversation conversation-id)):messages (messages->chat-messages messages)})));;; ---------------------------------------- Forking ----------------------------------------@@ -863,10 +844,8 @@(let [to-clone (conj (vec before) target)new-conversation-id (str (random-uuid))](t2/with-transaction [_conn]- (t2/insert! :model/MetabotConversation- {:id new-conversation-id- :user_id user-id- :forked_from_conversation_id conversation-id})- (t2/insert! :model/MetabotMessage- (mapv #(forked-message-row new-conversation-id user-id %) to-clone)))+ (metabot.db/insert-conversation! {:id new-conversation-id+ :user_id user-id+ :forked_from_conversation_id conversation-id})+ (metabot.db/insert-messages! (mapv #(forked-message-row new-conversation-id user-id %) to-clone)))new-conversation-id))))diff --git a/src/metabase/metabot/query_analyzer.clj b/src/metabase/metabot/query_analyzer.cljindex 2f74aa3279f..8cca3914868 100644--- a/src/metabase/metabot/query_analyzer.clj+++ b/src/metabase/metabot/query_analyzer.clj@@ -8,10 +8,10 @@[clojure.string :as str][metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.metabot.db :as metabot.db][metabase.metabot.query-analyzer.parameter-substitution :as nqa.sub][metabase.sql-tools.core :as sql-tools]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]));; NOTE: be careful when adding square braces, as the rules for nesting them are different.(def ^:private quotes "\"`")@@ -67,13 +67,10 @@([db-id table](table-reference db-id nil table))([db-id schema table]- (t2/select-one :model/QueryTable- {:select [[:t.id :table-id] [:t.name :table] [:t.schema :schema]]- :from [[(t2/table-name :model/Table) :t]]- :where [:and- [:= :t.db_id db-id]- (table-query {:schema (some-> schema name)- :table (name table)})]})))+ (metabot.db/query-table-reference-where [:and+ [:= :t.db_id db-id]+ (table-query {:schema (some-> schema name)+ :table (name table)})])))(defn- strip-redundant-table-refs"Strip out duplicate references, and unqualified references that are shadowed by found or qualified ones."@@ -103,12 +100,9 @@(consolidate-tablestables(when (seq tables)- (t2/select :model/QueryTable- {:select [[:t.id :table-id] [:t.name :table] [:t.schema :schema]]- :from [[(t2/table-name :model/Table) :t]]- :where [:and- [:= :t.db_id db-id]- (into [:or] (map table-query tables))]}))))+ (metabot.db/query-table-references-where [:and+ [:= :t.db_id db-id]+ (into [:or] (map table-query tables))]))))(defn- tables-via-sql-tools"Returns a set of table identifiers that (may) be referenced in the given card's query.diff --git a/src/metabase/metabot/suggested_prompts.clj b/src/metabase/metabot/suggested_prompts.cljindex bb99d9a655a..c869c282d30 100644--- a/src/metabase/metabot/suggested_prompts.clj+++ b/src/metabase/metabot/suggested_prompts.clj@@ -2,12 +2,12 @@(:require[medley.core :as m][metabase.lib-be.core :as lib-be]+ [metabase.metabot.db :as metabot.db][metabase.metabot.example-question-generator :as native-generator][metabase.metabot.tools.entity-details :as metabot.tools.entity-details][metabase.metabot.tools.util :as metabot.tools.u][metabase.metabot.usage :as metabot.usage]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -97,9 +97,9 @@model-prompts (vec (mapcat ->prompt table_questions models))total (+ (count metric-prompts) (count model-prompts))](when (seq metric-prompts)- (t2/insert! :model/MetabotPrompt metric-prompts))+ (metabot.db/insert-prompts! metric-prompts))(when (seq model-prompts)- (t2/insert! :model/MetabotPrompt model-prompts))+ (metabot.db/insert-prompts! model-prompts))(if (zero? total){:status :ai-produced-no-prompts}{:status :generated :prompt_count total})))))))@@ -107,4 +107,4 @@(defn delete-all-metabot-prompts"Drop suggested prompts for instance of Metabot."[metabot-id]- (t2/delete! :model/MetabotPrompt {:where [:= :metabot_id metabot-id]}))+ (metabot.db/delete-prompts-for-metabot! metabot-id))diff --git a/src/metabase/metabot/table_utils.clj b/src/metabase/metabot/table_utils.cljindex 49442d539fb..2ec46c415a9 100644--- a/src/metabase/metabot/table_utils.clj+++ b/src/metabase/metabot/table_utils.clj@@ -3,6 +3,7 @@(:require[clojure.set :as set][metabase.api.common :as api]+ [metabase.metabot.db :as metabot.db][metabase.metabot.query-analyzer :as query-analyzer][metabase.models.interface :as mi][metabase.util :as u]@@ -46,14 +47,11 @@{:perms/view-data :unrestricted:perms/create-queries :query-builder-and-native});; Fetch most viewed tables, excluding priority tables and excluded tables- fill-tables (t2/select [:model/Table :id :db_id :name :schema :description]- :db_id database-id- :active true- :visibility_type nil- (cond-> {:where table-where-clause- :order-by [[:view_count :desc]]- :limit all-tables-limit}- table-cte (assoc :with table-cte)))+ fill-tables (metabot.db/most-viewed-tables-where database-id+ (cond-> {:where table-where-clause+ :order-by [[:view_count :desc]]+ :limit all-tables-limit}+ table-cte (assoc :with table-cte)))fill-tables (remove #(or (priority-table-ids (:id %))(exclude-table-ids (:id %))) fill-tables)fill-tables (t2/hydrate fill-tables :fields)@@ -75,7 +73,7 @@This is the handler for the /get-tables tool endpoint."[{:keys [database-id]}]{:structured-output- {:database (t2/select-one [:model/Database :id :name :description :engine] database-id)+ {:database (metabot.db/database-summary database-id):tables (database-tables database-id)}})(defn similar?@@ -141,15 +139,12 @@(keep (fn [table](when (some #(matching-tables? table % {:match-schema? false}) unrecognized-tables)(t2.realize/realize table))))- (t2/reducible-select [:model/Table :id :name :schema :description]- :db_id database-id- :active true- :visibility_type nil- (cond-> (assoc (visible-filter-clause)- :limit 10000)- (seq used-ids) (update :where #(if %- [:and % [:not-in :id used-ids]]- [:not-in :id used-ids]))))))+ (metabot.db/visible-tables-reducible database-id+ (cond-> (assoc (visible-filter-clause)+ :limit 10000)+ (seq used-ids) (update :where #(if %+ [:and % [:not-in :id used-ids]]+ [:not-in :id used-ids]))))))(defn used-tables-from-ids"Return table info for `table-ids` in the same shape as [[used-tables]].@@ -158,12 +153,7 @@[database-id table-ids](if-not (seq table-ids)[]- (t2/select [:model/Table :id :name :schema :description]- :db_id database-id- :id [:in table-ids]- :active true- :visibility_type nil- (visible-filter-clause))))+ (metabot.db/visible-table-summaries-where database-id table-ids (visible-filter-clause))))(defn used-tables"Return all tables used in the query, including fuzzy-matched ones.@@ -252,11 +242,7 @@([query](schema-sample query nil))([{:keys [database] :as query} {:keys [all-tables-limit] :or {all-tables-limit max-schema-sample-tables}}]- (let [tables (t2/select [:model/Table :id :name :schema]- :db_id database- :active true- :visibility_type nil- {:limit (inc all-tables-limit)})+ (let [tables (metabot.db/table-names database (inc all-tables-limit))tables (if (> (count tables) all-tables-limit)(used-tables query)tables)diff --git a/src/metabase/metabot/task/conversation_title_backfill.clj b/src/metabase/metabot/task/conversation_title_backfill.cljindex aefff0d6ea4..daae1dfd5c5 100644--- a/src/metabase/metabot/task/conversation_title_backfill.clj+++ b/src/metabase/metabot/task/conversation_title_backfill.clj@@ -8,13 +8,13 @@[metabase.events.core :as events][metabase.metabot.config :as metabot.config][metabase.metabot.conversation-title :as conversation-title]+ [metabase.metabot.db :as metabot.db][metabase.metabot.persistence :as metabot.persistence][metabase.metabot.settings :as metabot.settings][metabase.metabot.usage :as metabot.usage][metabase.task.core :as task][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2])+ [methodical.core :as methodical])(:import(java.time Instant)(java.util Date)@@ -66,11 +66,7 @@(defn- titleless-conversation-ids[after-id]- (t2/select-fn-vec :id :model/MetabotConversation- {:where (cond-> [:and [:= :title nil]]- after-id (conj [:> :id after-id]))- :order-by [[:id :asc]]- :limit conversation-page-size}))+ (metabot.db/titleless-conversation-ids after-id conversation-page-size))(defn- title-source[conversation-id]diff --git a/src/metabase/metabot/task/metabot_conversation_trimmer.clj b/src/metabase/metabot/task/metabot_conversation_trimmer.cljindex 6199c4ce5c7..318368a3c09 100644--- a/src/metabase/metabot/task/metabot_conversation_trimmer.clj+++ b/src/metabase/metabot/task/metabot_conversation_trimmer.clj@@ -9,10 +9,10 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t]+ [metabase.metabot.db :as metabot.db][metabase.metabot.settings :as metabot.settings][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(org.quartz DisallowConcurrentExecution)))@@ -29,7 +29,7 @@(do(log/infof "Trimming metabot_conversation rows older than %d days." (long retention-days))(let [cutoff (t/minus (t/offset-date-time) (t/days (long retention-days)))- deleted (t2/delete! :model/MetabotConversation {:where [:< :created_at cutoff]})]+ deleted (metabot.db/delete-conversations-created-before! cutoff)](log/infof "Metabot conversation cleanup complete. Deleted %d conversations (messages/feedback removed by ON DELETE CASCADE)."(or deleted 0)))))))diff --git a/src/metabase/metabot/task/suggested_prompts_generator.clj b/src/metabase/metabot/task/suggested_prompts_generator.cljindex 51abcb11057..b157c007a4a 100644--- a/src/metabase/metabot/task/suggested_prompts_generator.clj+++ b/src/metabase/metabot/task/suggested_prompts_generator.clj@@ -4,13 +4,13 @@[clojurewerkz.quartzite.jobs :as jobs][clojurewerkz.quartzite.triggers :as triggers][metabase.metabot.config :as metabot.config]+ [metabase.metabot.db :as metabot.db][metabase.metabot.settings :as metabot.settings][metabase.metabot.suggested-prompts :as metabot.suggested-prompts][metabase.metabot.usage :as metabot.usage][metabase.request.core :as request][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.time Instant)(java.util Date)@@ -32,12 +32,12 @@(defn- generate-suggested-prompts-for-metabot! [config-id](let [metabot-eid (get-in metabot.config/metabot-config [config-id :entity-id])- metabot-id (t2/select-one-pk :model/Metabot :entity_id metabot-eid)]+ metabot-id (metabot.db/metabot-id-by-entity-id metabot-eid)](cond(nil? metabot-id)(log/warnf "No Metabot instance found for %s. Skipping suggested prompt generation." config-id)- (pos? (t2/count :model/MetabotPrompt :metabot_id metabot-id))+ (pos? (metabot.db/prompt-count-for-metabot metabot-id))(log/infof "Suggested prompts are present for %s. Not generating." config-id):elsediff --git a/src/metabase/metabot/tools/autogen_dashboard.clj b/src/metabase/metabot/tools/autogen_dashboard.cljindex 3ae6c03d635..cd8cd1f5c97 100644--- a/src/metabase/metabot/tools/autogen_dashboard.clj+++ b/src/metabase/metabot/tools/autogen_dashboard.clj@@ -3,11 +3,11 @@(:require[clojure.string :as str][metabase.metabot.agent.streaming :as streaming]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tools.shared :as shared][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -19,7 +19,7 @@[{:keys [table_id model_id metric_id query_id report_id]} memory](condtable_id- (let [table (t2/select-one :model/Table :id table_id)]+ (let [table (metabot.db/table table_id)](when-not table(throw (ex-info (str "Table not found with ID: " table_id){:agent-error? true :table-id table_id})))@@ -27,7 +27,7 @@:path (str "/auto/dashboard/table/" table_id)})model_id- (let [model (t2/select-one :model/Card :id model_id :type :model)]+ (let [model (metabot.db/card-of-type model_id :model)](when-not model(throw (ex-info (str "Model not found with ID: " model_id){:agent-error? true :model-id model_id})))@@ -35,7 +35,7 @@:path (str "/auto/dashboard/model/" model_id)})metric_id- (let [metric (t2/select-one :model/Card :id metric_id :type :metric)]+ (let [metric (metabot.db/card-of-type metric_id :metric)](when-not metric(throw (ex-info (str "Metric not found with ID: " metric_id){:agent-error? true :metric-id metric_id})))@@ -43,7 +43,7 @@:path (str "/auto/dashboard/metric/" metric_id)})report_id- (let [report (t2/select-one :model/Card :id report_id :type :question)]+ (let [report (metabot.db/card-of-type report_id :question)](when-not report(throw (ex-info (str "Report/Question not found with ID: " report_id){:agent-error? true :report-id report_id})))diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.cljindex 9ac2d6fd20f..9fd6aae77d7 100644--- a/src/metabase/metabot/tools/construct.clj+++ b/src/metabase/metabot/tools/construct.clj@@ -12,6 +12,7 @@[metabase.lib.schema.expression :as lib.schema.expression][metabase.metabot.agent.links :as links][metabase.metabot.agent.streaming :as streaming]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tmpl :as te][metabase.metabot.tools.charts.create :as create-chart-tools]@@ -26,8 +27,7 @@[metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(set! *warn-on-reflection* true)@@ -265,7 +265,7 @@(detect-metabase-uri-source-table! parsed-query)(if-let [table-fk (first-stage-source-table-fk parsed-query)](let [db-name (nth table-fk 0)- ids (t2/select-pks-vec :model/Database :name db-name)]+ ids (metabot.db/database-ids-by-name db-name)](case (count ids)0 (throw (ex-info (tru (str "Unknown database: `{0}`. Use the exact database name as ""reported by search / `read_resource` (it appears "diff --git a/src/metabase/metabot/tools/create_alert.clj b/src/metabase/metabot/tools/create_alert.cljindex 123ecdcd68b..2eaf152dc8a 100644--- a/src/metabase/metabot/tools/create_alert.clj+++ b/src/metabase/metabot/tools/create_alert.clj@@ -5,14 +5,14 @@[clojure.set :as set][metabase.api.common :as api][metabase.channel.settings :as channel.settings]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tools.shared :as shared][metabase.metabot.tools.util :as metabot.tools.u][metabase.notification.api :as notification.api][metabase.util.cron :as u.cron][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -27,7 +27,7 @@"Private helper for create-alert (call that instead)."[{:keys [card-id slack-channel schedule send-condition send-once]:or {send-once false}}]- (let [card (some-> (t2/select-one :model/Card card-id) api/read-check)+ (let [card (some-> (metabot.db/card card-id) api/read-check)channel-name (some->> slack-channelchannel.settings/find-cached-slack-channel-or-username:display-name)]diff --git a/src/metabase/metabot/tools/create_dashboard_subscription.clj b/src/metabase/metabot/tools/create_dashboard_subscription.cljindex 038d92d0be6..4211e26576e 100644--- a/src/metabase/metabot/tools/create_dashboard_subscription.clj+++ b/src/metabase/metabot/tools/create_dashboard_subscription.clj@@ -3,6 +3,7 @@[clojure.set :as set][metabase.api.common :as api][metabase.channel.settings :as channel.settings]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tools.create-alert :as tools.create-alert][metabase.metabot.tools.shared :as shared]@@ -23,7 +24,7 @@(defn- create-dashboard-subscription*"Private helper for create-dashboard-subscription (call that instead)."[{:keys [dashboard-id slack-channel schedule]}]- (let [dashboard (some-> (t2/select-one :model/Dashboard dashboard-id)+ (let [dashboard (some-> (metabot.db/dashboard dashboard-id)api/read-check(t2/hydrate [:dashcards :card]))cards (for [{:keys [id card]} (:dashcards dashboard)diff --git a/src/metabase/metabot/tools/entity_details.clj b/src/metabase/metabot/tools/entity_details.cljindex 4ff37d1ea01..0abd384a2b2 100644--- a/src/metabase/metabot/tools/entity_details.clj+++ b/src/metabase/metabot/tools/entity_details.clj@@ -9,6 +9,7 @@[metabase.lib.metadata :as lib.metadata][metabase.lib.types.isa :as lib.types.isa][metabase.metabot.config :as metabot.config]+ [metabase.metabot.db :as metabot.db][metabase.metabot.metadata-perms :as metabot.perms][metabase.metabot.tools.shared.content-store :as shared.content-store][metabase.metabot.tools.util :as metabot.tools.u]@@ -29,7 +30,9 @@`model-key` is `:model/Measure` or `:model/Segment`."[model-key id](when id- (t2/select-one-fn :entity_id model-key :id id)))+ (case model-key+ :model/Measure (metabot.db/measure-entity-id id)+ :model/Segment (metabot.db/segment-entity-id id))))(defn- convert-measure-or-segment"Convert a measure or segment metadata object to the format expected by the API.@@ -74,11 +77,7 @@(defn verified-review?"Return true if the most recent ModerationReview for the given item id/type is verified."[id item-type]- (let [review (t2/select-one [:model/ModerationReview :status]- :moderated_item_id id- :moderated_item_type item-type- :most_recent true- {:order-by [[:id :desc]]})]+ (let [review (metabot.db/latest-review-status-row id item-type)](= (:status review) "verified")))(def ^:private max-glossary-items@@ -92,22 +91,20 @@(defn- glossary-for-context[];; Rather small glossary sizes are anticipated. Additional count is bearable.- (let [glossary-size (t2/count :model/Glossary)]+ (let [glossary-size (metabot.db/glossary-count)](when (> glossary-size max-glossary-items);; If we are notified about the following warning we should reconsider current,;; context injection, approach to glossary integration into Metabot.(log/warnf "Glossary size is larger than limit for context injection (%d > %d)."glossary-size max-glossary-items)))- (not-empty (t2/select-fn->fn :term :definition :model/Glossary- {:order-by [[glossary-order-column :desc]]- :limit max-glossary-items})))+ (not-empty (metabot.db/glossary-definitions glossary-order-column max-glossary-items)))(defn get-current-user"Get information about the current user."[_args](if-let [{:keys [id email first_name last_name]}(or (some-> api/*current-user* deref)- (t2/select-one [:model/User :id :email :first_name :last_name] api/*current-user-id*))]+ (metabot.db/user-summary api/*current-user-id*))]{:structured-output (merge {:id id:type :user:name (str first_name " " last_name)@@ -122,7 +119,7 @@(when-not (int? dashboard-id)(throw (ex-info "Invalid dashboard_id format"{:agent-error? true :status-code 400})))- (if-let [dashboard (t2/select-one [:model/Dashboard :id :description :name :collection_id] dashboard-id)]+ (if-let [dashboard (metabot.db/dashboard-summary dashboard-id)](do (api/read-check dashboard){:structured-output(-> dashboard@@ -137,7 +134,7 @@[id->values id](if-some [field-values (get id->values id)](:values field-values)- (let [field (t2/select-one :model/Field :id id)]+ (let [field (metabot.db/field id)](when (and field(params.field-values/current-user-can-fetch-field-values? field))(:values (params.field-values/get-or-create-field-values! field))))))@@ -825,10 +822,10 @@(metabot.tools.u/handle-agent-error e)))))(def ^:private measure-or-segment-dispatch- "Per-`kind` config for `measure-or-segment-details`: the app-DB model, the lib-metadata fetcher,- and the `convert-measure-or-segment` definition key."- {:measure {:model :model/Measure, :lookup-fn lib.metadata/measure, :definition-key :aggregation}- :segment {:model :model/Segment, :lookup-fn lib.metadata/segment, :definition-key :filters}})+ "Per-`kind` config for `measure-or-segment-details`: the lib-metadata fetcher and the+ `convert-measure-or-segment` definition key."+ {:measure {:lookup-fn lib.metadata/measure, :definition-key :aggregation}+ :segment {:lookup-fn lib.metadata/segment, :definition-key :filters}})(mu/defn- measure-or-segment-details"Build drill-in detail for a single measure or segment by numeric `id`.@@ -837,13 +834,15 @@shape matches the nested measures/segments `table-details` already emits."[kind :- [:enum :measure :segment]id :- :int]- (let [{:keys [model lookup-fn definition-key]} (measure-or-segment-dispatch kind)- row (t2/select-one [model :id :table_id] :id id)]- (when-not row+ (let [{:keys [lookup-fn definition-key]} (measure-or-segment-dispatch kind)+ table-id (case kind+ :measure (metabot.db/measure-table-id id)+ :segment (metabot.db/segment-table-id id))]+ (when-not table-id(throw (ex-info (format "%s %s not found" (name kind) id){:agent-error? true :status-code 404})));; Measure/segment perms delegate to the parent Table, so read-checking it gates access.- (let [table (api/read-check :model/Table (:table_id row))+ (let [table (api/read-check :model/Table table-id)db-id (:db_id table)mp (lib-be/application-database-metadata-provider db-id)database (lib.metadata/database mp)@@ -908,8 +907,7 @@(let [options (cond-> arguments(= (:with-field-values? arguments) false) (assoc :field-values-fn identity))details (if (int? report-id)- (let [card (t2/hydrate (metabot.tools.u/get-card report-id)- :average_query_time)+ (let [card (t2/hydrate (metabot.tools.u/get-card report-id) :average_query_time)mp (lib-be/application-database-metadata-provider (:database_id card));; The select-keys below drops :related_tables and :metrics, so don't compute them. On;; wide-FK source tables the related-tables cost can be substantial (metabase#76493).diff --git a/src/metabase/metabot/tools/field_stats.clj b/src/metabase/metabot/tools/field_stats.cljindex e49567ecf2f..a4c0515ee7c 100644--- a/src/metabase/metabot/tools/field_stats.clj+++ b/src/metabase/metabot/tools/field_stats.clj@@ -3,12 +3,12 @@[clojure.set :as set][metabase.api.common :as api][metabase.lib.core :as lib]+ [metabase.metabot.db :as metabot.db][metabase.metabot.metadata-perms :as metabot.perms][metabase.metabot.tools.util :as metabot.tools.u][metabase.parameters.field-values :as params.field-values][metabase.request.core :as request]- [metabase.sync.core :as sync]- [toucan2.core :as t2]))+ [metabase.sync.core :as sync]))(defn- build-field-statistics [fvs fp limit](merge@@ -23,7 +23,7 @@(or fingerprint;; Run with admin perms to match behavior during normal sync.(and (pos? (:updated-fingerprints (request/as-admin (sync/refingerprint-field! field))))- (t2/select-one-fn :fingerprint :model/Field :id id))))+ (metabot.db/field-fingerprint id))))(defn- field-statistics"Fingerprint statistics are global (computed across every row of the table), so they're withheld@@ -34,7 +34,7 @@caller's column metadata, since saved Card result metadata can be stale or user-edited."[{:keys [id fingerprint]} limit](if id- (let [field (t2/select-one :model/Field :id id)+ (let [field (metabot.db/field id)table-id (:table_id field)fvs (params.field-values/get-or-create-field-values! field)restricted? (or (not (int? table-id))diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.cljindex 66b841b70ed..3389875c295 100644--- a/src/metabase/metabot/tools/resources.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -71,6 +71,7 @@[metabase.documents.core :as documents][metabase.documents.prose-mirror :as prose-mirror][metabase.metabot.agent.streaming :as streaming]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tmpl :as te][metabase.metabot.tools.entity-details :as entity-details]@@ -87,8 +88,7 @@[metabase.util.malli :as mu][metabase.util.match :as match][metabase.warehouses.core :as warehouses]- [ring.util.codec :as codec]- [toucan2.core :as t2]))+ [ring.util.codec :as codec]))(set! *warn-on-reflection* true)@@ -281,7 +281,7 @@(defn- present-source-card"Resolve a source-card id to a typed item map (model / metric / question)."[source-card-id]- (let [src-card (t2/select-one [:model/Card :id :type :card_schema] :id source-card-id)+ (let [src-card (metabot.db/card-type-row source-card-id)src-type (case (:type src-card):model "model":metric "metric"@@ -313,10 +313,7 @@;; ----- Fetch handlers (one per URI shape) -----(defn- fetch-databases-list [query-params]- (let [all (t2/select [:model/Database :id :name :engine :description :is_audit]- :is_audit false- :router_database_id nil- {:order-by [[:%lower.name :asc]]})+ (let [all (metabot.db/non-audit-databases)_ (perms/prime-database-perms-cache {:db-ids (into #{} (map :id) all)})dbs (->> all(filter mi/can-read?)@@ -327,16 +324,7 @@"metabase://collections (root only) and metabase://collections?tree=true (flat list of all)."[{:keys [tree] :as query-params}](let [tree? (= "true" tree)- where (cond-> [:and- [:= :archived false]- [:= :namespace nil]- ;; Exclude the system Trash collection from navigation listings.- [:or [:= :type nil] [:!= :type "trash"]]]- (not tree?) (conj [:= :location "/"]))- colls (->> (t2/select [:model/Collection :id :name :location :authority_level- :description :personal_owner_id]- {:where where- :order-by [[:location :asc] [:%lower.name :asc]]})+ colls (->> (metabot.db/navigable-collections tree?)(filter mi/can-read?));; For tree mode, compute path names by chaining ancestor names.id->name (when tree? (into {} (map (juxt :id :name)) colls))@@ -384,10 +372,7 @@(let [db-id (parse-long id-str)_ (warehouses/get-database db-id)_ (perms/prime-table-perms-cache {:db-ids #{db-id}})- tables (->> (t2/select [:model/Table :id :name :display_name :schema :db_id :description]- :db_id db-id- :active true- {:order-by [[:%lower.schema :asc] [:%lower.name :asc]]})+ tables (->> (metabot.db/active-tables-for-database db-id)(filter mi/can-read?)(mapv present-table))](list-result :database-tables tables query-params)))@@ -395,12 +380,7 @@(defn- fetch-database-models [id-str query-params](let [db-id (parse-long id-str)_ (warehouses/get-database db-id)- models (->> (t2/select [:model/Card :id :name :type :description :card_schema- :collection_id :database_id :table_id]- :type :model- :database_id db-id- :archived false- {:order-by [[:%lower.name :asc]]})+ models (->> (metabot.db/models-for-database db-id)(filter mi/can-read?)(mapv present-card))](list-result :database-models models query-params)))@@ -408,11 +388,7 @@(defn- fetch-database-schemas [id-str query-params](let [db-id (parse-long id-str)_ (warehouses/get-database db-id)- rows (t2/query- {:select-distinct [:schema]- :from [:metabase_table]- :where [:and [:= :db_id db-id] [:= :active true]]- :order-by [[:schema :asc]]})+ rows (metabot.db/active-schemas-for-database db-id)schemas (->> rows(keep :schema)(mapv (fn [s]@@ -425,11 +401,7 @@(defn- fetch-database-schema-tables [id-str schema-name query-params](let [db-id (parse-long id-str)_ (warehouses/get-database db-id)- tables (->> (t2/select [:model/Table :id :name :display_name :schema :db_id :description]- :db_id db-id- :schema schema-name- :active true- {:order-by [[:%lower.name :asc]]})+ tables (->> (metabot.db/active-tables-in-schema db-id schema-name)(filter mi/can-read?)(mapv present-table))](list-result :database-schema-tables tables query-params)))@@ -444,28 +416,14 @@(documents/with-content-gate-cache(let [coll-id (parse-long id-str)coll (api/read-check :model/Collection coll-id)- cards (->> (t2/select [:model/Card :id :name :type :description :card_schema- :collection_id :database_id :table_id]- {:where [:and [:= :collection_id coll-id] [:= :archived false]]- :order-by [[:%lower.name :asc]]})+ cards (->> (metabot.db/cards-in-collection coll-id)(filter mi/can-read?))- dashboards (->> (t2/select [:model/Dashboard :id :name :description :collection_id]- :collection_id coll-id- :archived false- {:order-by [[:%lower.name :asc]]})+ dashboards (->> (metabot.db/dashboards-in-collection coll-id)(filter mi/can-read?));; Exploration Summary documents are only through their exploration — so they stay out of this listing- documents (->> (t2/select [:model/Document :id :name :collection_id :exploration_id]- :collection_id coll-id- :archived false- :exploration_id nil- {:order-by [[:%lower.name :asc]]})+ documents (->> (metabot.db/documents-in-collection coll-id)(filter mi/can-read?))- subcollections (->> (t2/select [:model/Collection :id :name :location :authority_level- :description :personal_owner_id]- :location (str (:location coll) coll-id "/")- :archived false- {:order-by [[:%lower.name :asc]]})+ subcollections (->> (metabot.db/unarchived-collections-at-location (str (:location coll) coll-id "/"))(filter mi/can-read?))items (concat (map present-collection subcollections)(map present-card cards)@@ -476,11 +434,7 @@(defn- fetch-collection-subcollections [id-str query-params](let [coll-id (parse-long id-str)coll (api/read-check :model/Collection coll-id)- subs (->> (t2/select [:model/Collection :id :name :location :authority_level- :description :personal_owner_id]- :location (str (:location coll) coll-id "/")- :archived false- {:order-by [[:%lower.name :asc]]})+ subs (->> (metabot.db/unarchived-collections-at-location (str (:location coll) coll-id "/"))(filter mi/can-read?)(mapv present-collection))](list-result :collection-subcollections subs query-params)))@@ -511,7 +465,9 @@(check-resource-database (:database_id card))))(defn- check-measure-or-segment-resource-database [model id]- (when-let [table-id (t2/select-one-fn :table_id model :id id)]+ (when-let [table-id (case model+ :model/Measure (metabot.db/measure-table-id id)+ :model/Segment (metabot.db/segment-table-id id))](check-table-resource-database table-id)))(defn- table-details@@ -548,11 +504,7 @@table (api/read-check :model/Table table-id)db-id (:db_id table)_ (check-resource-database db-id)- cards (->> (t2/select [:model/Card :id :name :type :description :card_schema- :collection_id :database_id :table_id]- :table_id table-id- :archived false- {:order-by [[:%lower.name :asc]]})+ cards (->> (metabot.db/cards-for-table table-id)(filter mi/can-read?)(mapv present-card));; SQL-narrow transforms by source_database_id (a transform can only reference@@ -560,10 +512,7 @@;; table ids in memory — no per-row re-fetch. Apply the can-read? check last,;; on the already-narrowed candidate set.transforms (when db-id- (->> (t2/select [:model/Transform :id :name :description- :source_database_id :source]- :source_database_id db-id- {:order-by [[:%lower.name :asc]]})+ (->> (metabot.db/transforms-for-source-database db-id)(filter (fn [t] (some #{table-id} (transform-source-table-ids t))))(filter mi/can-read?)(mapv present-transform)))]@@ -638,8 +587,7 @@(let [transform (transforms/get-transform (parse-long id-str))source-table-ids (transform-source-table-ids transform)source-tables (when (seq source-table-ids)- (->> (t2/select [:model/Table :id :name :display_name :schema :db_id :description]- :id [:in (set source-table-ids)])+ (->> (metabot.db/table-summaries (set source-table-ids))(filter mi/can-read?)(mapv present-table)))db-id (:source_database_id transform)@@ -709,18 +657,11 @@[id-str query-params](let [dashboard-id (parse-long id-str)_ (api/read-check :model/Dashboard dashboard-id)- tabs (t2/select [:model/DashboardTab :id :name] :dashboard_id dashboard-id- {:order-by [[:position :asc] [:id :asc]]})- dashcards (t2/select [:model/DashboardCard :id :card_id :action_id :dashboard_tab_id- :visualization_settings]- :dashboard_id dashboard-id- {:order-by [[:row :asc] [:col :asc]]})+ tabs (metabot.db/dashboard-tabs dashboard-id)+ dashcards (metabot.db/dashcards dashboard-id)card-ids (into #{} (keep :card_id) dashcards)readable (when (seq card-ids)- (->> (t2/select [:model/Card :id :name :type :description :card_schema- :collection_id :database_id :table_id]- :id [:in card-ids]- :archived false)+ (->> (metabot.db/unarchived-card-summaries card-ids)(filter mi/can-read?)(into {} (map (juxt :id identity)))))->item (fn [{:keys [id card_id action_id] :as dashcard}]diff --git a/src/metabase/metabot/tools/save_entity.clj b/src/metabase/metabot/tools/save_entity.cljindex 03cf33895ad..7a62feab40c 100644--- a/src/metabase/metabot/tools/save_entity.clj+++ b/src/metabase/metabot/tools/save_entity.clj@@ -14,6 +14,7 @@[metabase.events.core :as events][metabase.metabot.agent.links :as links][metabase.metabot.agent.streaming :as streaming]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tmpl :as te][metabase.metabot.tools.shared :as shared]@@ -87,7 +88,7 @@[collection-id](if (nil? collection-id)(:name (collection/root-collection-with-ui-details nil))- (t2/select-one-fn :name :model/Collection :id collection-id)))+ (metabot.db/collection-name collection-id)))(defn- save-to-collection![{:keys [name description dataset_query display destination]}]@@ -128,7 +129,7 @@:delay-event)]{:card card:destination {:type "dashboard" :id dashboard-id}- :destination-name (t2/select-one-fn :name :model/Dashboard :id dashboard-id)+ :destination-name (metabot.db/dashboard-name dashboard-id):link (str "metabase://dashboard/" dashboard-id)})))(defn- save-to-document!@@ -215,9 +216,7 @@"dashboard" (save-to-dashboard! args)"document" (save-to-document! args))](when-let [conversation-id (shared/current-conversation-id)]- (t2/update! (t2/table-name :model/Card) (:id (:card saved))- {:metabot_conversation_id conversation-id- :metabot_chart_id chart_id}))+ (metabot.db/link-card-to-conversation! (:id (:card saved)) conversation-id chart_id))saved))_ (events/publish-event! :event/card-create{:object card :user-id api/*current-user-id*})diff --git a/src/metabase/metabot/tools/search.clj b/src/metabase/metabot/tools/search.cljindex 98517e1d973..314af5f59d5 100644--- a/src/metabase/metabot/tools/search.clj+++ b/src/metabase/metabot/tools/search.clj@@ -6,6 +6,7 @@[metabase.api.common :as api][metabase.metabot.agent.streaming :as streaming][metabase.metabot.config :as metabot.config]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.search-models :as metabot.search-models][metabase.metabot.tmpl :as te]@@ -19,8 +20,7 @@[metabase.transforms.core :as transforms][metabase.util :as u][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -97,7 +97,7 @@[results](let [coll-ids (->> results (keep #(get-in % [:collection :id])) distinct)descriptions (when (seq coll-ids)- (t2/select-pk->fn :description :model/Collection :id [:in coll-ids]))]+ (metabot.db/collection-descriptions coll-ids))](cond->> results(seq descriptions) (mapv (fn [r](let [cid (-> r :collection :id)]@@ -112,10 +112,10 @@[results](let [db-ids (->> results (keep :database_id) distinct)id->db (when (seq db-ids)- (t2/select-pk->fn (juxt :engine :name) :model/Database :id [:in db-ids]))]+ (metabot.db/database-engines-and-names db-ids))](cond->> results(seq id->db) (mapv (fn [r]- (let [[engine db-name] (get id->db (:database_id r))]+ (let [{engine :engine, db-name :name} (get id->db (:database_id r))](-> r(m/assoc-some :database_engine engine)(m/assoc-some :database_name db-name))))))))@@ -132,7 +132,7 @@(keep :id)distinct)id->eid (when (seq card-ids)- (t2/select-pk->fn :entity_id :model/Card :id [:in card-ids]))]+ (metabot.db/card-entity-ids card-ids))](cond->> results(seq id->eid) (mapv (fn [r](if-let [eid (and (carded-types (:type r))@@ -160,14 +160,13 @@[results](let [metric-ids (->> results (filter #(= "metric" (:type %))) (keep :id) distinct)card-id->table-id (when (seq metric-ids)- (t2/select-pk->fn :table_id :model/Card :id [:in metric-ids]))+ (metabot.db/card-table-ids metric-ids))table-ids (->> card-id->table-id vals (remove nil?) distinct)table-id->info (when (seq table-ids)(into {}(comp (filter mi/can-read?)(map (juxt :id (juxt :schema :name))))- (t2/select [:model/Table :id :schema :name :db_id]- :id [:in table-ids])))+ (metabot.db/table-schema-rows table-ids)))metric-id->table-info(into {}(keep (fn [[metric-id table-id]]@@ -196,7 +195,7 @@[results](let [transform-ids (->> results (filter #(= "transform" (:type %))) (map :id) set)readable-ids (when (seq transform-ids)- (->> (t2/select :model/Transform :id [:in transform-ids])+ (->> (metabot.db/transforms transform-ids)transforms/add-source-readable(filter :source_readable)(map :id)@@ -215,9 +214,7 @@[results](let [document-ids (->> results (filter #(= "document" (:type %))) (map :id) set)id->document (when (seq document-ids)- (->> (t2/select :model/Document- :id [:in document-ids]- :archived false)+ (->> (metabot.db/unarchived-documents document-ids)(filter mi/can-read?)(map (juxt :id identity))(into {})))]@@ -303,7 +300,7 @@(set (distinct (keep metabot.search-models/entity-type->search-model entity-types)))metabot-search-models)_ (log/infof "[METABOT-SEARCH] Converted entity-types %s to search-models %s" entity-types search-models)- metabot (t2/select-one :model/Metabot :entity_id (get-in metabot.config/metabot-config [metabot-id :entity-id] metabot-id))+ metabot (metabot.db/metabot-by-entity-id (get-in metabot.config/metabot-config [metabot-id :entity-id] metabot-id))use-verified? (if metabot-id(:use_verified_content metabot)false)@@ -378,7 +375,7 @@(when (seq ids);; only surface tables the current user can read — a curated entry may point at one they can't access(for [t (filter mi/can-read?- (t2/select [:model/Table :id :name :display_name :db_id :schema :description] :id [:in ids]))]+ (metabot.db/table-summaries ids))]{:id (:id t):type "table":name (:name t)@@ -397,18 +394,14 @@id->card (when (seq ids)(into {} (map (juxt :id identity))(filter mi/can-read?- (t2/select [:model/Card :id :name :description :database_id :collection_id- :card_schema :type]- :id [:in ids]))))+ (metabot.db/card-search-rows ids))))coll-ids (->> (vals id->card) (keep :collection_id) distinct)id->coll (when (seq coll-ids)(into {} (map (juxt :id identity))- (t2/select [:model/Collection :id :name :authority_level] :id [:in coll-ids])))+ (metabot.db/collection-summaries coll-ids)));; verified is already a set (t2/select-fn-set), possibly nil when there were no idsverified (when (seq ids)- (t2/select-fn-set :moderated_item_id :model/ModerationReview- :moderated_item_id [:in ids] :moderated_item_type "card"- :most_recent true :status "verified"))]+ (metabot.db/verified-item-ids ids "card"))](for [id ids:let [c (id->card id)]:when c]@@ -431,16 +424,15 @@[refs](when (seq refs)(let [by-type (group-by :type refs)- fetch (fn [model ids]+ fetch (fn [db-fn ids](when-let [ids (not-empty (distinct ids))]- (filter mi/can-read?- (t2/select [model :id :name :description :table_id :entity_id] :id [:in ids]))))- rows (concat (map #(assoc % :type "measure") (fetch :model/Measure (map :id (get by-type "measure"))))- (map #(assoc % :type "segment") (fetch :model/Segment (map :id (get by-type "segment")))))+ (filter mi/can-read? (db-fn ids))))+ rows (concat (map #(assoc % :type "measure") (fetch metabot.db/measures (map :id (get by-type "measure"))))+ (map #(assoc % :type "segment") (fetch metabot.db/segments (map :id (get by-type "segment")))))tbl-ids (not-empty (distinct (keep :table_id rows)))id->tbl (when tbl-ids(into {} (map (juxt :id identity))- (t2/select [:model/Table :id :name :schema :db_id] :id [:in tbl-ids])))]+ (metabot.db/table-schema-rows tbl-ids)))](for [{:keys [id type name description table_id entity_id]} rows:let [t (get id->tbl table_id)]](cond-> {:id id :type type :name name :description description}diff --git a/src/metabase/metabot/tools/sql/create.clj b/src/metabase/metabot/tools/sql/create.cljindex 0c897231bce..3f5ced0f87b 100644--- a/src/metabase/metabot/tools/sql/create.clj+++ b/src/metabase/metabot/tools/sql/create.clj@@ -4,13 +4,13 @@[metabase.api.common :as api][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]+ [metabase.metabot.db :as metabot.db][metabase.metabot.tools.sql.common :as metabot.tools.sql.common][metabase.metabot.tools.sql.validation :as metabot.tools.sql.validation][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -26,7 +26,7 @@(defn- validate-database-access"Check if the current user has access to the database."[database-id]- (when-not (t2/exists? :model/Database :id database-id)+ (when-not (metabot.db/database-exists? database-id)(throw (ex-info (tru "Database {0} not found" database-id){:agent-error? true:database-id database-id})))diff --git a/src/metabase/metabot/tools/subscriptions.clj b/src/metabase/metabot/tools/subscriptions.cljindex e7526362a96..bf63ac92c92 100644--- a/src/metabase/metabot/tools/subscriptions.clj+++ b/src/metabase/metabot/tools/subscriptions.clj@@ -4,6 +4,7 @@[clojure.set :as set][metabase.api.common :as api][metabase.channel.settings :as channel.settings]+ [metabase.metabot.db :as metabot.db][metabase.metabot.scope :as scope][metabase.metabot.tools.util :as metabot.tools.u][metabase.pulse.api :as pulse.api]@@ -24,7 +25,7 @@(defn- create-dashboard-subscription*"Private helper for create-dashboard-subscription (call that instead)."[{:keys [dashboard-id slack-channel schedule]}]- (let [dashboard (some-> (t2/select-one :model/Dashboard dashboard-id)+ (let [dashboard (some-> (metabot.db/dashboard dashboard-id)api/read-check(t2/hydrate [:dashcards :card]))cards (for [{:keys [id card]} (:dashcards dashboard)diff --git a/src/metabase/metabot/tools/util.clj b/src/metabase/metabot/tools/util.cljindex 0c0f77d708a..99419fbfc68 100644--- a/src/metabase/metabot/tools/util.clj+++ b/src/metabase/metabot/tools/util.clj@@ -8,9 +8,9 @@[metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.types.isa :as lib.types.isa]+ [metabase.metabot.db :as metabot.db][metabase.premium-features.core :as premium-features]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(defn handle-agent-error"Return an agent output for agent errors, re-throw `e` otherwise.@@ -142,21 +142,19 @@(defn get-database"Get the `fields` of the database with ID `id`."[id & fields]- (-> (t2/select-one (into [:model/Database :id] fields) id)+ (-> (metabot.db/database-with-columns (into [:model/Database :id] fields) id)api/read-check))(defn get-table"Get the `fields` of the table with ID `id`."[id & fields]- (-> (t2/select-one (into [:model/Table :id] fields)- :id id- :active true)+ (-> (metabot.db/active-table-with-columns (into [:model/Table :id] fields) id)api/read-check))(defn get-card"Retrieve the card with `id` from the app DB."[id]- (-> (t2/select-one :model/Card :id id)+ (-> (metabot.db/card id)api/read-check))(defn get-card-by-entity-id@@ -169,7 +167,7 @@card exists but the current user cannot read it, `api/read-check` raises a 403 instead ofsilently letting the representations resolver use an inaccessible card."[entity-id]- (some-> (t2/select-one :model/Card :entity_id entity-id)+ (some-> (metabot.db/card-by-entity-id entity-id)api/read-check))(defn card-query@@ -204,7 +202,7 @@Ignores analytics content."[metabot-id & {:keys [limit] :as _opts}]- (let [metabot (t2/select-one :model/Metabot :id metabot-id)+ (let [metabot (metabot.db/metabot metabot-id)metabot-collection-id (:collection_id metabot)use-verified-content? (:use_verified_content metabot)verified? (premium-features/has-feature? :content-verification)@@ -212,9 +210,7 @@library? (premium-features/has-feature? :library);; ids of collections under a Library-type root; their metrics/models are library-published contentlibrary-coll-ids (when library?- (let [roots (t2/select :model/Collection- :type [:in (mapv name collection/library-collection-types)]- :location "/")]+ (let [roots (metabot.db/root-collections-of-types (mapv name collection/library-collection-types))](into (set (map :id roots)) (mapcat collection/descendant-ids roots))));; Mirror collections.curation/curated? for card scope: verified, official-collection, or;; library-published (under a Library root). Each disjunct is gated on its feature.@@ -225,7 +221,7 @@;; Columns are qualified with report_card because the official-collections branch joins;; `collection`, which shares column names (type, archived, id) — unqualified refs would be ambiguous.collection-filter (if metabot-collection-id- (let [collection (t2/select-one :model/Collection :id metabot-collection-id)+ (let [collection (metabot.db/collection metabot-collection-id)collection-ids (conj (collection/descendant-ids collection) metabot-collection-id)][:in :report_card.collection_id collection-ids])[:and true])@@ -271,7 +267,7 @@[[metabase.metabot.tools.resources/check-resource-database]])."[db-ids](when (seq db-ids)- (t2/select-fn-set :id :model/Database :id [:in db-ids] :router_database_id [:not= nil])))+ (metabot.db/destination-database-ids db-ids)))(defn get-metrics-and-models"Retrieve the metric and model cards for the Metabot instance with ID `metabot-id` from the app DB.@@ -279,10 +275,10 @@Only cards visible to the current user are returned, excluding those backed by a destination(routed) database (see [[destination-db-ids]])."[metabot-id & {:as opts}]- (let [cards (t2/select :model/Card (-> (metabot-metrics-and-models-query metabot-id opts)- ;; qualified: the official-collections branch joins `collection`,- ;; which also has `id`- (update :order-by (fnil conj []) [:report_card.id])))+ (let [cards (metabot.db/cards-where (-> (metabot-metrics-and-models-query metabot-id opts)+ ;; qualified: the official-collections branch joins `collection`,+ ;; which also has `id`+ (update :order-by (fnil conj []) [:report_card.id])))destination-ids (destination-db-ids (into #{} (keep :database_id) cards))](if (seq destination-ids)(remove #(contains? destination-ids (:database_id %)) cards)diff --git a/src/metabase/metabot/used_tables.clj b/src/metabase/metabot/used_tables.cljindex 6b26ecce5f8..e3b9a8016c0 100644--- a/src/metabase/metabot/used_tables.clj+++ b/src/metabase/metabot/used_tables.clj@@ -26,11 +26,11 @@[metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.metabot.db :as metabot.db][metabase.metabot.query-analyzer :as nqa][metabase.metabot.tools :as metabot.tools][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.util.concurrent ArrayBlockingQueue Callable ExecutionException ExecutorService Future RejectedExecutionException ThreadFactory ThreadPoolExecutor TimeoutException TimeUnit)))@@ -385,7 +385,7 @@(try(let [rows (extract-used-tables-with-timing! message-id parts)](when (seq rows)- (t2/insert! :model/MetabotUsedTable rows)))+ (metabot.db/insert-used-tables! rows)))(catch Exception e(log/warn "Failed to record metabot used tables for message" message-id (ex-message e))))))diff --git a/src/metabase/metrics/api.clj b/src/metabase/metrics/api.cljindex 4d8e27bd81c..34f07b692fa 100644--- a/src/metabase/metrics/api.clj+++ b/src/metabase/metrics/api.clj@@ -8,6 +8,7 @@[metabase.lib-metric.core :as lib-metric][metabase.lib-metric.schema :as lib-metric.schema][metabase.metrics.core :as metrics]+ [metabase.metrics.db :as metrics.db][metabase.metrics.dimension :as metrics.dimension][metabase.metrics.permissions :as metrics.perms][metabase.queries.core :as queries]@@ -51,14 +52,10 @@[:result_column_name {:optional true} [:maybe :string]]]])(defn- count-metrics []- (t2/count :model/Card {:where (queries/visible-metric-cards-where-clause)}))+ (metrics.db/metric-card-count (queries/visible-metric-cards-where-clause)))(defn- select-metrics [limit offset]- (-> (t2/select [:model/Card :id :name :description :collection_id]- {:where (queries/visible-metric-cards-where-clause)- :order-by [[:name :asc]]- :limit limit- :offset offset})+ (-> (metrics.db/metric-cards-page (queries/visible-metric-cards-where-clause) limit offset)(t2/hydrate :collection)))(api.macros/defendpoint :get "/"@@ -84,9 +81,9 @@(mu/defn- hydrated-metric [id :- ms/PositiveIntinclude-orphaned? :- :boolean]- (api/read-check (t2/select-one :model/Card :id id :type "metric"))+ (api/read-check (metrics.db/metric-card id))(metrics/sync-dimensions! :metadata/metric id)- (cond-> (-> (t2/select-one :model/Card :id id :type "metric")+ (cond-> (-> (metrics.db/metric-card id)metrics.perms/filter-dimensions-for-user(update :dimensions #(or % []))(update :dimension_mappings #(or % [])))@@ -174,10 +171,10 @@source-id (lib-metric/expression-leaf-id leaf)](case source-type:metric (do- (api/read-check (t2/select-one :model/Card :id source-id :type "metric"))+ (api/read-check (metrics.db/metric-card source-id))[(lib-metric/expression-leaf-uuid leaf) source-id]):measure (do- (api/query-check (t2/select-one :model/Measure :id source-id))+ (api/query-check (metrics.db/measure source-id))nil))))(lib-metric/expression-leaves expression))))@@ -345,10 +342,10 @@;;; +----------------------------------------------------------------------------------------------------------------+(defn- read-check-metric! [id]- (api/read-check (t2/select-one :model/Card :id id :type "metric")))+ (api/read-check (metrics.db/metric-card id)))(defn- write-check-metric! [id]- (api/write-check (t2/select-one :model/Card :id id :type "metric")))+ (api/write-check (metrics.db/metric-card id)));; The module-local parent keeps the topic publishable in OSS, where no consumer namespace derives;; it. (A direct :metabase/event derive would throw once an EE consumer makes it an ancestor.)diff --git a/src/metabase/metrics/core.clj b/src/metabase/metrics/core.cljindex cf0a735d945..7344e37897b 100644--- a/src/metabase/metrics/core.clj+++ b/src/metabase/metrics/core.clj@@ -7,6 +7,7 @@[metabase.lib-metric.core :as lib-metric][metabase.lib.core :as lib][metabase.lib.metadata.protocols :as lib.metadata.protocols]+ [metabase.metrics.db :as metrics.db][metabase.metrics.dimension :as metrics.dimension][metabase.metrics.permissions :as metrics.perms][metabase.metrics.transforms :as metrics.transforms]@@ -14,8 +15,7 @@[metabase.util.i18n :refer [tru]][metabase.util.log :as log][metabase.util.malli.registry :as mr]- [metabase.util.namespaces :as shared.ns]- [toucan2.core :as t2]))+ [metabase.util.namespaces :as shared.ns]));;; ------------------------------------------------- Re-exports --------------------------------@@ -212,9 +212,7 @@(defn sync-metric-dimensions-for-database!"Compute and persist dimensions for every metric Card in `database-id` that doesn't have any yet."[database-id]- (doseq [{:keys [id dimensions]} (t2/select [:model/Card :id :dimensions]- :type "metric"- :database_id database-id)+ (doseq [{:keys [id dimensions]} (metrics.db/metric-cards-for-database database-id):when (empty? dimensions)](try(sync-dimensions! :metadata/metric id)diff --git a/src/metabase/metrics/db.clj b/src/metabase/metrics/db.cljnew file mode 100644index 00000000000..808bca803ed--- /dev/null+++ b/src/metabase/metrics/db.clj@@ -0,0 +1,45 @@+(ns metabase.metrics.db+ "Application database queries for the metrics module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++(defn metric-card-count+ "The number of Cards matching the Honey SQL `where` clause."+ [where]+ (t2/count :model/Card {:where where}))++(defn metric-cards-page+ "Up to `limit` id, name, description, and Collection id rows from `offset` of the Cards matching the Honey SQL+ `where` clause, in name order."+ [where limit offset]+ (t2/select [:model/Card :id :name :description :collection_id]+ {:where where+ :order-by [[:name :asc]]+ :limit limit+ :offset offset}))++(defn metric-card+ "The metric Card with `id`, or nil."+ [id]+ (t2/select-one :model/Card :id id :type "metric"))++(defn measure+ "The Measure with `id`, or nil."+ [id]+ (t2/select-one :model/Measure :id id))++(defn metric-cards-for-database+ "The id and dimensions of the metric Cards of the Database with `database-id`."+ [database-id]+ (t2/select [:model/Card :id :dimensions] :type "metric" :database_id database-id))++(defn fields-with-columns+ "The id and `columns` of the Fields with `field-ids`."+ [columns field-ids]+ (t2/select (into [:model/Field :id] columns) :id [:in field-ids]))++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field :id field-id))diff --git a/src/metabase/metrics/dimension.clj b/src/metabase/metrics/dimension.cljindex 045df60d42c..8ca84e00708 100644--- a/src/metabase/metrics/dimension.clj+++ b/src/metabase/metrics/dimension.clj@@ -6,13 +6,13 @@[malli.util :as mut][metabase.lib-metric.core :as lib-metric][metabase.lib-metric.schema :as lm.schema]+ [metabase.metrics.db :as metrics.db][metabase.parameters.core :as parameters][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));;; ------------------------------------------------- API Shape -------------------------------------------------;;; Convert internal (kebab) dimensions to the snake_case shape the frontend expects, and back.@@ -219,9 +219,9 @@metrics)field-ids (into #{} (comp cat (keep second)) dims+fids)field->row (when (seq field-ids)- (t2/select-pk->fn #(update-keys (select-keys % field-cols) u/->kebab-case-en)- (into [:model/Field :id] field-cols)- :id [:in field-ids]))+ (into {}+ (map (juxt :id #(update-keys (select-keys % field-cols) u/->kebab-case-en)))+ (metrics.db/fields-with-columns field-cols field-ids)))nil-cols (zipmap (map u/->kebab-case-en field-cols) (repeat nil))](mapv (fn [metric pairs](cond-> metric@@ -239,7 +239,7 @@dimension-mappings :- [:maybe [:sequential :map]]dimension-id :- :string](let [field-id (lib-metric/resolve-dimension-to-field-id dimensions dimension-mappings dimension-id)- field (t2/select-one :model/Field :id field-id)]+ field (metrics.db/field field-id)](parameters/field->values field)))(mu/defn dimension-search-values :- [:sequential [:vector :string]]@@ -259,11 +259,11 @@dimension-id :- :stringvalue :- :string](let [field-id (lib-metric/resolve-dimension-to-field-id dimensions dimension-mappings dimension-id)- field (t2/select-one :model/Field :id field-id)+ field (metrics.db/field field-id)parsed-value (parameters/parse-query-param-value-for-field field value)remapped-fid (parameters/remapped-field-id field-id)](if remapped-fid- (let [remapped-field (t2/select-one :model/Field :id remapped-fid)]+ (let [remapped-field (metrics.db/field remapped-fid)](parameters/remapped-value field remapped-field parsed-value));; No remapping - return the value as-is[parsed-value])))diff --git a/src/metabase/model_persistence/api.clj b/src/metabase/model_persistence/api.cljindex 4017057874c..1f88b4d94c3 100644--- a/src/metabase/model_persistence/api.clj+++ b/src/metabase/model_persistence/api.clj@@ -1,13 +1,13 @@(ns metabase.model-persistence.api(:require[clojure.string :as str]- [honey.sql.helpers :as sql.helpers][medley.core :as m][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.driver.connection :as driver.conn][metabase.driver.ddl.interface :as ddl.i][metabase.driver.util :as driver.u]+ [metabase.model-persistence.db :as model-persistence.db][metabase.model-persistence.models.persisted-info :as persisted-info][metabase.model-persistence.settings :as model-persistence.settings][metabase.model-persistence.task.persist-refresh :as task.persist-refresh]@@ -30,31 +30,8 @@"Returns a list of persisted info, annotated with database_name, card_name, and schema_name."[{:keys [persisted-info-id card-id db-ids]} limit offset](let [site-uuid-str (system/site-uuid)- db-id->fire-time (task.persist-refresh/job-info-by-db-id)- query (cond-> {:select [:p.id :p.database_id :p.definition- :p.active :p.state :p.error- :p.refresh_begin :p.refresh_end- :p.table_name :p.creator_id- :p.card_id [:c.name :card_name]- [:c.archived :card_archived]- [:c.type :card_type]- [:db.name :database_name]- [:col.id :collection_id] [:col.name :collection_name]- [:col.authority_level :collection_authority_level]]- :from [[:persisted_info :p]]- :left-join [[:metabase_database :db] [:= :db.id :p.database_id]- [:report_card :c] [:= :c.id :p.card_id]- [:collection :col] [:= :c.collection_id :col.id]]- :where [:and- [:= :c.type "model"]- [:= :c.archived false]]- :order-by [[:p.refresh_begin :desc]]}- persisted-info-id (sql.helpers/where [:= :p.id persisted-info-id])- (seq db-ids) (sql.helpers/where [:in :p.database_id db-ids])- card-id (sql.helpers/where [:= :p.card_id card-id])- limit (sql.helpers/limit limit)- offset (sql.helpers/offset offset))]- (as-> (t2/select :model/PersistedInfo query) results+ db-id->fire-time (task.persist-refresh/job-info-by-db-id)]+ (as-> (model-persistence.db/persisted-info-listing persisted-info-id db-ids card-id limit offset) results(t2/hydrate results :creator)(map (fn [{:keys [database_id] :as pi}](assoc pi@@ -70,22 +47,17 @@"List the entries of [[PersistedInfo]] in order to show a status page."[](perms/check-has-application-permission :monitoring)- (let [db-ids (t2/select-fn-set :database_id :model/PersistedInfo)+ (let [db-ids (model-persistence.db/persisted-database-ids)writable-db-ids (when (seq db-ids)(perms/prime-database-perms-cache {:db-ids db-ids})- (->> (t2/select :model/Database :id [:in db-ids])+ (->> (model-persistence.db/databases db-ids)(filter mi/can-write?)(map :id)set))persisted-infos (fetch-persisted-info {:db-ids writable-db-ids} (request/limit) (request/offset))]{:data persisted-infos:total (if (seq writable-db-ids)- (t2/count :model/PersistedInfo {:from [[:persisted_info :p]]- :join [[:report_card :c] [:= :c.id :p.card_id]]- :where [:and- [:in :p.database_id writable-db-ids]- [:= :c.type "model"]- [:not :c.archived]]})+ (model-persistence.db/persisted-model-count-for-databases writable-db-ids)0):limit (request/limit):offset (request/offset)}))@@ -100,7 +72,7 @@[:persisted-info-id ms/PositiveInt]]](api/let-404 [persisted-info (first (fetch-persisted-info {:persisted-info-id persisted-info-id} nil nil))](api/read-check :model/Card (:card_id persisted-info))- (api/write-check (t2/select-one :model/Database :id (:database_id persisted-info)))+ (api/write-check (model-persistence.db/database (:database_id persisted-info)))persisted-info));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -113,7 +85,7 @@[:card-id ms/PositiveInt]]](api/let-404 [persisted-info (first (fetch-persisted-info {:card-id card-id} nil nil))](api/read-check :model/Card card-id)- (api/read-check (t2/select-one :model/Database :id (:database_id persisted-info)))+ (api/read-check (model-persistence.db/database (:database_id persisted-info)))persisted-info))(def ^:private CronSchedule@@ -165,12 +137,12 @@- remove `:persist-models-enabled` from relevant [[Database]] settings- schedule a task to [[metabase.driver.ddl.interface/unpersist]] each table"[]- (let [id->db (m/index-by :id (t2/select :model/Database))+ (let [id->db (m/index-by :id (model-persistence.db/all-databases))enabled-dbs (filter (comp :persist-models-enabled :settings) (vals id->db))](log/info "Disabling model persistence")(doseq [db enabled-dbs]- (t2/update! :model/Database (u/the-id db)- {:settings (not-empty (dissoc (:settings db) :persist-models-enabled))}))+ (model-persistence.db/update-database! (u/the-id db)+ {:settings (not-empty (dissoc (:settings db) :persist-models-enabled))}))(task.persist-refresh/disable-persisting!)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -205,9 +177,9 @@[{:keys [card-id]} :- [:map[:card-id ms/PositiveInt]]](premium-features/assert-has-feature :cache-granular-controls (tru "Granular cache controls"))- (api/let-404 [{:keys [database_id] :as card} (t2/select-one :model/Card :id card-id)]+ (api/let-404 [{:keys [database_id] :as card} (model-persistence.db/card card-id)](api/write-check card)- (let [database (t2/select-one :model/Database :id database_id)]+ (let [database (model-persistence.db/database database_id)](api/write-check database)(when-not (driver.u/supports? (:engine database) :persist-models database)(throw (ex-info (tru "Database does not support persisting")@@ -231,14 +203,14 @@"Refresh the persisted model caching `card-id`."[{:keys [card-id]} :- [:map[:card-id ms/PositiveInt]]]- (api/let-404 [card (t2/select-one :model/Card :id card-id)- persisted-info (t2/select-one :model/PersistedInfo :card_id card-id)]+ (api/let-404 [card (model-persistence.db/card card-id)+ persisted-info (model-persistence.db/persisted-info-for-card card-id)](when (not (queries/model? card))(throw (ex-info (trs "Cannot refresh a non-model question") {:status-code 400})))(when (:archived card)(throw (ex-info (trs "Cannot refresh an archived model") {:status-code 400})))(api/write-check card)- (api/write-check (t2/select-one :model/Database :id (:database_id persisted-info)))+ (api/write-check (model-persistence.db/database (:database_id persisted-info)))(task.persist-refresh/schedule-refresh-for-individual! persisted-info)api/generic-204-no-content))@@ -252,10 +224,10 @@[{:keys [card-id]} :- [:map[:card-id ms/PositiveInt]]](premium-features/assert-has-feature :cache-granular-controls (tru "Granular cache controls"))- (api/let-404 [card (t2/select-one :model/Card :id card-id)]+ (api/let-404 [card (model-persistence.db/card card-id)](api/write-check card)- (when-let [persisted-info (t2/select-one :model/PersistedInfo :card_id card-id)]- (api/write-check (t2/select-one :model/Database :id (:database_id persisted-info)))+ (when-let [persisted-info (model-persistence.db/persisted-info-for-card card-id)]+ (api/write-check (model-persistence.db/database (:database_id persisted-info)))(persisted-info/mark-for-pruning! {:id (:id persisted-info)} "off"))api/generic-204-no-content))@@ -274,7 +246,7 @@(api/check (model-persistence.settings/persisted-models-enabled)400(tru "Persisting models is not enabled."))- (api/let-404 [database (t2/select-one :model/Database :id id)]+ (api/let-404 [database (model-persistence.db/database id)](api/write-check database)(if (-> database :settings :persist-models-enabled);; todo: some other response if already persisted?@@ -284,7 +256,7 @@schema (ddl.i/schema-name database (system/site-uuid))](if success?;; do secrets require special handling to not clobber them or mess up encryption?- (do (t2/update! :model/Database id {:settings (assoc (:settings database) :persist-models-enabled true)})+ (do (model-persistence.db/update-database! id {:settings (assoc (:settings database) :persist-models-enabled true)})(task.persist-refresh/schedule-persistence-for-database!database(model-persistence.settings/persisted-model-refresh-cron-schedule))@@ -301,10 +273,10 @@"Attempt to disable model persistence for a database. If already not enabled, just returns a generic 204."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (api/let-404 [database (t2/select-one :model/Database :id id)]+ (api/let-404 [database (model-persistence.db/database id)](api/write-check database)(if (-> database :settings :persist-models-enabled)- (do (t2/update! :model/Database id {:settings (dissoc (:settings database) :persist-models-enabled)})+ (do (model-persistence.db/update-database! id {:settings (dissoc (:settings database) :persist-models-enabled)})(persisted-info/mark-for-pruning! {:database_id id})(task.persist-refresh/unschedule-persistence-for-database! database)api/generic-204-no-content)diff --git a/src/metabase/model_persistence/db.clj b/src/metabase/model_persistence/db.cljnew file mode 100644index 00000000000..01a42f7a673--- /dev/null+++ b/src/metabase/model_persistence/db.clj@@ -0,0 +1,223 @@+(ns metabase.model-persistence.db+ "Application database queries for the model persistence module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [metabase.app-db.core :as mdb]+ [metabase.tracing.core :as tracing]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn persisted-info-listing+ "Up to `limit` PersistedInfo listing rows (id, database, definition, active, state, error, refresh window,+ table name, creator, card name/archived/type, database name, and collection id/name/authority level) for+ unarchived model Cards, optionally narrowed to `persisted-info-id`, `db-ids`, and/or `card-id`, newest+ refresh first, paginated from `offset` by `limit`."+ [persisted-info-id db-ids card-id limit offset]+ (t2/select :model/PersistedInfo+ (cond-> {:select [:p.id :p.database_id :p.definition+ :p.active :p.state :p.error+ :p.refresh_begin :p.refresh_end+ :p.table_name :p.creator_id+ :p.card_id [:c.name :card_name]+ [:c.archived :card_archived]+ [:c.type :card_type]+ [:db.name :database_name]+ [:col.id :collection_id] [:col.name :collection_name]+ [:col.authority_level :collection_authority_level]]+ :from [[:persisted_info :p]]+ :left-join [[:metabase_database :db] [:= :db.id :p.database_id]+ [:report_card :c] [:= :c.id :p.card_id]+ [:collection :col] [:= :c.collection_id :col.id]]+ :where [:and+ [:= :c.type "model"]+ [:= :c.archived false]]+ :order-by [[:p.refresh_begin :desc]]}+ persisted-info-id (sql.helpers/where [:= :p.id persisted-info-id])+ (seq db-ids) (sql.helpers/where [:in :p.database_id db-ids])+ card-id (sql.helpers/where [:= :p.card_id card-id])+ limit (sql.helpers/limit limit)+ offset (sql.helpers/offset offset))))++(defn deletable-prunable-persisted-infos+ "The PersistedInfos in one of `states` for over an hour, or attached to an archived question, or whose+ Card has been deleted — the records [[metabase.model-persistence.task.persist-refresh]] may unpersist."+ [states]+ (let [hsql {:select [:p.*]+ :from [[:persisted_info :p]]+ :left-join [[:report_card :c] [:= :c.id :p.card_id]]+ :where [:or+ [:and+ [:in :state states]+ ;; Buffer deletions for an hour if the prune job happens soon after setting+ ;; state: 1. so people have a chance to change their mind, 2. so a query+ ;; running against the cache doesn't get ripped out.+ [:< :state_change_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now -1 :hour)]]+ [:= :c.type "question"]+ [:= :c.archived true]+ ;; card_id is set to null when the corresponding card is deleted+ [:= :p.card_id nil]]}]+ (tracing/with-span :tasks "task.persist.find-deletable" {:db/statement (tracing/best-effort-sanitize-sql hsql)}+ (t2/select :model/PersistedInfo hsql))))++(defn refreshable-persisted-infos+ "The PersistedInfos of the Database with `database-id` in one of `states` whose Card is an unarchived+ model, plus the Card's `:type`, `:archived`, and `:name`."+ [database-id states]+ (let [hsql {:select [:p.* :c.type :c.archived :c.name]+ :from [[:persisted_info :p]]+ :left-join [[:report_card :c] [:= :c.id :p.card_id]]+ :where [:and+ [:= :p.database_id database-id]+ [:in :p.state states]+ [:= :c.archived false]+ [:= :c.type "model"]]}]+ (tracing/with-span :tasks "task.persist.find-refreshable" {:db/id database-id+ :db/statement (tracing/best-effort-sanitize-sql hsql)}+ (t2/select :model/PersistedInfo hsql))))++(defn persisted-infos-by-ids+ "The PersistedInfos with `ids`."+ [ids]+ (t2/select :model/PersistedInfo :id [:in ids]))++(defn persisted-info+ "The PersistedInfo with `id`, or nil."+ [id]+ (t2/select-one :model/PersistedInfo :id id))++(defn persisted-info-for-card+ "The PersistedInfo of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/PersistedInfo :card_id card-id))++(defn persisted-info-id-for-card+ "The id of the PersistedInfo of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :id :model/PersistedInfo :card_id card-id))++(defn persisted-info-state+ "The state of the PersistedInfo with `id`, or nil."+ [id]+ (t2/select-one-fn :state :model/PersistedInfo :id id))++(defn persisted-database-ids+ "The set of Database ids with PersistedInfos."+ []+ (t2/select-fn-set :database_id :model/PersistedInfo))++(defn persisted-card-ids-in-states+ "The Card ids among `card-ids` whose PersistedInfo is in one of `states`."+ [card-ids states]+ (t2/select-fn-set :card_id :model/PersistedInfo :card_id [:in card-ids] :state [:in states]))++(defn persisted-model-count-for-databases+ "The number of PersistedInfos of unarchived model Cards of the Databases with `database-ids`."+ [database-ids]+ (t2/count :model/PersistedInfo {:from [[:persisted_info :p]]+ :join [[:report_card :c] [:= :c.id :p.card_id]]+ :where [:and+ [:in :p.database_id database-ids]+ [:= :c.type "model"]+ [:not :c.archived]]}))++(defn insert-persisted-info!+ "Insert the PersistedInfo `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/PersistedInfo row))++(defn insert-persisted-infos!+ "Insert the PersistedInfo `rows`."+ [rows]+ (t2/insert! :model/PersistedInfo rows))++(defn update-persisted-info!+ "Apply `changes` to the PersistedInfo with `id`."+ [id changes]+ (t2/update! :model/PersistedInfo id changes))++(defn deactivate-all-persisted-infos!+ "Deactivate every PersistedInfo and move it to `state`."+ [state]+ (t2/update! :model/PersistedInfo {} {:active false, :state state, :state_change_at :%now}))++(defn deactivate-persisted-info!+ "Deactivate the PersistedInfo with `id` and move it to `state`."+ [id state]+ (t2/update! :model/PersistedInfo id {:active false, :state state, :state_change_at :%now}))++(defn deactivate-persisted-infos-for-database!+ "Deactivate the PersistedInfos of the Database with `database-id` and move them to `state`."+ [database-id state]+ (t2/update! :model/PersistedInfo :database_id database-id {:active false, :state state, :state_change_at :%now}))++(defn invalidate-persisted-infos-for-cards!+ "Deactivate the active PersistedInfos of the Cards with `card-ids` and move them back to creating."+ [card-ids]+ (t2/update! :model/PersistedInfo+ {:active true, :card_id [:in card-ids]}+ {:active false, :state "creating", :state_change_at :%now}))++(defn reset-persisted-info-to-creating!+ "Deactivate the PersistedInfo with `id` and move it back to creating."+ [id]+ (t2/update! :model/PersistedInfo id {:active false, :state "creating", :state_change_at :%now}))++(defn ready-deletable-persisted-infos!+ "Move the deletable PersistedInfos of the Database with `database-id` to `state`."+ [database-id state]+ (t2/query-one+ {:update [:persisted_info]+ :where [:and+ [:= :database_id database-id]+ [:= :state "deletable"]]+ :set {:active false,+ :state state,+ :state_change_at :%now}}))++(defn delete-persisted-info!+ "Delete the PersistedInfo with `id`."+ [id]+ (t2/delete! :model/PersistedInfo :id id))++(defn unpersisted-models-for-database+ "The model Cards of the Database with `database-id` that have no PersistedInfo."+ [database-id]+ (t2/select :model/Card+ {:where [:and+ [:= :database_id database-id]+ [:= :type "model"]+ [:not [:exists ^:allow-subquery+ {:select [1]+ :from [:persisted_info]+ :where [:= :persisted_info.card_id :report_card.id]}]]]}))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn card-archived-and-type+ "The archived flag and type of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :archived :type :card_schema] :id card-id))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn databases+ "The Databases with `database-ids`."+ [database-ids]+ (t2/select :model/Database :id [:in database-ids]))++(defn all-databases+ "Every Database."+ []+ (t2/select :model/Database))++(defn update-database!+ "Apply `changes` to the Database with `database-id`."+ [database-id changes]+ (t2/update! :model/Database database-id changes))diff --git a/src/metabase/model_persistence/events/persisted_info.clj b/src/metabase/model_persistence/events/persisted_info.cljindex 409b983b267..294e63db3df 100644--- a/src/metabase/model_persistence/events/persisted_info.clj+++ b/src/metabase/model_persistence/events/persisted_info.clj@@ -1,11 +1,11 @@(ns metabase.model-persistence.events.persisted-info(:require[metabase.events.core :as events]+ [metabase.model-persistence.db :as model-persistence.db][metabase.model-persistence.models.persisted-info :as persisted-info][metabase.model-persistence.settings :as model-persistence.settings][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(events/derive! ::event :metabase/event)(events/derive! :event/card-create ::event)@@ -20,8 +20,8 @@;; is only supposed to be that initial edge when the dataset is being changed.(when (and (= (:type card) :model)(model-persistence.settings/persisted-models-enabled)- (get-in (t2/select-one :model/Database :id (:database_id card)) [:settings :persist-models-enabled])- (nil? (t2/select-one-fn :id :model/PersistedInfo :card_id (:id card))))+ (get-in (model-persistence.db/database (:database_id card)) [:settings :persist-models-enabled])+ (nil? (model-persistence.db/persisted-info-id-for-card (:id card))))(persisted-info/turn-on-model! user-id card))(catch Throwable e(log/warnf "Failed to process persisted-info event. %s: %s" topic (ex-message e)))))diff --git a/src/metabase/model_persistence/models/persisted_info.clj b/src/metabase/model_persistence/models/persisted_info.cljindex 66000d7443b..f16dae0c303 100644--- a/src/metabase/model_persistence/models/persisted_info.clj+++ b/src/metabase/model_persistence/models/persisted_info.clj@@ -4,6 +4,7 @@[clojure.string :as str][metabase.lib.schema.common :as lib.schema.common][metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.model-persistence.db :as model-persistence.db][metabase.models.interface :as mi][metabase.premium-features.core :refer [defenterprise]][metabase.query-processor.util :as qp.util]@@ -106,9 +107,7 @@"Hydrate a card :is_persisted for the frontend."[cards](when (seq cards)- (let [existing-ids (t2/select-fn-set :card_id :model/PersistedInfo- :card_id [:in (map :id cards)]- :state [:in (refreshable-states)])]+ (let [existing-ids (model-persistence.db/persisted-card-ids-in-states (map :id cards) (refreshable-states))](map (fn [{id :id :as card}](assoc card :persisted (contains? existing-ids id)))cards))))@@ -122,16 +121,18 @@([conditions-map](mark-for-pruning! conditions-map "deletable"))([conditions-map state]- (t2/update! :model/PersistedInfo conditions-map {:active false, :state state, :state_change_at :%now})))+ (cond+ (contains? conditions-map :id) (model-persistence.db/deactivate-persisted-info! (:id conditions-map) state)+ (contains? conditions-map :database_id) (model-persistence.db/deactivate-persisted-infos-for-database! (:database_id conditions-map) state)+ :else (model-persistence.db/deactivate-all-persisted-infos! state))))(defn invalidate!- "Invalidates any caches corresponding to the `conditions-map`. Equivalent to toggling the caching off and on again."- [conditions-map]+ "Invalidates any caches corresponding to the Cards with `card-ids`. Equivalent to toggling the caching off and+ on again."+ [card-ids];; We do not immediately delete the cached table, it will get clobbered during the next refresh cycle.- (t2/update! :model/PersistedInfo- (merge {:active true} conditions-map)- ;; TODO perhaps we should immediately kick off a recalculation of these caches- {:active false, :state "creating", :state_change_at :%now}))+ ;; TODO perhaps we should immediately kick off a recalculation of these caches+ (model-persistence.db/invalidate-persisted-infos-for-cards! card-ids))(defenterprise default-persistent-info-state"The default state for a new PersistedInfo record. Defaults to 'creating' for OSS"@@ -160,42 +161,27 @@(defn ready-unpersisted-models!"Looks for all new models in database and creates a persisted-info ready to be synced."[database-id]- (let [cards (t2/select :model/Card- {:where [:and- [:= :database_id database-id]- [:= :type "model"]- [:not [:exists ^:allow-subquery- {:select [1]- :from [:persisted_info]- :where [:= :persisted_info.card_id :report_card.id]}]]]})]- (t2/insert! :model/PersistedInfo (map #(create-row nil %) cards))))+ (let [cards (model-persistence.db/unpersisted-models-for-database database-id)]+ (model-persistence.db/insert-persisted-infos! (map #(create-row nil %) cards))))(defn turn-on-model!"Marks PersistedInfo as `creating`, these will at some point be persisted by the PersistRefresh task."[user-id card](let [card-id (u/the-id card)- existing-persisted-info (t2/select-one :model/PersistedInfo :card_id card-id)+ existing-persisted-info (model-persistence.db/persisted-info-for-card card-id)persisted-info (cond(not existing-persisted-info)- (first (t2/insert-returning-instances! :model/PersistedInfo (create-row user-id card)))+ (model-persistence.db/insert-persisted-info! (create-row user-id card))(contains? #{"deletable" "off"} (:state existing-persisted-info))(do- (t2/update! :model/PersistedInfo (u/the-id existing-persisted-info)- {:active false, :state "creating", :state_change_at :%now})- (t2/select-one :model/PersistedInfo :card_id card-id)))]+ (model-persistence.db/reset-persisted-info-to-creating! (u/the-id existing-persisted-info))+ (model-persistence.db/persisted-info-for-card card-id)))]persisted-info))(defn ready-database!"Sets PersistedInfo state to the default state for models without a PeristedInfo or those in a `deletable` state.Will ignore explicitly set `off` models."[database-id]- (t2/query-one- {:update [:persisted_info]- :where [:and- [:= :database_id database-id]- [:= :state "deletable"]]- :set {:active false,- :state (default-persistent-info-state),- :state_change_at :%now}})+ (model-persistence.db/ready-deletable-persisted-infos! database-id (default-persistent-info-state))(ready-unpersisted-models! database-id))diff --git a/src/metabase/model_persistence/task/persist_refresh.clj b/src/metabase/model_persistence/task/persist_refresh.cljindex 815de4ec61f..5a13661203c 100644--- a/src/metabase/model_persistence/task/persist_refresh.clj+++ b/src/metabase/model_persistence/task/persist_refresh.clj@@ -6,10 +6,10 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][medley.core :as m]- [metabase.app-db.core :as mdb][metabase.driver :as driver][metabase.driver.ddl.interface :as ddl.i][metabase.events.core :as events]+ [metabase.model-persistence.db :as model-persistence.db][metabase.model-persistence.models.persisted-info :as persisted-info][metabase.model-persistence.settings :as model-persistence.settings][metabase.query-processor.core :as qp]@@ -18,7 +18,6 @@[metabase.task.core :as task][metabase.tracing.core :as tracing][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.log :as log][metabase.util.malli :as mu][potemkin.types :as p]@@ -54,34 +53,34 @@(defn- refresh-with-stats! [refresher database stats persisted-info];; Since this could be long running, double check state just before refreshing- (when (contains? (persisted-info/refreshable-states) (t2/select-one-fn :state :model/PersistedInfo :id (:id persisted-info)))+ (when (contains? (persisted-info/refreshable-states) (model-persistence.db/persisted-info-state (:id persisted-info)))(tracing/with-span :tasks "task.persist.refresh-model" {:db/id (u/the-id database):persist/card-id (:card_id persisted-info):persist/table (:table_name persisted-info)}(log/infof "Attempting to refresh persisted model %s." (:card_id persisted-info))- (let [card (t2/select-one :model/Card :id (:card_id persisted-info))+ (let [card (model-persistence.db/card (:card_id persisted-info))definition (persisted-info/metadata->definition (:result_metadata card)(:table_name persisted-info))- _ (t2/update! :model/PersistedInfo (u/the-id persisted-info)- {:definition definition,- :query_hash (persisted-info/query-hash (:dataset_query card))- :active false,- :refresh_begin :%now,- :refresh_end nil,- :state "refreshing"- :state_change_at :%now})+ _ (model-persistence.db/update-persisted-info! (u/the-id persisted-info)+ {:definition definition,+ :query_hash (persisted-info/query-hash (:dataset_query card))+ :active false,+ :refresh_begin :%now,+ :refresh_end nil,+ :state "refreshing"+ :state_change_at :%now}){:keys [state error]} (try(refresh! refresher database definition card)(catch Exception e(log/infof "Error refreshing persisting model with card-id %s: %s"(:card_id persisted-info) (ex-message e)){:state :error :error (ex-message e)}))]- (t2/update! :model/PersistedInfo (u/the-id persisted-info)- {:active (= state :success),- :refresh_end :%now,- :state (if (= state :success) "persisted" "error")- :state_change_at :%now- :error (when (= state :error) error)})+ (model-persistence.db/update-persisted-info! (u/the-id persisted-info)+ {:active (= state :success),+ :refresh_end :%now,+ :state (if (= state :success) "persisted" "error")+ :state_change_at :%now+ :error (when (= state :error) error)})(if (= :success state)(update stats :success inc)(-> stats@@ -100,8 +99,7 @@(try(let [error-details (error-details task-details)error-details-by-id (m/index-by :persisted-info-id error-details)- persisted-infos (->> (t2/hydrate (t2/select :model/PersistedInfo :id [:in (keys error-details-by-id)])- [:card :collection] :database)+ persisted-infos (->> (t2/hydrate (model-persistence.db/persisted-infos-by-ids (keys error-details-by-id)) [:card :collection] :database)(map #(assoc % :error (get-in error-details-by-id [(:id %) :error]))))](events/publish-event! :event/persisted-model-refresh-error{:database-id db-id@@ -128,13 +126,12 @@"Seam for tests to pass in specific deletables to drop."[refresher deletables](when (seq deletables)- (let [db-id->db (m/index-by :id (t2/select :model/Database :id [:in (map :database_id deletables)]))+ (let [db-id->db (m/index-by :id (model-persistence.db/databases (map :database_id deletables)))unpersist-fn (fn [](reduce (fn [stats persisted-info];; Since this could be long running, double check state just before deleting- (let [current-state (t2/select-one-fn :state :model/PersistedInfo :id (:id persisted-info))- card-info (t2/select-one [:model/Card :archived :type :card_schema]- :id (:card_id persisted-info))]+ (let [current-state (model-persistence.db/persisted-info-state (:id persisted-info))+ card-info (model-persistence.db/card-archived-and-type (:card_id persisted-info))](if (or (contains? (persisted-info/prunable-states) current-state)(:archived card-info)(not= (:type card-info) :model))@@ -145,7 +142,7 @@(try(unpersist! refresher database persisted-info)(when-not (= "off" current-state)- (t2/delete! :model/PersistedInfo :id (:id persisted-info)))+ (model-persistence.db/delete-persisted-info! (:id persisted-info)))(update stats :success inc)(catch Exception e(log/infof "Error unpersisting model with card-id %s: %s" (:card_id persisted-info) (ex-message e))@@ -161,38 +158,12 @@persisted info records pointing to cards that are no longer models, archived cards/models, and all records where the correspondingcard or database has been permanently deleted."[]- (let [hsql {:select [:p.*]- :from [[:persisted_info :p]]- :left-join [[:report_card :c] [:= :c.id :p.card_id]]- :where [:or- [:and- [:in :state (persisted-info/prunable-states)]- ;; Buffer deletions for an hour if the- ;; prune job happens soon after setting state.- ;; 1. so that people have a chance to change their mind.- ;; 2. if a query is running against the cache, it doesn't get ripped out.- [:< :state_change_at- (h2x/add-interval-honeysql-form (mdb/db-type) :%now -1 :hour)]]- [:= :c.type "question"]- [:= :c.archived true]- ;; card_id is set to null when the corresponding card is deleted- [:= :p.card_id nil]]}]- (tracing/with-span :tasks "task.persist.find-deletable" {:db/statement (tracing/best-effort-sanitize-sql hsql)}- (t2/select :model/PersistedInfo hsql))))+ (model-persistence.db/deletable-prunable-persisted-infos (persisted-info/prunable-states)))(defn- refreshable-models"Returns refreshable models for a database id. Must still be models and not archived."[database-id]- (let [hsql {:select [:p.* :c.type :c.archived :c.name]- :from [[:persisted_info :p]]- :left-join [[:report_card :c] [:= :c.id :p.card_id]]- :where [:and- [:= :p.database_id database-id]- [:in :p.state (persisted-info/refreshable-states)]- [:= :c.archived false]- [:= :c.type "model"]]}]- (tracing/with-span :tasks "task.persist.find-refreshable" {:db/id database-id :db/statement (tracing/best-effort-sanitize-sql hsql)}- (t2/select :model/PersistedInfo hsql))))+ (model-persistence.db/refreshable-persisted-infos database-id (persisted-info/refreshable-states)))(defn- prune-all-deletable!"Prunes all deletable PersistInfos, should not be called from tests as@@ -207,7 +178,7 @@[database-id refresher trigger](log/infof "Starting persisted model refresh task for Database %s." database-id)(persisted-info/ready-unpersisted-models! database-id)- (let [database (t2/select-one :model/Database :id database-id)+ (let [database (model-persistence.db/database database-id)persisted (refreshable-models database-id)thunk (fn [](reduce (partial refresh-with-stats! refresher database)@@ -220,9 +191,9 @@(defn- refresh-individual!"Refresh an individual model based on [[PersistedInfo]]."[persisted-info-id refresher trigger]- (let [persisted-info (t2/select-one :model/PersistedInfo :id persisted-info-id)+ (let [persisted-info (model-persistence.db/persisted-info persisted-info-id)database (when persisted-info- (t2/select-one :model/Database :id (:database_id persisted-info)))]+ (model-persistence.db/database (:database_id persisted-info)))](if (and persisted-info database)(do(save-task-history! "persist-refresh" (u/the-id database)@@ -411,7 +382,7 @@`:persist-models-enabled` in the settings atinterval [[model-persistence.settings/persisted-model-refresh-cron-schedule]]."[]- (let [dbs-with-persistence (filter (comp :persist-models-enabled :settings) (t2/select :model/Database))+ (let [dbs-with-persistence (filter (comp :persist-models-enabled :settings) (model-persistence.db/all-databases))cron-schedule (model-persistence.settings/persisted-model-refresh-cron-schedule)](unschedule-all-refresh-triggers! refresh-job-key)(doseq [db dbs-with-persistence]diff --git a/src/metabase/models/db.clj b/src/metabase/models/db.cljnew file mode 100644index 00000000000..a7f2ff298ce--- /dev/null+++ b/src/metabase/models/db.clj@@ -0,0 +1,240 @@+(ns metabase.models.db+ "Application database queries for the models module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (the model machinery still uses+ `toucan2.core`)."+ (:require+ [toucan2.core :as t2]+ [toucan2.tools.identity-query :as t2.identity-query]))++(defn entity-by-pk+ "The `model` row whose `pk-column` is `id`, or nil."+ [model pk-column id]+ (t2/select-one model pk-column id))++(defn entity-by-entity-id+ "The `model` row with `entity-id`, or nil."+ [model entity-id]+ (t2/select-one model :entity_id entity-id))++(defn entity-field+ "The `field` of the `model` row with `id`, or nil."+ [model id field]+ (t2/select-one-fn field model :id id))++(defn pk-by-entity-id+ "The `pk-column` of the `model` row with `entity-id`, or nil."+ [model pk-column entity-id]+ (t2/select-one-fn pk-column [model pk-column] :entity_id entity-id))++(defn pk-by-field+ "The primary key of the `model` row whose `field` is `value`, or nil."+ [model field value]+ (t2/select-one-pk model field value))++(defn after-select-via-identity-query+ "`row-map` run through the after-select machinery of `model`."+ [model row-map]+ (t2/select-one model (t2.identity-query/identity-query [row-map])))++(defn entities-reducible+ "A reducible of the `model` rows additionally matching the Honey SQL `extra-where` when given — the serdes+ extract-query nested-fetch hook passes a dynamic foreign-key-column + id-list condition here that varies per+ model/transform and can't be expressed as fixed data — ordered by `order-by` (or unordered when nil)."+ [model extra-where order-by]+ (t2/reducible-select model (cond-> {}+ extra-where (assoc :where extra-where)+ order-by (assoc :order-by order-by))))++(defn entities-in-collections-reducible+ "A reducible of the `model` rows whose `:collection_id` is in `collection-set` (nil in the set counts as the root+ collection), additionally matching the Honey SQL `extra-where` when given (see [[entities-reducible]] for why this+ stays a raw clause), ordered by `order-by` (or unordered when nil)."+ [model collection-set extra-where order-by]+ (t2/reducible-select model+ (cond-> {:where [:and+ [:or+ [:in :collection_id collection-set]+ (when (some nil? collection-set)+ [:= :collection_id nil])]+ extra-where]}+ order-by (assoc :order-by order-by))))++(defn table-names-reducible+ "A reducible of the id, name, and display name of every Table."+ []+ (t2/reducible-select [:model/Table :id :name :display_name]))++(defn field-names-reducible+ "A reducible of the id, name, and display name of every Field."+ []+ (t2/reducible-select [:model/Field :id :name :display_name]))++(defn update-entity!+ "Apply `changes` to the `model` row with `id`."+ [model id changes]+ (t2/update! model id changes))++(defn set-table-display-name!+ "Set the display name of the Table with `id`."+ [id display-name]+ (t2/update! :model/Table id {:display_name display-name}))++(defn set-field-display-name!+ "Set the display name of the Field with `id`."+ [id display-name]+ (t2/update! :model/Field id {:display_name display-name}))++(defn insert-entity!+ "Insert the `model` `row` and return the inserted instance."+ [model row]+ (t2/insert-returning-instance! model row))++(defn insert-entity-returning-pk!+ "Insert the `model` `row` and return its primary key."+ [model row]+ (t2/insert-returning-pk! model row))++(defn insert-entities!+ "Insert the `model` `rows`."+ [model rows]+ (t2/insert! model rows))++(defn delete-entity!+ "Delete the `model` row with `id`."+ [model id]+ (t2/delete! model id))++(defn delete-entities-with-ids!+ "Delete the `model` rows whose `id-column` is one of `ids`."+ [model id-column ids]+ (t2/delete! model id-column [:in ids]))++(defn delete-children!+ "Delete the `model` rows whose `parent-column` is `parent-id`."+ [model parent-column parent-id]+ (t2/delete! model parent-column parent-id))++(defn delete-children-except!+ "Delete the `model` rows whose `parent-column` is `parent-id` and whose entity id is not one of `entity-ids`."+ [model parent-column parent-id entity-ids]+ (t2/delete! model parent-column parent-id :entity_id [:not-in entity-ids]))++(defn collection-paths-columns+ "The id, entity id, location, and name of every Collection."+ []+ (t2/select [:model/Collection :id :entity_id :location :name]))++(defn dashboard-entity-ids-and-names+ "The entity id and name of every Dashboard."+ []+ (t2/select [:model/Dashboard :entity_id :name]))++(defn document-entity-ids-and-names+ "The entity id and name of every Document."+ []+ (t2/select [:model/Document :entity_id :name]))++(defn field-hierarchy-rows+ "The name and Table id of the Field with `field-id` and each of its ancestors, deepest first."+ [field-id]+ (t2/select :model/Field+ {:with-recursive [[[:parents ^:allow-subquery {:columns [:id :name :parent_id :table_id]}]+ ^:allow-subquery {:union-all [^:allow-subquery {:from [[:metabase_field :mf]]+ :select [:mf.id :mf.name :mf.parent_id :mf.table_id]+ :where [:= :id field-id]}+ ^:allow-subquery {:from [[:metabase_field :pf]]+ :select [:pf.id :pf.name :pf.parent_id :pf.table_id]+ :join [[:parents :p] [:= :p.parent_id :pf.id]]}]}]]+ :from [:parents]+ :select [:name :table_id]}))++(defn table-ref-columns+ "The id, Database id, name, and schema of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one [:model/Table :id :db_id :name :schema] :id table-id))++(defn database-name+ "The name of the Database with `database-id`, or nil."+ [database-id]+ (t2/select-one-fn :name [:model/Database :id :name] :id database-id))++(defn database-names+ "The names of every Database."+ []+ (t2/select-fn-vec :name :model/Database))++(defn database-id-by-name+ "The id of the Database named `database-name`, or nil."+ [database-name]+ (t2/select-one-fn :id :model/Database :name database-name))++(defn table-id-by-name+ "The id of the Table named `table-name` in `schema` of the Database with `database-id`, or nil."+ [table-name schema database-id]+ (t2/select-one-fn :id :model/Table :name table-name :schema schema :db_id database-id))++(defn insert-inactive-table!+ "Insert an inactive Table named `table-name` in `schema` of the Database with `database-id` and return its id."+ [database-id schema table-name]+ (t2/insert-returning-pk! :model/Table {:db_id database-id+ :schema schema+ :name table-name+ :active false}))++(defn field-pk+ "The id of the Field named `field-name` under `parent-id` in the Table with `table-id`, or nil."+ [table-id field-name parent-id]+ (t2/select-one-pk :model/Field :table_id table-id :name field-name :parent_id parent-id))++(defn- field-in-path-query+ [table-id [field & rest]]+ (when field+ ^:allow-subquery {:from [:metabase_field]+ :select [:id]+ :where [:and+ [:= :table_id table-id]+ [:= :name field]+ [:= :parent_id (field-in-path-query table-id rest)]]}))++(defn field-pk-in-path+ "The id of the Field named by the last of `field-names` (each nested inside the previous, bottom-most first) under+ `table-id`, or nil."+ [table-id field-names]+ (when (seq field-names)+ (t2/select-one-pk :model/Field (field-in-path-query table-id field-names))))++(defn insert-inactive-field!+ "Insert an inactive, untyped Field named `field-name` under `parent-id` in the Table with `table-id` and return its+ id."+ [table-id parent-id field-name]+ (t2/insert-returning-pk! :model/Field {:table_id table-id+ :parent_id parent-id+ :name field-name+ :active false+ :base_type :type/*+ :database_type "NULL"}))++(defn metadata-tables+ "The `:metadata/table` rows named `table-name` in `schema` of the Database with `database-id`."+ [database-id schema table-name]+ (t2/select :metadata/table :db_id database-id :schema schema :name table-name))++(defn card-serdes-columns+ "The id, entity id, Collection id, Database id, and schema of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :id :entity_id :collection_id :database_id :card_schema] :id card-id))++(defn measure-serdes-columns+ "The id, entity id, and Table id of the Measure with `measure-id`, or nil."+ [measure-id]+ (t2/select-one [:model/Measure :id :entity_id :table_id] :id measure-id))++(defn segment-serdes-columns+ "The id, entity id, and Table id of the Segment with `segment-id`, or nil."+ [segment-id]+ (t2/select-one [:model/Segment :id :entity_id :table_id] :id segment-id))++(defn entity-by-own-pk+ "The `model` row identified by `id`, using whatever column is that model's own primary key."+ [model id]+ (t2/select-one model (first (t2/primary-keys model)) id))diff --git a/src/metabase/models/humanization.clj b/src/metabase/models/humanization.cljindex e82b53b5b2a..158bf5707c3 100644--- a/src/metabase/models/humanization.clj+++ b/src/metabase/models/humanization.clj@@ -10,13 +10,13 @@There used to also be `:advanced`, which was the default until enough customerscomplained that we first fixed it and then the fix wasn't good enough so we removed it."(:require+ [metabase.models.db :as models.db][metabase.settings.core :as setting :refer [defsetting]][metabase.util :as u][metabase.util.humanization :as u.humanization][metabase.util.i18n :refer [deferred-tru tru]][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(declare humanization-strategy)@@ -37,8 +37,9 @@(u.humanization/name->human-readable-name strategy s)))(defn- re-humanize-names!- "Update all non-custom display names of all instances of `model` (e.g. Table or Field)."- [old-strategy model]+ "Update all non-custom display names of all `entities-reducible` rows (e.g. Table or Field ones), using `model` for+ logging and `set-display-name!` to apply the change."+ [old-strategy model entities-reducible set-display-name!](run! (fn [{id :id, internal-name :name, display-name :display_name}](let [old-strategy-display-name (name->human-readable-name old-strategy internal-name)new-strategy-display-name (name->human-readable-name internal-name)@@ -47,16 +48,15 @@(not custom-display-name?))(log/infof "Updating display name for %s '%s': '%s' -> '%s'"(name model) internal-name display-name new-strategy-display-name)- (t2/update! model id- {:display_name new-strategy-display-name}))))- (t2/reducible-select [model :id :name :display_name])))+ (set-display-name! id new-strategy-display-name))))+ (entities-reducible)))(mu/defn- re-humanize-table-and-field-names!"Update the non-custom display names of all Tables & Fields in the database using new values obtained fromthe (obstensibly swapped implementation of) `name->human-readable-name`."[old-strategy :- :keyword]- (doseq [model [:model/Table :model/Field]]- (re-humanize-names! old-strategy model)))+ (re-humanize-names! old-strategy :model/Table models.db/table-names-reducible models.db/set-table-display-name!)+ (re-humanize-names! old-strategy :model/Field models.db/field-names-reducible models.db/set-field-display-name!))(defn- set-humanization-strategy! [new-value](let [new-strategy (keyword (or new-value :simple))]diff --git a/src/metabase/models/interface.clj b/src/metabase/models/interface.cljindex e3a4fe94a4e..5377db1f282 100644--- a/src/metabase/models/interface.clj+++ b/src/metabase/models/interface.clj@@ -20,6 +20,7 @@;; stored card queries/refs are still legacy MBQL; validated against the legacy schema on read/write^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.legacy-mbql.schema :as mbql.s][metabase.lib.core :as lib]+ [metabase.models.db :as models.db][metabase.models.dispatch :as models.dispatch][metabase.models.json-migration :as jm][metabase.models.resolution]@@ -39,7 +40,6 @@[toucan2.protocols :as t2.protocols][toucan2.tools.before-insert :as t2.before-insert][toucan2.tools.hydrate :as t2.hydrate]- [toucan2.tools.identity-query :as t2.identity-query][toucan2.util :as t2.u])(:import(java.sql Blob)@@ -621,7 +621,7 @@{:pre [(map? row-map)]}(let [model (t2/resolve-model modelable)](try- (t2/select-one model (t2.identity-query/identity-query [row-map]))+ (models.db/after-select-via-identity-query model row-map)(catch Throwable e(throw (ex-info (format "Error doing after-select for model %s: %s" model (ex-message e)){:model model}@@ -773,7 +773,7 @@a-model :- qualified-keyword?object-id :- [:or pos-int? string?]](or (current-user-has-root-permissions?)- (check-perms-with-fn fn-symb read-or-write (t2/select-one a-model (first (t2/primary-keys a-model)) object-id))))+ (check-perms-with-fn fn-symb read-or-write (models.db/entity-by-pk a-model (first (t2/primary-keys a-model)) object-id))))([fn-symb :- qualified-symbol?read-or-write :- [:enum :read :write]diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.cljindex a158d748a6f..a9f638d391c 100644--- a/src/metabase/models/serialization.clj+++ b/src/metabase/models/serialization.clj@@ -68,6 +68,7 @@[metabase.lib.schema.common :as lib.schema.common][metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.parameter :as lib.schema.parameter]+ [metabase.models.db :as models.db][metabase.models.interface :as mi][metabase.models.serialization.resolve :as resolve][metabase.models.visualization-settings :as mb.viz]@@ -175,7 +176,7 @@pk (first (t2/primary-keys model))eid (cond-> eid(str/starts-with? eid "eid:") (subs 4))]- (t2/select-one-fn pk [model pk] :entity_id eid)))+ (models.db/pk-by-entity-id model pk eid)));;; # Serdes paths and <tt>:serdes/meta</tt>;;; The Clojure maps from extraction and ingestion always include a special key `:serdes/meta` giving some information@@ -503,16 +504,8 @@(if (or (empty? collection-set)(nil? (-> spec :transform :collection_id)));; either no collections specified or our model has no collection- (t2/reducible-select model (cond-> {:where (or where true)}- order-by (assoc :order-by order-by)))- (t2/reducible-select model (cond-> {:where [:and- [:or- [:in :collection_id collection-set]- (when (some nil? collection-set)- [:= :collection_id nil])]- (when where- where)]}- order-by (assoc :order-by order-by))))))+ (models.db/entities-reducible model where order-by)+ (models.db/entities-in-collections-reducible model collection-set where order-by))))(defmethod extract-query :default [model-name opts](let [spec (*make-spec* model-name opts)@@ -685,8 +678,8 @@pk (first (t2/primary-keys model))id (get local pk)](log/tracef "Upserting %s %d" model-name id)- (t2/update! model id ingested)- (t2/select-one model pk id)))+ (models.db/update-entity! model id ingested)+ (models.db/entity-by-pk model pk id)))(defmulti load-insert!"Called by the default [[load-one!]] if there is no corresponding entity already in the appdb.@@ -707,7 +700,7 @@(defmethod load-insert! :default [model-name ingested](log/tracef "Inserting %s" model-name)- (first (t2/insert-returning-instances! (t2.model/resolve-model (symbol model-name)) ingested)))+ (models.db/insert-entity! (t2.model/resolve-model (symbol model-name)) ingested))(defmulti load-one!"Black box for integrating a deserialized entity into this appdb.@@ -791,7 +784,7 @@"Given an entity ID string, finds the matching entity. This is useful when writing [[xform-one]] toturn a foreign key from a portable form to an appdb ID. Returns a Toucan entity or nil."[model :- ::model-keyword-or-symbol id-str]- (t2/select-one model :entity_id id-str))+ (models.db/entity-by-entity-id model id-str))(defn storage-default-collection-path"Implements the most common structure for [[storage-path]].@@ -823,7 +816,7 @@- `:unique-name-fns` is an atom of `{parent-key -> unique-name-fn}` where each `unique-name-fn` is a`lib/non-truncating-unique-name-generator`, used to deduplicate names within the same folder during export."[]- (let [colls (t2/select ['Collection :id :entity_id :location :name])+ (let [colls (models.db/collection-paths-columns)id->coll (into {} (for [{:keys [id] :as coll} colls] [(str id) coll]))coll->path (into {}(for [{:keys [entity_id id location]} colls@@ -835,10 +828,10 @@all-ids)]][entity_id path-maps]))dashboards (into {}- (for [{:keys [entity_id name]} (t2/select ['Dashboard :entity_id :name])]+ (for [{:keys [entity_id name]} (models.db/dashboard-entity-ids-and-names)][entity_id {:label name :key entity_id}]))documents (into {}- (for [{:keys [entity_id name]} (t2/select ['Document :entity_id :name])]+ (for [{:keys [entity_id name]} (models.db/document-entity-ids-and-names)][entity_id {:label name :key entity_id}]))]{:collections coll->path:dashboards dashboards@@ -849,17 +842,17 @@;;; These wrapper functions delegate to the current resolver (set by [[with-cache]]).;;; When no resolver is bound, they fall back to the database-backed resolver.-;; TODO: `requiring-resolve` is needed here because resolve.db requires this ns-;; (for `generate-path`, `field-hierarchy`, `lookup-by-id`, `recursively-find-field-q`).-;; Moving those into resolve.db (or a shared utils ns) would break the cycle and-;; let us require resolve.db directly.+;; TODO: `requiring-resolve` is needed here because resolve.default requires this ns+;; (for `generate-path`, `field-hierarchy`, `lookup-by-id`).+;; Moving those into resolve.default (or a shared utils ns) would break the cycle and+;; let us require resolve.default directly.(defn- export-resolver [](or resolve/*export-resolver*- @(requiring-resolve 'metabase.models.serialization.resolve.db/default-export-resolver)))+ @(requiring-resolve 'metabase.models.serialization.resolve.default/default-export-resolver)))(defn- import-resolver [](or resolve/*import-resolver*- @(requiring-resolve 'metabase.models.serialization.resolve.db/default-import-resolver)))+ @(requiring-resolve 'metabase.models.serialization.resolve.default/default-import-resolver)));;; ## General foreign keys@@ -1011,29 +1004,7 @@"Returns the field hierarchy (field + parents) for a field ID. Used by resolvers."[id](reverse- (t2/select :model/Field- {:with-recursive [[[:parents ^:allow-subquery {:columns [:id :name :parent_id :table_id]}]- ^:allow-subquery {:union-all [^:allow-subquery {:from [[:metabase_field :mf]]- :select [:mf.id :mf.name :mf.parent_id :mf.table_id]- :where [:= :id id]}- ^:allow-subquery {:from [[:metabase_field :pf]]- :select [:pf.id :pf.name :pf.parent_id :pf.table_id]- :join [[:parents :p] [:= :p.parent_id :pf.id]]}]}]]- :from [:parents]- :select [:name :table_id]})))--(defn recursively-find-field-q- "Build a query to find a field among parents (should start with bottom-most field first), i.e.:-- `(recursively-find-field-q 1 [\"inner\" \"outer\"])`"- [table-id [field & rest]]- (when field- ^:allow-subquery {:from [:metabase_field]- :select [:id]- :where [:and- [:= :table_id table-id]- [:= :name field]- [:= :parent_id (recursively-find-field-q table-id rest)]]}))+ (models.db/field-hierarchy-rows id)));; NOTE: field lookups are intentionally NOT routed through the cached resolver, unlike the;; database and table exporters above. Fields are unbounded in number (millions on large@@ -1794,7 +1765,7 @@left in its portable entity-id form, instead of throwing. Use for paths where a deleted source Cardshould be treated as a broken section rather than break the whole read."[settings]- (binding [resolve/*import-resolver* @(requiring-resolve 'metabase.models.serialization.resolve.db/lenient-import-resolver)]+ (binding [resolve/*import-resolver* @(requiring-resolve 'metabase.models.serialization.resolve.default/lenient-import-resolver)](import-visualizer-settings settings)))(defn import-visualization-settings@@ -1926,12 +1897,12 @@(update :serdes/meta #(or % [{:model model-name :id (get ingested key-field)}]))))](cond(nil? first-eid) ; no entity id, just drop existing stuff- (do (t2/delete! model backward-fk parent-id)+ (do (models.db/delete-children! model backward-fk parent-id)(doseq [ingested lst](load-one! (enrich ingested) nil))):else ; match by entity id- (do (t2/delete! model backward-fk parent-id :entity_id [:not-in (map :entity_id lst)])+ (do (models.db/delete-children-except! model backward-fk parent-id (map :entity_id lst))(doseq [ingested lst:let [ingested (enrich ingested)local (lookup-by-id model (entity-id model-name ingested))]]@@ -1987,6 +1958,6 @@(defmacro with-cache"Runs body with resolvers bound to cached (memoized) versions for performance."[& body]- `(binding [resolve/*export-resolver* ((requiring-resolve 'metabase.models.serialization.resolve.db/cached-export-resolver))- resolve/*import-resolver* ((requiring-resolve 'metabase.models.serialization.resolve.db/cached-import-resolver))]+ `(binding [resolve/*export-resolver* ((requiring-resolve 'metabase.models.serialization.resolve.default/cached-export-resolver))+ resolve/*import-resolver* ((requiring-resolve 'metabase.models.serialization.resolve.default/cached-import-resolver))]~@body))diff --git a/src/metabase/models/serialization/resolve/db.clj b/src/metabase/models/serialization/resolve/default.cljsimilarity index 81%rename from src/metabase/models/serialization/resolve/db.cljrename to src/metabase/models/serialization/resolve/default.cljindex a03dfc207d2..7324924fe0c 100644--- a/src/metabase/models/serialization/resolve/db.clj+++ b/src/metabase/models/serialization/resolve/default.clj@@ -1,9 +1,10 @@-(ns metabase.models.serialization.resolve.db+(ns metabase.models.serialization.resolve.default"Database-backed implementations of the serdes resolver protocols.These are the default resolvers used during normal serdes export/importagainst the application database."(:require+ [metabase.models.db :as models.db][metabase.models.serialization :as serdes][metabase.models.serialization.resolve :as resolve][metabase.util.log :as log]@@ -21,7 +22,7 @@[id model](when id(let [model-name (name model)- entity (t2/select-one model (first (t2/primary-keys model)) id)+ entity (models.db/entity-by-own-pk model id)path (when entity(mapv :id (serdes/generate-path model-name entity)))](cond@@ -35,7 +36,7 @@(defn export-fk-keyed"Given a numeric ID, look up a different identifying field for that entity."[id model field]- (t2/select-one-fn field model :id id))+ (models.db/entity-field model id field))(defn export-user"Export a user as their email address."@@ -46,8 +47,8 @@"Given a numeric table_id, return a portable table reference [db-name schema table-name]."[table-id](when table-id- (let [{:keys [db_id name schema]} (t2/select-one [:model/Table :id :db_id :name :schema] :id table-id)- db-name (t2/select-one-fn :name [:model/Database :id :name] :id db_id)]+ (let [{:keys [db_id name schema]} (models.db/table-ref-columns table-id)+ db-name (models.db/database-name db_id)][db-name schema name])))(defn export-field-fk@@ -76,7 +77,7 @@(defn import-fk-keyed"Given a portable identifying field value, return the numeric :id."[portable model field]- (t2/select-one-pk model field portable))+ (models.db/pk-by-field model field portable))(defn import-user"Import a user by email, creating if needed. Returns PK."@@ -90,11 +91,7 @@"Creates a new inactive Table for a deserialized reference whose `[db-name schema table-name]`triple doesn't match any existing row. Returns the new table id."[db-id schema table-name]- (:id (t2/insert-returning-instance! :model/Table- {:db_id db-id- :schema schema- :name table-name- :active false})))+ (models.db/insert-inactive-table! db-id schema table-name))(defn- synthesize-field!"Walks a field path from top-level to deepest, returning each existing field id and creating any@@ -103,33 +100,26 @@(loop [parent-id nilremaining field-names](if-let [field-name (first remaining)]- (let [field-id (or (t2/select-one-pk :model/Field- :table_id table-id- :name field-name- :parent_id parent-id)- (t2/insert-returning-pk! :model/Field- {:table_id table-id- :parent_id parent-id- :name field-name- :active false- :base_type :type/*- :database_type "NULL"}))]+ (let [field-id (or (models.db/field-pk table-id field-name parent-id)+ (models.db/insert-inactive-field! table-id parent-id field-name))](recur field-id (rest remaining)))parent-id)))(defn import-table-fk"Given [db-name schema table-name], return numeric table_id. If the database exists but the table- doesn't, synthesize an inactive Table from the path so we can still resolve the reference."+ doesn't, synthesize an inactive Table from the path so we can still resolve the reference. The thrown ex-data's+ `:error` is pinned to `:metabase.models.serialization.resolve.db/database-not-found` — this code's old namespace,+ before this file replaced it — since other modules and tests compare against that literal keyword value."[[db-name schema table-name :as table-id]](when table-id- (if-let [db-id (t2/select-one-fn :id :model/Database :name db-name)]- (or (t2/select-one-fn :id :model/Table :name table-name :schema schema :db_id db-id)+ (if-let [db-id (models.db/database-id-by-name db-name)]+ (or (models.db/table-id-by-name table-name schema db-id)(synthesize-table! db-id schema table-name))(throw (ex-info (format "table id present, but database not found: %s" table-id){:table-id table-id:db-name db-name- :database-names (sort (t2/select-fn-vec :name :model/Database))- :error ::database-not-found})))))+ :database-names (sort (models.db/database-names))+ :error :metabase.models.serialization.resolve.db/database-not-found})))))(defn import-field-fk"Given [db-name schema table-name field-name ...], return numeric field_id. If part of the parent@@ -137,9 +127,8 @@reference."[resolver [db-name schema table-name & fields :as field-id]](when field-id- (let [table-id (resolve/import-table-fk resolver [db-name schema table-name])- field-q (serdes/recursively-find-field-q table-id (reverse fields))]- (or (t2/select-one-pk :model/Field field-q)+ (let [table-id (resolve/import-table-fk resolver [db-name schema table-name])]+ (or (models.db/field-pk-in-path table-id (reverse fields))(synthesize-field! table-id fields)))));;; ============================================================diff --git a/src/metabase/models/serialization/resolve/mp.clj b/src/metabase/models/serialization/resolve/mp.cljindex 447e161bc92..c7574feb82a 100644--- a/src/metabase/models/serialization/resolve/mp.clj+++ b/src/metabase/models/serialization/resolve/mp.clj@@ -1,7 +1,7 @@(ns metabase.models.serialization.resolve.mp"Metadata-provider-backed implementations of the serdes resolver protocols.- Unlike `metabase.models.serialization.resolve.db`, this resolver does not touch toucan2 /+ Unlike `metabase.models.serialization.resolve.default`, this resolver does not touch toucan2 /the application database for *warehouse-schema* lookups (tables, fields) - it works off a`lib.metadata/MetadataProvider`, which may be the live application-DB-backed provider, atest-only mock provider, or any cached variant.@@ -37,11 +37,11 @@[metabase.app-db.core :as mdb][metabase.lib.metadata :as lib.metadata][metabase.lib.metadata.protocols :as lib.metadata.protocols]+ [metabase.models.db :as models.db][metabase.models.serialization :as serdes][metabase.models.serialization.resolve :as resolve][metabase.util.i18n :refer [tru]]- [potemkin.types :as p.types]- [toucan2.core :as t2]))+ [potemkin.types :as p.types]))(set! *warn-on-reflection* true)@@ -74,7 +74,7 @@(defn- matching-tables-via-app-db"Return all tables matching the `(db-id, schema, table-name)` triple by direct application-DB- query — same shape `resolve.db/import-table-fk` has always used. Bypasses the metadata+ query — same shape `resolve.default/import-table-fk` has always used. Bypasses the metadataprovider entirely.Returns inactive rows too: the app DB is authoritative for *existence*, and@@ -85,7 +85,7 @@`001_update_migrations.yaml` `is_defective_duplicate` carve-out for pre-constraint rows)return more than one candidate so [[find-table]] can raise `:ambiguous-table`."[db-id schema table-name]- (t2/select :metadata/table :db_id db-id :schema schema :name table-name))+ (models.db/metadata-tables db-id schema table-name))(defn- app-db-backed-provider?"True when `metadata-provider` is part of the production app-DB-backed wrapper chain@@ -336,13 +336,13 @@;; transforming the entire dataset_query just to export one stable identifier.;; `:card_schema` must ride along: selecting `:database_id` makes the after-select;; treat this as a full card row and demand it.- (t2/select-one [:model/Card :id :entity_id :collection_id :database_id :card_schema] :id card-id)))+ (models.db/card-serdes-columns card-id)))(measure-by-id [_ measure-id](when measure-id- (t2/select-one [:model/Measure :id :entity_id :table_id] :id measure-id)))+ (models.db/measure-serdes-columns measure-id)))(segment-by-id [_ segment-id](when segment-id- (t2/select-one [:model/Segment :id :entity_id :table_id] :id segment-id)))))+ (models.db/segment-serdes-columns segment-id)))));;; ============================================================;;; Resolver implementationsdiff --git a/src/metabase/models/util/spec_update.clj b/src/metabase/models/util/spec_update.cljindex 02af0009fd0..db696025683 100644--- a/src/metabase/models/util/spec_update.clj+++ b/src/metabase/models/util/spec_update.clj@@ -6,6 +6,7 @@[malli.error :as me][malli.transform :as mtx][medley.core :as m]+ [metabase.models.db :as models.db][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]@@ -138,7 +139,7 @@(sanitize-row row)))];; Update the parent row if needed(when (or force-update? updates-needed?)- (t2/update! model (id-col row) (sanitize-row row-with-refs)))+ (models.db/update-entity! model (id-col row) (sanitize-row row-with-refs)));; Handle non-ref nested models(when nested-specs(let [nested-without-refs (non-ref-nested-models nested-specs row)]@@ -166,7 +167,7 @@(let [;; Process any ref-in-parent models firstparent-updates (handle-refs-in-parent! nil row nested-specs path)row-with-refs (merge row parent-updates)- parent-id (t2/insert-returning-pk! model (sanitize-row row-with-refs))]+ parent-id (models.db/insert-entity-returning-pk! model (sanitize-row row-with-refs))](log/debugf "%s created a new entity %s %s" (format-path path) model parent-id);; Only process non-ref nested models(let [nested-without-refs (non-ref-nested-models nested-specs row)]@@ -179,11 +180,11 @@(do(log/tracef "%s no nested spec found, batch creating %d new rows of %s" (format-path path) (count to-create) model)(let [rows (map sanitize-row to-create)]- (t2/insert! model rows)))))+ (models.db/insert-entities! model rows)))))(when (seq to-delete);; TODO: cascade deletes?(log/debugf "%s deleting %d rows with ids %s" (format-path path) (count to-delete) (str/join ", " (map id-col to-delete)))- (t2/delete! model id-col [:in (map id-col to-delete)]))+ (models.db/delete-entities-with-ids! model id-col (map id-col to-delete)))(when (seq to-update)(log/tracef "%s Attempt updating %s rows of %s" (format-path path) (count to-update) model)(doseq [row to-update]@@ -222,13 +223,13 @@(nil? new-data)(do(log/debugf "%s Deleting" (format-path (conj path existing-id)))- (t2/delete! model existing-id)+ (models.db/delete-entity! model existing-id)(handle-nested! existing-data new-data existing-id)nil);; create(nil? existing-data)- (let [parent-id (t2/insert-returning-pk! model new-data-sanitized)+ (let [parent-id (models.db/insert-entity-returning-pk! model new-data-sanitized)path (conj path parent-id)](log/debugf "%s Created a new entity %s %s" (format-path path) model parent-id)(handle-nested! nil new-data parent-id)@@ -239,8 +240,8 @@(do(log/debugf "%s ID changed from %s to %s - deleting and recreating"(format-path path) existing-id (id-col new-data))- (t2/delete! model existing-id)- (let [parent-id (t2/insert-returning-pk! model new-data-sanitized)+ (models.db/delete-entity! model existing-id)+ (let [parent-id (models.db/insert-entity-returning-pk! model new-data-sanitized)path (conj path parent-id)](log/debugf "%s Created a new entity %s %s" (format-path path) model parent-id)(handle-nested! nil new-data parent-id)@@ -250,7 +251,7 @@(not= (compare-row new-data-sanitized) (compare-row existing-data-sanitized))(do(log/debugf "%s Updating" (format-path (conj path existing-id)))- (t2/update! model existing-id new-data-sanitized)+ (models.db/update-entity! model existing-id new-data-sanitized)(handle-nested! existing-data new-data existing-id)existing-id)diff --git a/src/metabase/mq/db.clj b/src/metabase/mq/db.cljnew file mode 100644index 00000000000..3ca843ae631--- /dev/null+++ b/src/metabase/mq/db.clj@@ -0,0 +1,47 @@+(ns metabase.mq.db+ "Application database queries for the message queue module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn waiting-queue-triggers-before+ "The `{:trigger_name :job_name}` rows of `trigger-group` triggers in `sched-name`'s Quartz store that are `WAITING`+ and started before `threshold` (epoch ms)."+ [sched-name trigger-group threshold]+ ;; unquoted upper-case `QRTZ_TRIGGERS` resolves on every app DB; see [[metabase.mq.task.queue-reaper]].+ (t2/query [(str "SELECT trigger_name, job_name FROM QRTZ_TRIGGERS"+ " WHERE sched_name = ? AND trigger_group = ? AND trigger_state = 'WAITING'"+ " AND start_time < ?")+ sched-name trigger-group threshold]))++(defn insert-outbox-row!+ "Insert a `queue_message_outbox` row for `queue-name` with `payload` and return its id."+ [queue-name payload]+ (t2/insert-returning-pk! :queue_message_outbox {:queue_name queue-name, :payload payload}))++(defn delete-outbox-rows!+ "Delete the `queue_message_outbox` rows with `ids`."+ [ids]+ (t2/delete! :queue_message_outbox :id [:in ids]))++(defn due-outbox-rows+ "Up to `limit` `queue_message_outbox` rows after `after-id`, in id order, that are due: never attempted and created+ before `created-before`, or scheduled to retry at or before `now`. Locked with the `for` clause `for-clause`."+ [after-id now created-before limit for-clause]+ (t2/query {:select [:id :queue_name :payload :publish_attempts]+ :from [:queue_message_outbox]+ :where [:and+ [:> :id after-id]+ [:or+ [:and [:= :next_attempt_at nil] [:< :created_at created-before]]+ [:<= :next_attempt_at now]]]+ :order-by [[:id :asc]]+ :limit limit+ :for for-clause}))++(defn bump-outbox-row!+ "Increment the publish attempts of the `queue_message_outbox` row with `id` and schedule its next attempt."+ [id next-attempt-at]+ (t2/update! :queue_message_outbox :id id+ {:publish_attempts [:+ :publish_attempts [:inline 1]]+ :next_attempt_at next-attempt-at}))diff --git a/src/metabase/mq/queue/outbox.clj b/src/metabase/mq/queue/outbox.cljindex 13837b63628..dce1d043e28 100644--- a/src/metabase/mq/queue/outbox.clj+++ b/src/metabase/mq/queue/outbox.clj@@ -19,6 +19,7 @@(:require[metabase.analytics-interface.core :as analytics][metabase.app-db.core :as mdb]+ [metabase.mq.db :as mq.db][metabase.mq.payload :as payload][metabase.mq.queue.backend :as q.backend][metabase.mq.queue.registry :as q.registry]@@ -72,9 +73,7 @@"Insert one already-encoded batch `payload` for `channel` as a `queue_message_outbox` row and returnits primary key."[channel payload]- (t2/insert-returning-pk! :queue_message_outbox- {:queue_name (name channel)- :payload payload}))+ (mq.db/insert-outbox-row! (name channel) payload))(defn insert-outbox-rows!"before-commit callback: for every channel buffered in `*transaction-state*`, apply the queue's@@ -114,7 +113,7 @@[](::rows @state))](when (seq published-ids)- (t2/delete! :queue_message_outbox :id [:in published-ids]))))+ (mq.db/delete-outbox-rows! published-ids))))(defn defer-transactional!"Routes `msgs` for `channel` through the transactional outbox. Accumulates them per channel in@@ -155,17 +154,11 @@(t2/with-transaction [_conn](let [now (Instant/now)now-ts (Timestamp/from now)- rows (t2/query {:select [:id :queue_name :payload :publish_attempts]- :from [:queue_message_outbox]- :where [:and- [:> :id after-id]- [:or- [:and [:= :next_attempt_at nil]- [:< :created_at (Timestamp/from (.minusMillis now recovery-age-ms))]]- [:<= :next_attempt_at now-ts]]]- :order-by [[:id :asc]]- :limit recovery-page-size- :for (for-update-clause)})+ rows (mq.db/due-outbox-rows after-id+ now-ts+ (Timestamp/from (.minusMillis now recovery-age-ms))+ recovery-page-size+ (for-update-clause)){:keys [recover-ids bumps backend-down?]}(reduce (fn [acc {:keys [id queue_name payload] :as row}](try@@ -180,11 +173,9 @@{:recover-ids [] :bumps [] :backend-down? false}rows)];; published rows are removed; message-specific failures have their attempt count bumped and next retry scheduled.- (when (seq recover-ids) (t2/delete! :queue_message_outbox :id [:in recover-ids]))+ (when (seq recover-ids) (mq.db/delete-outbox-rows! recover-ids))(doseq [{:keys [id next-attempt-at]} bumps]- (t2/update! :queue_message_outbox :id id- {:publish_attempts [:+ :publish_attempts [:inline 1]]- :next_attempt_at next-attempt-at}))+ (mq.db/bump-outbox-row! id next-attempt-at))(when backend-down?(log/info "Outbox recovery: backend unavailable, remaining rows retry next run"));; nil next-after-id stops the sweep: no more due rows, or the backend is down.diff --git a/src/metabase/mq/task/queue_reaper.clj b/src/metabase/mq/task/queue_reaper.cljindex 699851b1479..0da2c02f0ec 100644--- a/src/metabase/mq/task/queue_reaper.clj+++ b/src/metabase/mq/task/queue_reaper.clj@@ -23,11 +23,11 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][metabase.analytics-interface.core :as analytics]+ [metabase.mq.db :as mq.db][metabase.mq.quartz-affinity :as quartz-affinity][metabase.mq.settings :as mq.settings][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.lang.management ManagementFactory)(java.time Instant)@@ -55,10 +55,7 @@lower-case* reference (`:qrtz_triggers`) fails on case-sensitive MySQL/MariaDB. (Quartz's own SQLreferences these tables the same unquoted upper-case way.)"[sched-name threshold]- (t2/query [(str "SELECT trigger_name, job_name FROM QRTZ_TRIGGERS"- " WHERE sched_name = ? AND trigger_group = ? AND trigger_state = 'WAITING'"- " AND start_time < ?")- sched-name quartz-affinity/queue-job-group threshold]))+ (mq.db/waiting-queue-triggers-before sched-name quartz-affinity/queue-job-group threshold))(defn- drop-orphaned-triggers!"Drops queue message triggers that have sat `WAITING` — never acquired by any node — for longer thandiff --git a/src/metabase/native_query_snippets/api.clj b/src/metabase/native_query_snippets/api.cljindex ba413da8406..3be6d0bbb2e 100644--- a/src/metabase/native_query_snippets/api.clj+++ b/src/metabase/native_query_snippets/api.clj@@ -6,6 +6,7 @@[metabase.api.macros :as api.macros][metabase.collections.core :as collections][metabase.models.interface :as mi]+ [metabase.native-query-snippets.db :as native-query-snippets.db][metabase.native-query-snippets.models.native-query-snippet :as native-query-snippet][metabase.util :as u][metabase.util.i18n :refer [tru]]@@ -20,9 +21,7 @@([](list-native-query-snippets false))([archived :- ms/BooleanValue]- (let [snippets (t2/select :model/NativeQuerySnippet- :archived archived- {:order-by [[:%lower.name :asc]]})]+ (let [snippets (native-query-snippets.db/snippets-by-archived archived)](t2/hydrate (filter mi/can-read? snippets) :creator :is_remote_synced))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -39,7 +38,7 @@(mu/defn get-native-query-snippet :- [:maybe (ms/InstanceOf :model/NativeQuerySnippet)]"Fetch native query snippet with ID and hydrate creator."[id :- ms/PositiveInt]- (-> (api/read-check (t2/select-one :model/NativeQuerySnippet :id id))+ (-> (api/read-check (native-query-snippets.db/snippet id))(t2/hydrate :creator :is_remote_synced)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -53,7 +52,7 @@(get-native-query-snippet id))(defn- check-snippet-name-is-unique [snippet-name]- (when (t2/exists? :model/NativeQuerySnippet :name snippet-name)+ (when (native-query-snippets.db/snippet-name-exists? snippet-name)(throw (ex-info (tru "A snippet with that name already exists. Please pick a different name."){:status-code 400}))))@@ -77,13 +76,13 @@:name name:collection_id collection_id}](api/create-check :model/NativeQuerySnippet snippet)- (api/check-500 (first (t2/insert-returning-instances! :model/NativeQuerySnippet snippet)))))+ (api/check-500 (native-query-snippets.db/insert-snippet! snippet))))(defn- check-perms-and-update-snippet!"Check whether current user has write permissions, then update NativeQuerySnippet with values in `body`. Returnsupdated/hydrated NativeQuerySnippet"[id body]- (let [snippet (t2/select-one :model/NativeQuerySnippet :id id)+ (let [snippet (native-query-snippets.db/snippet id)body-fields (u/select-keys-when body:present #{:description :collection_id}:non-nil #{:archived :content :name})@@ -93,7 +92,7 @@(when-let [new-name (:name changes)](check-snippet-name-is-unique new-name))(t2/with-transaction [_conn]- (t2/update! :model/NativeQuerySnippet id changes)+ (native-query-snippets.db/update-snippet! id changes)(collections/check-for-remote-sync-update snippet)))(get-native-query-snippet id)))diff --git a/src/metabase/native_query_snippets/db.clj b/src/metabase/native_query_snippets/db.cljnew file mode 100644index 00000000000..ced861973df--- /dev/null+++ b/src/metabase/native_query_snippets/db.clj@@ -0,0 +1,62 @@+(ns metabase.native-query-snippets.db+ "Application database queries for the native query snippets module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [metabase.models.serialization :as serdes]+ [toucan2.core :as t2]))++(defn snippets-by-archived+ "The NativeQuerySnippets whose archived flag is `archived`, in case-insensitive name order."+ [archived]+ (t2/select :model/NativeQuerySnippet :archived archived {:order-by [[:%lower.name :asc]]}))++(defn snippet+ "The NativeQuerySnippet with `id`, or nil."+ [id]+ (t2/select-one :model/NativeQuerySnippet :id id))++(defn snippet-name-exists?+ "Whether a NativeQuerySnippet named `snippet-name` exists."+ [snippet-name]+ (t2/exists? :model/NativeQuerySnippet :name snippet-name))++(defn other-snippet-with-name-exists?+ "Whether a NativeQuerySnippet named `snippet-name` with an entity id other than `entity-id` exists."+ [snippet-name entity-id]+ (t2/exists? :model/NativeQuerySnippet :name snippet-name :entity_id [:!= entity-id]))++(defn insert-snippet!+ "Insert the NativeQuerySnippet `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/NativeQuerySnippet row))++(defn update-snippet!+ "Apply `changes` to the NativeQuerySnippet with `id`."+ [id changes]+ (t2/update! :model/NativeQuerySnippet id changes))++(defn snippet-id-by-name+ "The id of the NativeQuerySnippet named `snippet-name`, or nil."+ [snippet-name]+ (t2/select-one-fn :id :model/NativeQuerySnippet :name snippet-name))++(defn snippet-collection-id+ "The Collection id of the NativeQuerySnippet with `id`, or nil."+ [id]+ (t2/select-one-fn :collection_id :model/NativeQuerySnippet :id id))++(defn exportable-snippets+ "A reducible of the NativeQuerySnippets to export via serdes: unarchived when `skip-archived?`, and either+ in one of `collection-ids`, uncollected when `include-root?`, or matching the serdes-supplied+ `extra-condition` — an additional condition the caller widens the export scope with (e.g. also export as+ a Card dependency, regardless of collection), or nil — in stable export order."+ [collection-ids include-root? skip-archived? extra-condition]+ (t2/reducible-select :model/NativeQuerySnippet+ (cond-> {:where [:and+ (when skip-archived? [:not :archived])+ [:or+ (when (seq collection-ids) [:in :collection_id collection-ids])+ (when include-root? [:= :collection_id nil])]]+ :order-by serdes/stable-storage-order}+ extra-condition (sql.helpers/where :or extra-condition))))diff --git a/src/metabase/native_query_snippets/models/native_query_snippet.clj b/src/metabase/native_query_snippets/models/native_query_snippet.cljindex 3bc61dd9406..e2954ee218a 100644--- a/src/metabase/native_query_snippets/models/native_query_snippet.clj+++ b/src/metabase/native_query_snippets/models/native_query_snippet.clj@@ -1,12 +1,12 @@(ns metabase.native-query-snippets.models.native-query-snippet(:require- [honey.sql.helpers :as sql.helpers][metabase.api.common :as api][metabase.collections.models.collection :as collection][metabase.events.core :as events][metabase.lib.core :as lib][metabase.models.interface :as mi][metabase.models.serialization :as serdes]+ [metabase.native-query-snippets.db :as native-query-snippets.db][metabase.native-query-snippets.models.native-query-snippet.permissions :as snippet.perms][metabase.remote-sync.core :as remote-sync][metabase.util :as u]@@ -66,8 +66,7 @@(lib/recognize-template-tags (:content snippet)))set-snippet-id (fn [{:keys [snippet-name] :as tag}];; Check for exact match in database:- (if-let [snippet-id (t2/select-one-fn :id :model/NativeQuerySnippet- :name snippet-name)]+ (if-let [snippet-id (native-query-snippets.db/snippet-id-by-name snippet-name)](assoc tag :snippet-id snippet-id);; Use previous reference if possible:(or (name->old-tag snippet-name) tag)))]@@ -161,16 +160,11 @@;; NativeQuerySnippets live in their own special collections, so the logic is the following:;; - you either are exporting one of those;; - or it was requested as a dependency of some Card, so export it regardless of collection- (t2/reducible-select :model/NativeQuerySnippet (cond-> {:where [:and- (when skip-archived [:not :archived])- [:or- (when-let [collection-ids (not-empty (remove nil? collection-set))]- [:in :collection_id collection-ids])- (when (some nil? collection-set)- [:= :collection_id nil])]]- ;; stable filename de-dup suffixes across exports, see GHY-3754- :order-by serdes/stable-storage-order}- where (sql.helpers/where :or where))))+ (native-query-snippets.db/exportable-snippets+ (not-empty (remove nil? collection-set))+ (boolean (some nil? collection-set))+ skip-archived+ where))(defmethod serdes/make-spec "NativeQuerySnippet" [_model-name _opts]{:copy [:archived :content :description :entity_id :name]@@ -186,7 +180,7 @@(defmethod serdes/required "NativeQuerySnippet"[_model id]- (when-let [collection_id (t2/select-one-fn :collection_id :model/NativeQuerySnippet :id id)]+ (when-let [collection_id (native-query-snippets.db/snippet-collection-id id)]{["Collection" collection_id] {"NativeQuerySnippet" id}}))(defmethod serdes/deserialization-dependencies "NativeQuerySnippet"@@ -207,8 +201,7 @@;; if we got local snippet in db and it has same name as incoming one, we can be sure;; there will be no conflicts and skip the query to the db(if (and (not= (:name ingested) (:name maybe-local))- (t2/exists? :model/NativeQuerySnippet- :name (:name ingested) :entity_id [:!= (:entity_id ingested)]))+ (native-query-snippets.db/other-snippet-with-name-exists? (:name ingested) (:entity_id ingested)))(recur (update ingested :name str " (copy)")maybe-local)(serdes/default-load-one! ingested maybe-local)))diff --git a/src/metabase/notification/api/admin.clj b/src/metabase/notification/api/admin.cljindex 81823c8c59b..63efc22a2d4 100644--- a/src/metabase/notification/api/admin.clj+++ b/src/metabase/notification/api/admin.clj@@ -22,18 +22,14 @@`last_send_status=failing` corresponds to the Failing tab — notifications whose most recentsend tick (rolled up across all channels) had at least one channel failure."(:require- [clojure.string :as str]- [honey.sql.helpers :as sql.helpers][medley.core :as m][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.app-db.core :as mdb]- [metabase.models.interface :as mi][metabase.notification.api.notification :as notification-api]+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.request.core :as request][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [tru]][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]@@ -125,8 +121,7 @@(into #{}(comp (filter #(some-> % :details :value u/lower-case-en (= lower-email)))(map :notification_handler_id))- (t2/reducible-select [:model/NotificationRecipient :notification_handler_id :details]- :type :notification-recipient/raw-value))))+ (notification.db/raw-value-recipients-reducible))))(defn- notification-ids-with-recipient-email"Notification IDs whose recipients (user or raw-value) match `email` exactly. One SQL query@@ -134,253 +129,8 @@recipients via a pre-resolved set of handler IDs from an in-memory scan."[email](let [lower-email (u/lower-case-en email)- raw-handler-ids (handler-ids-with-raw-value-matching email)- user-clause [:and- [:= :nr.type "notification-recipient/user"]- [:= [:lower :cu.email] lower-email]]- where-clause (if (seq raw-handler-ids)- [:or user-clause [:in :notification_handler.id raw-handler-ids]]- user-clause)]- (t2/select-fn-set- :notification_id (t2/table-name :model/NotificationHandler)- {:join [[(t2/table-name :model/NotificationRecipient) :nr]- [:= :nr.notification_handler_id :notification_handler.id]]- :left-join [[:core_user :cu] [:= :cu.id :nr.user_id]]- :where where-clause})))--(defn- query-where-clause- "WHERE clause for the fuzzy `?query=` filter. Substring ILIKE OR'd across card name and creator- first/last/email. Recipient branches were removed in the design iteration — recipients stay as- the structured `?recipient_email=` filter."- [query]- (let [wildcard (h2x/like-substring query)]- [:or- [:like [:lower :c.name] wildcard]- [:like [:lower :cu.first_name] wildcard]- [:like [:lower :cu.last_name] wildcard]- [:like [:lower :cu.email] wildcard]]))--(def ^:private run-lookback-days- "How far back to consider alert-type TaskRuns / TaskHistory rows when computing run summaries."- 90)--(defn- lookback-cutoff []- (h2x/add-interval-honeysql-form (mdb/db-type) (mi/now) (- run-lookback-days) :day))--(defn- latest-run-per-notification- "Honey.sql subquery: one row per notification with its most recent terminal alert-type TaskRun- (status :success / :failed / :abandoned) within [[run-lookback-days]]. Excludes :started in-flight- runs (they shouldn't surface as a `last_check`) and runs with no `notification_id` (unattributable,- e.g. created before that column existed). Uses- `ROW_NUMBER() OVER (PARTITION BY notification_id ORDER BY started_at DESC)`."- []- ^:allow-subquery- {:select [:id :notification_id :status :started_at :ended_at]- :from [[^:allow-subquery- {:select [:id :notification_id :status :started_at :ended_at- [[:over [[:row_number]- ^:allow-subquery- {:partition-by [:notification_id]- :order-by [[:started_at :desc]]}]]- :rn]]- :from [:task_run]- :where [:and- [:= :run_type run-type-alert]- [:is-not :notification_id nil]- [:in :status terminal-statuses]- [:> :started_at (lookback-cutoff)]]}- :sub]]- :where [:= :sub.rn 1]})--(defn- latest-send-tick-per-notification- "Honey.sql subquery: one row per notification summarising the LATEST tick that had channel-send- attempts within [[run-lookback-days]]. The inner subquery ranks each notification's runs that have- a channel-send child by `started_at DESC` and keeps rank=1; the outer computes `has_failure` with- a correlated EXISTS rather than GROUP BY + SUM, to stay H2/Postgres/MySQL compatible.-- Result columns:- - `:notification_id` — join key used by base-list-query- - `:id` — task_run.id of the latest send tick (for looking up channel-send error msg)- - `:started_at` — the tick's started_at (for sort + `:last_send.at`)- - `:has_failure` — true if any channel-send in the tick failed"- []- (let [lookback (lookback-cutoff)]- ^:allow-subquery- {:select [:lr.notification_id- [:lr.run_id :id]- [:lr.tick_started_at :started_at]- ;; Boolean CASE, read back in Clojure — same pattern as- ;; `metabase.search.in-place.legacy/bookmark-col`. `has-failure?` runs it through- ;; `bit->boolean` to absorb the MySQL/MariaDB bit-vs-boolean JDBC quirk.- [[:case- [:exists ^:allow-subquery- {:select [[1]]- :from [[:task_history :tf]]- :where [:and- [:= :tf.run_id :lr.run_id]- [:= :tf.task task-channel-send]- [:= :tf.status "failed"]]}]- true- :else false]- :has_failure]]- :from [[^:allow-subquery- {:select [:tr2.notification_id- [:tr2.id :run_id]- [:tr2.started_at :tick_started_at]- [[:over [[:row_number]- ^:allow-subquery- {:partition-by [:tr2.notification_id]- :order-by [[:tr2.started_at :desc]]}]]- :rn]]- :from [[:task_run :tr2]]- :where [:and- [:= :tr2.run_type run-type-alert]- [:is-not :tr2.notification_id nil]- [:in :tr2.status terminal-statuses]- [:> :tr2.started_at lookback]- ;; only keep runs that actually had channel-send rows- [:exists ^:allow-subquery- {:select [[1]]- :from [[:task_history :tx]]- :where [:and- [:= :tx.run_id :tr2.id]- [:= :tx.task task-channel-send]]}]]}- :lr]]- :where [:= :lr.rn 1]}))--(def ^:private sort-column->order-by- "Maps the public `sort_column` enum to the SQL expression used in `ORDER BY`. Uses raw- expressions rather than the SELECT aliases because H2 does not resolve aliases inside- expressions. Whitelist; values outside this map are rejected by the `::sort-column` malli enum- upstream."- {:id :notification.id- :last_send :ls.started_at- :last_check :lc.started_at- :card_name :c.name- :creator_name [:coalesce :cu.last_name :cu.first_name :cu.email]- :updated_at :notification.updated_at})--(defn- channel-exists- "Honey `EXISTS` correlated with `:notification.id`: TRUE when the notification has at least one- handler whose channel_type is IN `channels`. Accepts either a single string or a vector of- strings (OR semantics across multiple channel types). Subquery instead of JOIN so the outer- query needs no `DISTINCT`."- [channels]- (let [channels (if (sequential? channels) channels [channels])]- [:exists- ^:allow-subquery- {:select [[1]]- :from [(t2/table-name :model/NotificationHandler)]- :where [:and- [:= :notification_handler.notification_id :notification.id]- [:in :notification_handler.channel_type channels]]}]))--(defn- list-where-clauses- "Optional WHERE clauses for the list/detail query, returned as data (a seq with inactive filters- elided) so `base-list-query` can `(reduce sql.helpers/where ...)` them onto the query."- [{:keys [active creator_id creator_active creatorless card_id recipient_email channel- last_send_status last_check_status query]}]- (keep- identity- [(when (some? active) [:= :notification.active active])- (when (some? creator_active) [:= :cu.is_active creator_active])- ;; `creatorless` = true: no creator at all, OR a deactivated creator (both are "creatorless")- ;; `creatorless` = false: has a live (active) creator- ;; [:= col nil] is IS NULL and [:is-not col nil] is IS NOT NULL per HoneySQL 2 semantics.- (when (true? creatorless)- [:or [:= :notification.creator_id nil] [:= :cu.is_active false]])- (when (false? creatorless)- [:and [:is-not :notification.creator_id nil] [:= :cu.is_active true]])- (when creator_id [:= :notification.creator_id creator_id])- (when card_id [:= :nc.card_id card_id])- (when (seq channel) (channel-exists channel))- (when last_send_status- (case last_send_status- :successful [:= :ls.has_failure false]- :failing [:= :ls.has_failure true]))- ;; `last_check` is the whole-run rollup (success/failed/abandoned), so it's a superset of- ;; `last_send`: it catches query failures and heartbeat-abandoned runs that never reached the- ;; channel-send step, not just delivery failures. The Failing tab filters on this.- (when last_check_status- (case last_check_status- :successful [:= :lc.status "success"]- :failing [:in :lc.status ["failed" "abandoned"]]))- (when recipient_email- (let [ids (notification-ids-with-recipient-email recipient_email)]- ;; No recipient matched → an always-false predicate so the page comes back empty. We use- ;; the truthy `[:= 1 0]` (renders `WHERE 1 = 0`) rather than `false`/`nil`, which the- ;; `keep identity` above would elide — turning "no matches" into "no filter".- (if (seq ids) [:in :notification.id ids] [:= 1 0])))- (when-not (str/blank? query) (query-where-clause query))]))--(defn- base-list-query- "Select notifications plus run-summary columns, card name, and creator name computed inline.-- When `skip-run-joins?` is true (detail path only), the `lc`/`ls` window subqueries and their- select columns are omitted — the detail endpoint overwrites `last_check`/`last_send` from- per-notification histories anyway, so those joins are pure waste on that path."- [{:keys [skip-run-joins?] :as filters}]- (reduce- sql.helpers/where- (cond-> {:select (cond-> [:notification.id- :notification.active- :notification.creator_id- :notification.created_at- :notification.updated_at- :notification.payload_type- :notification.payload_id- [:c.name :card_name]- [:cu.is_active :creator_is_active]- [[:coalesce :cu.last_name :cu.first_name :cu.email] :creator_name]]- (not skip-run-joins?)- (into [[:lc.id :lc_id]- [:lc.status :lc_status]- [:lc.started_at :lc_started_at]- [:ls.id :ls_id]- [:ls.started_at :ls_started_at]- [:ls.has_failure :ls_has_failure]]))- :from [:notification]- ;; A `notification/card` row with no payload_id is orphaned — it has no card, so- ;; every card-derived column is null and it can't be managed here. Exclude it.- :where [:and- [:= :notification.payload_type "notification/card"]- [:is-not :notification.payload_id nil]]}-- ;; These joins are always present regardless of the path.- true- (-> (sql.helpers/left-join [:notification_card :nc] [:= :nc.id :notification.payload_id])- (sql.helpers/left-join [:report_card :c] [:= :c.id :nc.card_id])- (sql.helpers/left-join [:core_user :cu] [:= :cu.id :notification.creator_id]))-- ;; Window subquery joins — skipped on the detail path (see docstring). Keyed by notification_id- ;; so each notification gets exactly its own latest run, not the card's (which would bleed- ;; across every notification sharing the card).- (not skip-run-joins?)- (-> (sql.helpers/left-join [(latest-run-per-notification) :lc] [:= :lc.notification_id :notification.id])- (sql.helpers/left-join [(latest-send-tick-per-notification) :ls] [:= :ls.notification_id :notification.id])))- (list-where-clauses filters)))--(defn- order-by-clauses- "Resolve `sort_column` + `sort_direction` (both already malli-validated enums) into an- honeysql `:order-by` vector. Pushes nulls last unconditionally — H2/Postgres/MySQL all default- to NULLS-FIRST under DESC. Always tie-breaks on `notification.id desc` so paging is stable."- [sort-column sort-direction]- (let [col (sort-column->order-by sort-column)- dir (or sort-direction :desc)]- [[[:case [:= col nil] 1 :else 0] :asc]- [col dir]- [:notification.id :desc]]))--(defn- list-query- [{:keys [sort_column sort_direction] :as filters}]- (assoc (base-list-query (dissoc filters :sort_column :sort_direction))- :order-by (order-by-clauses (or sort_column :last_send) sort_direction)))--(defn- count-query- [filters]- (-> (list-query filters)- (assoc :select [[[:count :notification.id] :count]])- (dissoc :order-by)))+ raw-handler-ids (handler-ids-with-raw-value-matching email)]+ (notification.db/handler-notification-ids-for-email lower-email raw-handler-ids)))(defn- coerce-run-status"Map a task_run/task_history `:status` keyword to the public `::run-status` enum.@@ -433,25 +183,7 @@CASE is a no-op when `task-name` is supplied — all candidate rows share the same `:task`."[task-name run-ids](when (seq run-ids)- (->> (t2/select :model/TaskHistory- {:select [:run_id :task_details]- :from [[^:allow-subquery- {:select [:run_id :task_details- [[:over [[:row_number]- ^:allow-subquery- {:partition-by [:run_id]- :order-by [[[:case- [:= :task task-notification-send] 0- :else 1] :asc]- [:ended_at :desc]]}]]- :rn]]- :from [:task_history]- :where (cond-> [:and- [:in :run_id run-ids]- [:in :status ["failed" "abandoned"]]]- task-name (conj [:= :task task-name]))}- :sub]]- :where [:= :sub.rn 1]})+ (->> (notification.db/latest-failed-task-history task-notification-send run-ids task-name)(into {} (map (juxt :run_id (comp :message :task_details)))))))(defn- has-failure?@@ -505,13 +237,12 @@(defn- list-notifications"Single SQL query for the page; one extra query for failed-run error messages on that page."- [{:keys [limit offset] :as filters}]- (let [base-filters (dissoc filters :limit :offset)- page-rows (t2/select :model/Notification- (assoc (list-query base-filters)- :limit limit- :offset offset))- total (or (:count (t2/query-one (count-query base-filters))) 0)+ [{:keys [limit offset recipient_email] :as filters}]+ (let [base-filters (cond-> (-> filters (dissoc :limit :offset :recipient_email))+ recipient_email+ (assoc :recipient_notification_ids (notification-ids-with-recipient-email recipient_email)))+ page-rows (notification.db/admin-notifications-page base-filters limit offset)+ total (or (notification.db/admin-notifications-count base-filters) 0)decorated (-> page-rowsdecorate-runsmodels.notification/hydrate-notification)]@@ -599,14 +330,11 @@"Up to `:result-limit` most-recent terminal alert TaskRuns for `notification-id`, newest first, as`::run-summary` maps. Attributed directly via `task_run.notification_id`."[notification-id & {:keys [result-limit] :or {result-limit 10}}]- (let [runs (t2/select [:model/TaskRun :id :status :started_at]- {:where [:and- [:= :run_type run-type-alert]- [:= :notification_id notification-id]- [:in :status terminal-statuses]- [:> :started_at (lookback-cutoff)]]- :order-by [[:started_at :desc] [:id :desc]]- :limit result-limit})+ (let [runs (notification.db/terminal-alert-runs run-type-alert+ notification-id+ terminal-statuses+ (notification.db/admin-lookback-cutoff)+ result-limit)failed-ids (into #{} (keep (fn [{:keys [id status]}](when (#{:failed :abandoned} status) id))runs))@@ -633,31 +361,17 @@:status (if (some #(= :failing (:status %)) channel-entries) :failing :successful):error (some :error channel-entries):channels channel-entries}))))- (t2/reducible-select :model/TaskHistory- {:select [:th.run_id :th.task_details :th.status- [:tr.started_at :run_started_at]]- :from [[:task_history :th]]- :join [[:task_run :tr] [:= :tr.id :th.run_id]]- :where [:and- [:= :tr.run_type run-type-alert]- [:= :tr.notification_id notification-id]- [:= :th.task task-channel-send]- [:> :tr.started_at (lookback-cutoff)]]- ;; tr.id tie-breaks runs sharing a started_at so partition-by run_id- ;; keeps each run's rows adjacent.- :order-by [[:tr.started_at :desc] [:tr.id :desc]]- ;; safety cap; the (take result-limit) over partition-by run_id- ;; normally closes the cursor first.- :limit 500})))+ (notification.db/channel-send-history-reducible run-type-alert+ notification-id+ task-channel-send+ (notification.db/admin-lookback-cutoff))))(defn- get-notification-detail"Fetch a single card-type notification with `:last_check`, `:last_send`, `:check_history`, and`:send_history`, each attributed to THIS notification via `task_run.notification_id`. Returns nilfor a missing or non-card notification."[id]- (when-let [row (t2/select-one :model/Notification- (-> (base-list-query {:skip-run-joins? true})- (sql.helpers/where [:= :notification.id id])))]+ (when-let [row (notification.db/admin-notification-detail-row id)](let [decorated (-> (models.notification/hydrate-notification [row])firstsplice-creator-active)@@ -698,15 +412,10 @@;; before-update hook checks before permitting a `creator_id` change. (Harmless for the;; archive action, whose update-map never touches creator_id.)(t2/with-transaction [_conn]- (let [before (-> (t2/select :model/Notification- :id [:in ids]- :payload_type :notification/card)+ (let [before (-> (notification.db/card-notifications ids)models.notification/hydrate-notificationvec)]- (t2/update! :model/Notification- :id [:in ids]- :payload_type :notification/card- update-map)+ (notification.db/update-card-notifications! ids update-map)before))))(api.macros/defendpoint :post "/bulk" :- ::bulk-response@@ -724,7 +433,7 @@(api/check-superuser)(let [update-map (action->update-map action creator_id)before (bulk-update! update-map notification_ids)- after (->> (t2/select :model/Notification :id [:in (mapv :id before)])+ after (->> (notification.db/notifications-by-id (mapv :id before))models.notification/hydrate-notification(m/index-by :id))](doseq [b beforediff --git a/src/metabase/notification/api/notification.clj b/src/metabase/notification/api/notification.cljindex ca89752eeb7..e7445686135 100644--- a/src/metabase/notification/api/notification.clj+++ b/src/metabase/notification/api/notification.clj@@ -2,7 +2,6 @@"/api/notification endpoints"(:require[clojure.data :refer [diff]]- [honey.sql.helpers :as sql.helpers][medley.core :as m][metabase.api.common :as api][metabase.api.macros :as api.macros]@@ -13,6 +12,7 @@[metabase.events.core :as events][metabase.models.interface :as mi][metabase.notification.core :as notification]+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.util :as u][metabase.util.malli :as mu]@@ -91,7 +91,7 @@(defn get-notification"Get a notification by id."[id]- (-> (t2/select-one :model/Notification id)+ (-> (notification.db/notification id)api/check-404models.notification/hydrate-notification))@@ -102,52 +102,16 @@(defn list-notifications"List notifications. See `GET /` for parameters."[{:keys [creator_id creator_or_recipient_id recipient_id card_id payload_type include_inactive legacy-active legacy-user-id]}]- (->> (t2/reducible-select :model/Notification- (cond-> {:select-distinct [:notification.*]}- creator_id- (sql.helpers/where [:= :notification.creator_id creator_id])-- recipient_id- (-> (sql.helpers/left-join- :notification_handler [:= :notification_handler.notification_id :notification.id])- (sql.helpers/left-join- :notification_recipient [:= :notification_recipient.notification_handler_id :notification_handler.id])- (sql.helpers/where [:= :notification_recipient.user_id recipient_id]))-- creator_or_recipient_id- (-> (sql.helpers/left-join- :notification_handler [:= :notification_handler.notification_id :notification.id])- (sql.helpers/left-join- :notification_recipient [:= :notification_recipient.notification_handler_id :notification_handler.id])- (sql.helpers/where [:or [:= :notification_recipient.user_id creator_or_recipient_id]- [:= :notification.creator_id creator_or_recipient_id]]))-- card_id- (-> (sql.helpers/left-join- :notification_card- [:and- [:= :notification_card.id :notification.payload_id]- [:= :notification.payload_type "notification/card"]])- (sql.helpers/where [:= :notification_card.card_id card_id]))-- (and (nil? legacy-active) (not (true? include_inactive)))- (sql.helpers/where [:= :notification.active true])-- payload_type- (sql.helpers/where [:= :notification.payload_type (u/qualified-name payload_type)])-- ;; legacy-active and legacy-user-id only used by alert api, will be removed soon- (some? legacy-active)- (sql.helpers/where [:= :notification.active legacy-active])-- legacy-user-id- (-> (sql.helpers/left-join- :notification_handler [:= :notification_handler.notification_id :notification.id])- (sql.helpers/left-join- :notification_recipient [:= :notification_recipient.notification_handler_id :notification_handler.id])- (sql.helpers/where [:or- [:= :notification_recipient.user_id legacy-user-id]- [:= :notification.creator_id legacy-user-id]]))))+ (->> (notification.db/notifications-matching+ {:creator-id creator_id+ :creator-or-recipient-id creator_or_recipient_id+ :recipient-id recipient_id+ :card-id card_id+ :payload-type payload_type+ :include-inactive? include_inactive+ ;; legacy-active and legacy-user-id only used by alert api, will be removed soon+ :legacy-active legacy-active+ :legacy-user-id legacy-user-id})(into [] (comp(map t2.realize/realize)(filter mi/can-read?)))@@ -200,7 +164,7 @@(filter #(#{:notification-recipient/user :notification-recipient/raw-value} ((comp keyword :type) %)))(map (fn [recipient](if (= :notification-recipient/user ((comp keyword :type) recipient))- (or (-> recipient :user :email) (t2/select-one-fn :email :model/User (:user_id recipient)))+ (or (-> recipient :user :email) (notification.db/user-email (:user_id recipient)))(-> recipient :details :value))))(remove nil?)set))@@ -212,7 +176,7 @@(remove current-user?)seq)](messages/send-you-were-added-card-notification-email!- (update notification :payload t2/hydrate :card) recipients-except-creator @api/*current-user*)))))+ (update notification :payload #(t2/hydrate % :card)) recipients-except-creator @api/*current-user*)))))(mu/defn create-notification! :- ::models.notification/FullyHydratedNotification"Create a notification with permission checks, hydration, email notifications, and event publishing."@@ -248,7 +212,7 @@current-user @api/*current-user*old-emails (all-email-recipients existing-notification)new-emails (all-email-recipients updated-notification)- notification (update existing-notification :payload t2/hydrate :card)]+ notification (update existing-notification :payload #(t2/hydrate % :card))](cond;; Notification was just archived - notify all users they were unsubscribed(and was-active? (not is-active?))@@ -364,7 +328,7 @@(when (card-notification? <>)(u/ignore-exceptions(messages/send-you-unsubscribed-notification-card-email!- (update <> :payload t2/hydrate :card)+ (update <> :payload #(t2/hydrate % :card))[(:email @api/*current-user*)])))(events/publish-event! :event/notification-unsubscribe {:object {:id notification-id}:user-id api/*current-user-id*}))))diff --git a/src/metabase/notification/api/unsubscribe.clj b/src/metabase/notification/api/unsubscribe.cljindex b2e4f66f926..57ce94b5f67 100644--- a/src/metabase/notification/api/unsubscribe.clj+++ b/src/metabase/notification/api/unsubscribe.clj@@ -7,6 +7,7 @@[metabase.channel.email.messages :as messages][metabase.config.core :as config][metabase.events.core :as events]+ [metabase.notification.db :as notification.db][metabase.request.core :as request][metabase.util.i18n :refer [tru]][metabase.util.malli.schema :as ms]@@ -26,16 +27,12 @@(defn- notification-name-by-handler-id[notification-handler-id]- (let [notification (t2/hydrate (t2/select-one :model/Notification- :id [:in ^:allow-subquery {:select [:notification_id]- :from :notification_handler- :where [:= :id notification-handler-id]}])- :payload)]+ (let [notification (t2/hydrate (notification.db/notification-for-handler notification-handler-id) :payload)](case (:payload_type notification);; use the card name- :notification/card (->> notification :payload :card_id (t2/select-one-fn :name :model/Card))+ :notification/card (->> notification :payload :card_id notification.db/card-name);; use the dashboard name- :notification/dashboard (->> notification :payload :dashboard_id (t2/select-one-fn :name :model/Dashboard))+ :notification/dashboard (->> notification :payload :dashboard_id notification.db/dashboard-name)(name (:payload_type notification)))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -53,12 +50,10 @@request](check-hash notification-handler-id email hash (request/ip-address request))(t2/with-transaction [_conn]- (let [recipients (t2/select :model/NotificationRecipient- :notification_handler_id notification-handler-id- :type :notification-recipient/raw-value)+ (let [recipients (notification.db/raw-value-recipients-for-handler notification-handler-id)matching-recipient (m/find-first #(= email (-> % :details :value)) recipients)](if matching-recipient- (t2/delete! :model/NotificationRecipient (:id matching-recipient))+ (notification.db/delete-recipient! (:id matching-recipient))(throw (ex-info (tru "Email doesn''t exist.") {:status-code 400})))))(events/publish-event! :event/notification-unsubscribe-ex {:details {:email email}:object {:id notification-handler-id}})@@ -79,13 +74,12 @@request](check-hash notification-handler-id email hash (request/ip-address request))(t2/with-transaction [_conn]- (let [recipients (t2/select :model/NotificationRecipient :notification_handler_id notification-handler-id- :type :notification-recipient/raw-value)+ (let [recipients (notification.db/raw-value-recipients-for-handler notification-handler-id)matching-recipient (m/find-first #(= email (-> % :details :value)) recipients)](if-not matching-recipient- (t2/insert! :model/NotificationRecipient {:type :notification-recipient/raw-value- :details {:value email}- :notification_handler_id notification-handler-id})+ (notification.db/insert-recipients! {:type :notification-recipient/raw-value+ :details {:value email}+ :notification_handler_id notification-handler-id})(throw (ex-info (tru "Email already exist.") {:status-code 400})))))(events/publish-event! :event/notification-unsubscribe-undo-ex {:details {:email email}:object {:id notification-handler-id}})diff --git a/src/metabase/notification/card.clj b/src/metabase/notification/card.cljindex 774f36b54b8..fa4da18f3cf 100644--- a/src/metabase/notification/card.clj+++ b/src/metabase/notification/card.clj@@ -1,14 +1,14 @@(ns metabase.notification.card(:require[metabase.events.core :as events]- [metabase.notification.models :as models.notification]- [toucan2.core :as t2]))+ [metabase.notification.db :as notification.db]+ [metabase.notification.models :as models.notification]))(defn delete-card-notifications-and-notify!"Removes all of the alerts and notifies all of the email recipients of the alerts change."[topic actor card](when-let [card-notifications (seq (models.notification/notifications-for-card (:id card)))]- (t2/delete! :model/Notification :id [:in (map :id card-notifications)])+ (notification.db/delete-notifications! (map :id card-notifications))(events/publish-event! topic {:card card:actor actor:notifications card-notifications})))diff --git a/src/metabase/notification/db.clj b/src/metabase/notification/db.cljnew file mode 100644index 00000000000..b1da9795c2f--- /dev/null+++ b/src/metabase/notification/db.clj@@ -0,0 +1,638 @@+(ns metabase.notification.db+ "Application database queries for the notification module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods,+ and transactions."+ (:require+ [clojure.string :as str]+ [honey.sql.helpers :as sql.helpers]+ [metabase.app-db.core :as mdb]+ [metabase.models.interface :as mi]+ [metabase.util :as u]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++;;; --------------------------------------------- Notification ---------------------------------------------++(defn notification+ "The Notification with `notification-id`, or nil."+ [notification-id]+ (t2/select-one :model/Notification notification-id))++(defn notification-by-internal-id+ "The seeded Notification with `internal-id`, or nil."+ [internal-id]+ (t2/select-one :model/Notification :internal_id internal-id))++(defn notification-for-handler+ "The Notification owning the NotificationHandler with `handler-id`, or nil."+ [handler-id]+ (t2/select-one :model/Notification+ :id [:in ^:allow-subquery {:select [:notification_id]+ :from :notification_handler+ :where [:= :id handler-id]}]))++(defn notifications-matching+ "Reducible Notifications, optionally narrowed to `creator-id`, `creator-or-recipient-id` (a User who is either the+ creator or a recipient), `recipient-id`, `card-id`, and `payload-type`; active Notifications only unless+ `include-inactive?` or `legacy-active` (a boolean, overriding both) is given. `legacy-user-id` narrows to a User+ who is either the creator or a recipient."+ [{:keys [creator-id creator-or-recipient-id recipient-id card-id payload-type include-inactive? legacy-active+ legacy-user-id]}]+ (t2/reducible-select+ :model/Notification+ (cond-> {:select-distinct [:notification.*]}+ creator-id+ (sql.helpers/where [:= :notification.creator_id creator-id])++ recipient-id+ (-> (sql.helpers/left-join+ :notification_handler [:= :notification_handler.notification_id :notification.id])+ (sql.helpers/left-join+ :notification_recipient [:= :notification_recipient.notification_handler_id :notification_handler.id])+ (sql.helpers/where [:= :notification_recipient.user_id recipient-id]))++ creator-or-recipient-id+ (-> (sql.helpers/left-join+ :notification_handler [:= :notification_handler.notification_id :notification.id])+ (sql.helpers/left-join+ :notification_recipient [:= :notification_recipient.notification_handler_id :notification_handler.id])+ (sql.helpers/where [:or [:= :notification_recipient.user_id creator-or-recipient-id]+ [:= :notification.creator_id creator-or-recipient-id]]))++ card-id+ (-> (sql.helpers/left-join+ :notification_card+ [:and+ [:= :notification_card.id :notification.payload_id]+ [:= :notification.payload_type "notification/card"]])+ (sql.helpers/where [:= :notification_card.card_id card-id]))++ (and (nil? legacy-active) (not (true? include-inactive?)))+ (sql.helpers/where [:= :notification.active true])++ payload-type+ (sql.helpers/where [:= :notification.payload_type (u/qualified-name payload-type)])++ (some? legacy-active)+ (sql.helpers/where [:= :notification.active legacy-active])++ legacy-user-id+ (-> (sql.helpers/left-join+ :notification_handler [:= :notification_handler.notification_id :notification.id])+ (sql.helpers/left-join+ :notification_recipient [:= :notification_recipient.notification_handler_id :notification_handler.id])+ (sql.helpers/where [:or+ [:= :notification_recipient.user_id legacy-user-id]+ [:= :notification.creator_id legacy-user-id]])))))++(defn notifications-by-id+ "The Notifications with `notification-ids`."+ [notification-ids]+ (t2/select :model/Notification :id [:in notification-ids]))++(defn card-notifications+ "The card Notifications among `notification-ids`."+ [notification-ids]+ (t2/select :model/Notification :id [:in notification-ids] :payload_type :notification/card))++(defn active-card-notifications-for-card+ "The active card Notifications attached to the Card with `card-id`."+ [card-id]+ (t2/select :model/Notification+ :active true+ :payload_type :notification/card+ :payload_id [:in ^:allow-subquery {:select [:id]+ :from [:notification_card]+ :where [:= :card_id card-id]}]))++(defn active-system-event-notifications+ "The active Notifications subscribed to the system event named `event-name`."+ [event-name]+ (t2/select :model/Notification+ {:select [:n.*]+ :from [[:notification :n]]+ :left-join [[:notification_subscription :ns] [:= :n.id :ns.notification_id]]+ :where [:and+ [:= :n.active true]+ [:= :ns.event_name event-name]+ [:= :ns.type "notification-subscription/system-event"]]}))++(defn insert-notification!+ "Insert `notification` and return the new instance."+ [notification]+ (t2/insert-returning-instance! :model/Notification notification))++(defn update-card-notifications!+ "Apply `changes` to the card Notifications among `notification-ids`."+ [notification-ids changes]+ (t2/update! :model/Notification :id [:in notification-ids] :payload_type :notification/card changes))++(defn deactivate-notification!+ "Mark the Notification with `notification-id` inactive."+ [notification-id]+ (t2/update! :model/Notification notification-id {:active false}))++(defn delete-notification!+ "Delete the Notification with `notification-id`."+ [notification-id]+ (t2/delete! :model/Notification notification-id))++(defn delete-notifications!+ "Delete the Notifications with `notification-ids`."+ [notification-ids]+ (t2/delete! :model/Notification :id [:in notification-ids]))++(defn delete-notification-by-internal-id!+ "Delete the seeded Notification with `internal-id`."+ [internal-id]+ (t2/delete! :model/Notification :internal_id internal-id))++;;; ------------------------------------------- NotificationCard -------------------------------------------++(defn notification-cards+ "The NotificationCards with `notification-card-ids`."+ [notification-card-ids]+ (t2/select :model/NotificationCard :id [:in notification-card-ids]))++(defn notification-card-exists?+ "Whether a NotificationCard with `notification-card-id` exists."+ [notification-card-id]+ (t2/exists? :model/NotificationCard notification-card-id))++(defn notification-card-card-id+ "The `:card_id` of the NotificationCard with `notification-card-id`."+ [notification-card-id]+ (t2/select-one-fn :card_id :model/NotificationCard :id notification-card-id))++(defn insert-notification-card!+ "Insert `notification-card` and return its ID."+ [notification-card]+ (t2/insert-returning-pk! :model/NotificationCard notification-card))++(defn delete-notification-card!+ "Delete the NotificationCard with `notification-card-id`."+ [notification-card-id]+ (t2/delete! :model/NotificationCard notification-card-id))++;;; --------------------------------------- NotificationSubscription ---------------------------------------++(defn subscription+ "The NotificationSubscription with `subscription-id`, or nil."+ [subscription-id]+ (t2/select-one :model/NotificationSubscription subscription-id))++(defn subscriptions-for-notifications+ "The NotificationSubscriptions of the Notifications with `notification-ids`."+ [notification-ids]+ (t2/select :model/NotificationSubscription :notification_id [:in notification-ids]))++(defn cron-subscriptions-for-notification+ "The cron NotificationSubscriptions of the Notification with `notification-id`."+ [notification-id]+ (t2/select :model/NotificationSubscription+ :notification_id notification-id+ :type :notification-subscription/cron))++(defn cron-subscription-ids-for-notification+ "The IDs of the cron NotificationSubscriptions of the Notification with `notification-id`."+ [notification-id]+ (t2/select-pks-set :model/NotificationSubscription+ :notification_id notification-id+ :type :notification-subscription/cron))++(defn active-cron-subscriptions-by-id+ "A map of ID to cron NotificationSubscription for every active Notification."+ []+ (t2/select-pk->fn identity :model/NotificationSubscription+ :type :notification-subscription/cron+ {:select [:ns.*]+ :from [[:notification_subscription :ns]]+ :join [[:notification :n] [:= :ns.notification_id :n.id]]+ :where [:and+ [:= :ns.type "notification-subscription/cron"]+ [:= :n.active true]]}))++(defn insert-subscriptions!+ "Insert the NotificationSubscription `subscriptions`."+ [subscriptions]+ (t2/insert! :model/NotificationSubscription subscriptions))++;;; ------------------------------------ NotificationHandler / Recipient ------------------------------------++(defn handlers-for-notifications+ "The NotificationHandlers of the Notifications with `notification-ids`."+ [notification-ids]+ (t2/select :model/NotificationHandler :notification_id [:in notification-ids]))++(defn handler-notification-ids-for-email+ "The set of Notification IDs of the handlers whose recipients (joined to their user) have an exact, lower-cased+ `email` match, either directly (via the recipient's User) or among `raw-value-handler-ids` (handler IDs already+ known to have a matching raw-value recipient)."+ [lower-email raw-value-handler-ids]+ (let [user-clause [:and+ [:= :nr.type "notification-recipient/user"]+ [:= [:lower :cu.email] lower-email]]]+ (t2/select-fn-set :notification_id (t2/table-name :model/NotificationHandler)+ {:join [[(t2/table-name :model/NotificationRecipient) :nr]+ [:= :nr.notification_handler_id :notification_handler.id]]+ :left-join [[:core_user :cu] [:= :cu.id :nr.user_id]]+ :where (if (seq raw-value-handler-ids)+ [:or user-clause [:in :notification_handler.id raw-value-handler-ids]]+ user-clause)})))++(defn insert-handler!+ "Insert `handler` and return its ID."+ [handler]+ (t2/insert-returning-pk! :model/NotificationHandler handler))++(defn recipients-for-handlers+ "The NotificationRecipients of the NotificationHandlers with `handler-ids`."+ [handler-ids]+ (t2/select :model/NotificationRecipient :notification_handler_id [:in handler-ids]))++(defn raw-value-recipients-for-handler+ "The raw-value NotificationRecipients of the NotificationHandler with `handler-id`."+ [handler-id]+ (t2/select :model/NotificationRecipient+ :notification_handler_id handler-id+ :type :notification-recipient/raw-value))++(defn raw-value-recipients-reducible+ "Reducible handler IDs and details of every raw-value NotificationRecipient."+ []+ (t2/reducible-select [:model/NotificationRecipient :notification_handler_id :details]+ :type :notification-recipient/raw-value))++(defn insert-recipients!+ "Insert one NotificationRecipient map or a sequence of them."+ [recipients]+ (t2/insert! :model/NotificationRecipient recipients))++(defn delete-recipient!+ "Delete the NotificationRecipient with `recipient-id`."+ [recipient-id]+ (t2/delete! :model/NotificationRecipient recipient-id))++(defn delete-user-recipients-for-notification!+ "Delete the NotificationRecipients for the User with `user-id` on the Notification with `notification-id`."+ [notification-id user-id]+ (t2/delete! :model/NotificationRecipient+ :user_id user-id+ :notification_handler_id [:in ^:allow-subquery {:select [:id]+ :from [:notification_handler]+ :where [:= :notification_id notification-id]}]))++;;; ---------------------------------------------- Channels ----------------------------------------------++(defn active-channels-by-id+ "A map of ID to active Channel for `channel-ids`."+ [channel-ids]+ (t2/select-fn->fn :id identity :model/Channel :id [:in channel-ids] :active true))++(defn channel-templates-by-id+ "A map of ID to ChannelTemplate for `template-ids`."+ [template-ids]+ (t2/select-fn->fn :id identity :model/ChannelTemplate :id [:in template-ids]))++(defn channel-template-channel-type+ "The `:channel_type` of the ChannelTemplate with `template-id`."+ [template-id]+ (t2/select-one-fn :channel_type [:model/ChannelTemplate :channel_type] template-id))++(defn insert-channel-template!+ "Insert `template` and return its ID."+ [template]+ (t2/insert-returning-pk! :model/ChannelTemplate template))++(defn delete-channel-templates!+ "Delete the ChannelTemplates with `template-ids`."+ [template-ids]+ (t2/delete! :model/ChannelTemplate :id [:in template-ids]))++;;; ---------------------------------------------- Task runs ----------------------------------------------++(defn terminal-alert-runs+ "Up to `limit` TaskRuns of `run-type` for the Notification with `notification-id` that reached one of `statuses`+ after `cutoff`, newest first."+ [run-type notification-id statuses cutoff limit]+ (t2/select [:model/TaskRun :id :status :started_at]+ {:where [:and+ [:= :run_type run-type]+ [:= :notification_id notification-id]+ [:in :status statuses]+ [:> :started_at cutoff]]+ :order-by [[:started_at :desc] [:id :desc]]+ :limit limit}))++(defn channel-send-history-reducible+ "Reducible TaskHistory rows of `task` for the runs of `run-type` for the Notification with `notification-id`+ started after `cutoff`, newest run first with `tr.id` as the tiebreaker so each run's rows stay adjacent, capped+ at 500 rows."+ [run-type notification-id task cutoff]+ (t2/reducible-select :model/TaskHistory+ {:select [:th.run_id :th.task_details :th.status+ [:tr.started_at :run_started_at]]+ :from [[:task_history :th]]+ :join [[:task_run :tr] [:= :tr.id :th.run_id]]+ :where [:and+ [:= :tr.run_type run-type]+ [:= :tr.notification_id notification-id]+ [:= :th.task task]+ [:> :tr.started_at cutoff]]+ :order-by [[:tr.started_at :desc] [:tr.id :desc]]+ :limit 500}))++(defn latest-failed-task-history+ "The `:run_id` and `:task_details` of the single failed/abandoned TaskHistory row per run among `run-ids` (and, if+ given, restricted to `task-name`), preferring rows of `preferred-task` and then the latest by `ended_at`."+ [preferred-task run-ids task-name]+ (t2/select :model/TaskHistory+ {:select [:run_id :task_details]+ :from [[^:allow-subquery+ {:select [:run_id :task_details+ [[:over [[:row_number]+ ^:allow-subquery+ {:partition-by [:run_id]+ :order-by [[[:case+ [:= :task preferred-task] 0+ :else 1] :asc]+ [:ended_at :desc]]}]]+ :rn]]+ :from [:task_history]+ :where [:and+ [:in :run_id run-ids]+ [:in :status ["failed" "abandoned"]]+ (when task-name [:= :task task-name])]}+ :sub]]+ :where [:= :sub.rn 1]}))++;;; --------------------------------------------- Admin listing ---------------------------------------------++(def ^:private admin-run-type-alert "alert")+(def ^:private admin-task-channel-send "channel-send")+(def ^:private admin-terminal-statuses ["success" "failed" "abandoned"])++(def ^:private admin-run-lookback-days+ "How far back to consider alert-type TaskRuns / TaskHistory rows when computing run summaries."+ 90)++(defn admin-lookback-cutoff+ "The earliest `started_at` considered for the admin notification list/detail run history:+ [[admin-run-lookback-days]] days before now."+ []+ (h2x/add-interval-honeysql-form (mdb/db-type) (mi/now) (- admin-run-lookback-days) :day))++(defn- latest-run-per-notification+ [lookback]+ ^:allow-subquery+ {:select [:id :notification_id :status :started_at :ended_at]+ :from [[^:allow-subquery+ {:select [:id :notification_id :status :started_at :ended_at+ [[:over [[:row_number]+ ^:allow-subquery+ {:partition-by [:notification_id]+ :order-by [[:started_at :desc]]}]]+ :rn]]+ :from [:task_run]+ :where [:and+ [:= :run_type admin-run-type-alert]+ [:is-not :notification_id nil]+ [:in :status admin-terminal-statuses]+ [:> :started_at lookback]]}+ :sub]]+ :where [:= :sub.rn 1]})++(defn- latest-send-tick-per-notification+ [lookback]+ ^:allow-subquery+ {:select [:lr.notification_id+ [:lr.run_id :id]+ [:lr.tick_started_at :started_at]+ [[:case+ [:exists ^:allow-subquery+ {:select [[1]]+ :from [[:task_history :tf]]+ :where [:and+ [:= :tf.run_id :lr.run_id]+ [:= :tf.task admin-task-channel-send]+ [:= :tf.status "failed"]]}]+ true+ :else false]+ :has_failure]]+ :from [[^:allow-subquery+ {:select [:tr2.notification_id+ [:tr2.id :run_id]+ [:tr2.started_at :tick_started_at]+ [[:over [[:row_number]+ ^:allow-subquery+ {:partition-by [:tr2.notification_id]+ :order-by [[:tr2.started_at :desc]]}]]+ :rn]]+ :from [[:task_run :tr2]]+ :where [:and+ [:= :tr2.run_type admin-run-type-alert]+ [:is-not :tr2.notification_id nil]+ [:in :tr2.status admin-terminal-statuses]+ [:> :tr2.started_at lookback]+ [:exists ^:allow-subquery+ {:select [[1]]+ :from [[:task_history :tx]]+ :where [:and+ [:= :tx.run_id :tr2.id]+ [:= :tx.task admin-task-channel-send]]}]]}+ :lr]]+ :where [:= :lr.rn 1]})++(def ^:private admin-sort-column->order-by+ "Maps the public `sort_column` enum to the SQL expression used in `ORDER BY`. Uses raw expressions rather than the+ SELECT aliases because H2 does not resolve aliases inside expressions."+ {:id :notification.id+ :last_send :ls.started_at+ :last_check :lc.started_at+ :card_name :c.name+ :creator_name [:coalesce :cu.last_name :cu.first_name :cu.email]+ :updated_at :notification.updated_at})++(defn- admin-channel-exists+ [channels]+ (let [channels (if (sequential? channels) channels [channels])]+ [:exists+ ^:allow-subquery+ {:select [[1]]+ :from [(t2/table-name :model/NotificationHandler)]+ :where [:and+ [:= :notification_handler.notification_id :notification.id]+ [:in :notification_handler.channel_type channels]]}]))++(defn- admin-query-where-clause+ [query]+ (let [wildcard (h2x/like-substring query)]+ [:or+ [:like [:lower :c.name] wildcard]+ [:like [:lower :cu.first_name] wildcard]+ [:like [:lower :cu.last_name] wildcard]+ [:like [:lower :cu.email] wildcard]]))++(defn- admin-list-where-clauses+ [{:keys [active creator_id creator_active creatorless card_id recipient_notification_ids channel+ last_send_status last_check_status query]}]+ (keep+ identity+ [(when (some? active) [:= :notification.active active])+ (when (some? creator_active) [:= :cu.is_active creator_active])+ (when (true? creatorless)+ [:or [:= :notification.creator_id nil] [:= :cu.is_active false]])+ (when (false? creatorless)+ [:and [:is-not :notification.creator_id nil] [:= :cu.is_active true]])+ (when creator_id [:= :notification.creator_id creator_id])+ (when card_id [:= :nc.card_id card_id])+ (when (seq channel) (admin-channel-exists channel))+ (when last_send_status+ (case last_send_status+ :successful [:= :ls.has_failure false]+ :failing [:= :ls.has_failure true]))+ (when last_check_status+ (case last_check_status+ :successful [:= :lc.status "success"]+ :failing [:in :lc.status ["failed" "abandoned"]]))+ ;; recipient_notification_ids is nil when no recipient_email filter was given, and an empty set when a+ ;; recipient_email filter matched nobody -- in which case the page must come back empty.+ (when recipient_notification_ids+ (if (seq recipient_notification_ids)+ [:in :notification.id recipient_notification_ids]+ [:= 1 0]))+ (when-not (str/blank? query) (admin-query-where-clause query))]))++(defn- admin-base-list-query+ [{:keys [skip-run-joins?] :as filters}]+ (let [lookback (admin-lookback-cutoff)]+ (reduce+ sql.helpers/where+ (cond-> {:select (cond-> [:notification.id+ :notification.active+ :notification.creator_id+ :notification.created_at+ :notification.updated_at+ :notification.payload_type+ :notification.payload_id+ [:c.name :card_name]+ [:cu.is_active :creator_is_active]+ [[:coalesce :cu.last_name :cu.first_name :cu.email] :creator_name]]+ (not skip-run-joins?)+ (into [[:lc.id :lc_id]+ [:lc.status :lc_status]+ [:lc.started_at :lc_started_at]+ [:ls.id :ls_id]+ [:ls.started_at :ls_started_at]+ [:ls.has_failure :ls_has_failure]]))+ :from [:notification]+ :where [:and+ [:= :notification.payload_type "notification/card"]+ [:is-not :notification.payload_id nil]]}++ true+ (-> (sql.helpers/left-join [:notification_card :nc] [:= :nc.id :notification.payload_id])+ (sql.helpers/left-join [:report_card :c] [:= :c.id :nc.card_id])+ (sql.helpers/left-join [:core_user :cu] [:= :cu.id :notification.creator_id]))++ (not skip-run-joins?)+ (-> (sql.helpers/left-join [(latest-run-per-notification lookback) :lc] [:= :lc.notification_id :notification.id])+ (sql.helpers/left-join [(latest-send-tick-per-notification lookback) :ls] [:= :ls.notification_id :notification.id])))+ (admin-list-where-clauses filters))))++(defn- admin-order-by-clauses+ [sort-column sort-direction]+ (let [col (admin-sort-column->order-by sort-column)+ dir (or sort-direction :desc)]+ [[[:case [:= col nil] 1 :else 0] :asc]+ [col dir]+ [:notification.id :desc]]))++(defn- admin-list-query+ [{:keys [sort_column sort_direction] :as filters}]+ (assoc (admin-base-list-query (dissoc filters :sort_column :sort_direction))+ :order-by (admin-order-by-clauses (or sort_column :last_send) sort_direction)))++(defn admin-notifications-page+ "A page (`limit`/`offset`) of admin notification-list rows matching `filters` (see+ [[metabase.notification.api.admin]] for the supported keys), most-relevant first per `:sort_column`/+ `:sort_direction`."+ [filters limit offset]+ (t2/select :model/Notification (assoc (admin-list-query filters) :limit limit :offset offset)))++(defn admin-notifications-count+ "The number of admin notification-list rows matching `filters`."+ [filters]+ (:count (t2/query-one (-> (admin-list-query filters)+ (assoc :select [[[:count :notification.id] :count]])+ (dissoc :order-by)))))++(defn admin-notification-detail-row+ "The admin notification-list row (skipping the run-summary joins) for the Notification with `notification-id`, or+ nil."+ [notification-id]+ (t2/select-one :model/Notification+ (-> (admin-base-list-query {:skip-run-joins? true})+ (sql.helpers/where [:= :notification.id notification-id]))))++;;; ------------------------------------------- Other models -------------------------------------------++(defn instance+ "The instance of `model` with `id`, or nil."+ [model id]+ (t2/select-one model id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card card-id))++(defn unarchived-card+ "The Card with `card-id` if it is not archived, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id :archived false))++(defn card-name+ "The name of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :name :model/Card card-id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard dashboard-id))++(defn dashboard-name+ "The name of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-one-fn :name :model/Dashboard dashboard-id))++(defn dashboard-tabs+ "The DashboardTabs of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardTab :dashboard_id dashboard-id))++(defn dashboard-tab-count+ "The number of DashboardTabs on the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/count :model/DashboardTab :dashboard_id dashboard-id))++(defn dashcards-for-dashboard+ "The DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id))++(defn user-email+ "The email of the User with `user-id`."+ [user-id]+ (t2/select-one-fn :email [:model/User :email] user-id))++(defn user-summary+ "The ID, names, and email of the User with `user-id`."+ [user-id]+ (t2/select-one [:model/User :id :first_name :last_name :email] user-id))++(defn active-users-by-id+ "A map of ID to active User for `user-ids`."+ [user-ids]+ (t2/select-fn->fn :id identity :model/User :id [:in user-ids] :is_active true))diff --git a/src/metabase/notification/events/notification.clj b/src/metabase/notification/events/notification.cljindex 7b2e0be56c8..63d60fb3017 100644--- a/src/metabase/notification/events/notification.clj+++ b/src/metabase/notification/events/notification.clj@@ -3,12 +3,12 @@[malli.core :as mc][malli.transform :as mtx][metabase.events.core :as events]+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.notification.send :as notification.send][metabase.task-history.core :as task-history][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(events/derive! :metabase/event ::notification)@@ -33,7 +33,7 @@(if (map? x)(reduce-kv(fn [acc k {:keys [key model] :as _hydrate-prop}]- (assoc acc key (t2/select-one model (get x k))))+ (assoc acc key (notification.db/instance model (get x k))))xhydrates)x)))))}}}))diff --git a/src/metabase/notification/models.clj b/src/metabase/notification/models.cljindex 0c56f421a6e..eb7cbbc453f 100644--- a/src/metabase/notification/models.clj+++ b/src/metabase/notification/models.clj@@ -10,6 +10,7 @@[metabase.lib.schema.common :as lib.schema.common][metabase.models.interface :as mi][metabase.models.util.spec-update :as models.u.spec-update]+ [metabase.notification.db :as notification.db][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.util :as u]@@ -63,7 +64,7 @@(mi/instances-with-hydrated-datanotifications k#(group-by :notification_id- (t2/select :model/NotificationSubscription :notification_id [:in (map :id notifications)]))+ (notification.db/subscriptions-for-notifications (map :id notifications))):id{:default []}))@@ -77,10 +78,7 @@(for [[payload-type payload-ids] payload-type->ids](case payload-type:notification/card- (let [notification-cards (t2/hydrate- (t2/select :model/NotificationCard- :id [:in payload-ids])- :card)]+ (let [notification-cards (t2/hydrate (notification.db/notification-cards payload-ids) :card)](into {} (for [nc notification-cards][[:notification/card (:id nc)] nc]))){[payload-type nil] nil})))]@@ -95,7 +93,7 @@(mi/instances-with-hydrated-datanotifications k#(group-by :notification_id- (t2/select :model/NotificationHandler :notification_id [:in (map :id notifications)]))+ (notification.db/handlers-for-notifications (map :id notifications))):id{:default []}))@@ -153,9 +151,7 @@{:status-code 400:changes changes}))))(when (contains? (t2/changes instance) :active)- (let [subscriptions (t2/select :model/NotificationSubscription- :notification_id (:id instance)- :type :notification-subscription/cron)]+ (let [subscriptions (notification.db/cron-subscriptions-for-notification (:id instance))](doseq [subscription subscriptions](if (:active instance)(update-subscription-trigger! subscription)@@ -164,15 +160,11 @@(t2/define-before-delete :model/Notification[instance]- (doseq [subscription-id (t2/select-pks-set :model/NotificationSubscription- :notification_id (:id instance)- :type :notification-subscription/cron)]+ (doseq [subscription-id (notification.db/cron-subscription-ids-for-notification (:id instance))](delete-trigger-for-subscription! subscription-id))(when-let [payload-id (:payload_id instance)]- (t2/delete! (case (:payload_type instance)- :notification/card- :model/NotificationCard)- payload-id))+ (case (:payload_type instance)+ :notification/card (notification.db/delete-notification-card! payload-id)))instance);; ------------------------------------------------------------------------------------------------;;@@ -259,9 +251,7 @@(mi/instances-with-hydrated-datanotification-handlers k#(when-let [channel-ids (seq (keep :channel_id notification-handlers))]- (t2/select-fn->fn :id identity :model/Channel- :id [:in channel-ids]- :active true))+ (notification.db/active-channels-by-id channel-ids)):channel_id{:default nil}))@@ -271,8 +261,7 @@(mi/instances-with-hydrated-datanotification-handlers k#(when-let [template-ids (seq (keep :template_id notification-handlers))]- (t2/select-fn->fn :id identity :model/ChannelTemplate- :id [:in template-ids]))+ (notification.db/channel-templates-by-id template-ids)):template_id{:default nil}))@@ -283,8 +272,7 @@notification-handlersk#(group-by :notification_handler_id- (t2/select :model/NotificationRecipient- :notification_handler_id [:in (map :id notification-handlers)]))+ (notification.db/recipients-for-handlers (map :id notification-handlers))):id{:default []}))@@ -297,9 +285,7 @@(m/update-existing :notification-recipient/user(fn [recipients](let [id->user (when (seq recipients)- (t2/select-fn->fn :id identity :model/User- :id [:in (map :user_id recipients)]- :is_active true))]+ (notification.db/active-users-by-id (map :user_id recipients)))](mapv #(assoc % :user (id->user (:user_id %))) recipients))))(m/update-existing :notification-recipient/group(fn [recipients]@@ -311,7 +297,7 @@[notification-handler](when-let [template-id (:template_id notification-handler)](let [channel-type (keyword (:channel_type notification-handler))- template-type (t2/select-one-fn :channel_type [:model/ChannelTemplate :channel_type] template-id)]+ template-type (notification.db/channel-template-channel-type template-id)](when (not= channel-type template-type)(throw (ex-info "Channel type and template type mismatch"{:status 400@@ -578,7 +564,7 @@(current-user-is-creator? notification)(current-user-is-recipient? notification)))([_ pk]- (mi/can-read? (t2/select-one :model/Notification pk))))+ (mi/can-read? (notification.db/notification pk))))(defmethod mi/can-create? :model/Notification[_ notification]@@ -618,7 +604,7 @@(perms/current-user-has-application-permissions? :subscription))(current-user-can-read-payload? notification))))([_model pk]- (mi/can-write? (t2/select-one :model/Notification pk))))+ (mi/can-write? (notification.db/notification pk))));; ------------------------------------------------------------------------------------------------;;;; Public APIs ;;@@ -665,33 +651,17 @@(mu/defn hydrate-notification :- [:or ::FullyHydratedNotification [:sequential ::FullyHydratedNotification]]"Fully hydrate notifictitons."[notification-or-notifications]- (t2/hydrate notification-or-notifications- :creator- :payload- :subscriptions- [:handlers :channel :template [:recipients :recipients-detail]]))+ (t2/hydrate notification-or-notifications :creator :payload :subscriptions [:handlers :channel :template [:recipients :recipients-detail]]))(mu/defn notifications-for-card :- [:sequential ::FullyHydratedNotification]"Find all active card notifications for a given card-id."[card-id :- pos-int?]- (hydrate-notification (t2/select :model/Notification- :active true- :payload_type :notification/card- :payload_id [:in ^:allow-subquery {:select [:id]- :from [:notification_card]- :where [:= :card_id card-id]}])))+ (hydrate-notification (notification.db/active-card-notifications-for-card card-id)))(defn notifications-for-event"Find all active notifications for a given event."[event-name]- (t2/select :model/Notification- {:select [:n.*]- :from [[:notification :n]]- :left-join [[:notification_subscription :ns] [:= :n.id :ns.notification_id]]- :where [:and- [:= :n.active true]- [:= :ns.event_name (u/qualified-name event-name)]- [:= :ns.type (u/qualified-name :notification-subscription/system-event)]]}))+ (notification.db/active-system-event-notifications (u/qualified-name event-name)))(defn create-notification!"Create a new notification with `subsciptions`.@@ -703,27 +673,27 @@(:notification/system-event :notification/testing)nil:notification/card- (t2/insert-returning-pk! :model/NotificationCard (:payload notification)))+ (notification.db/insert-notification-card! (:payload notification)))notification (-> notification(assoc :payload_id payload-id)(dissoc :payload))- instance (t2/insert-returning-instance! :model/Notification notification)+ instance (notification.db/insert-notification! notification)notification-id (:id instance)](when (seq subscriptions)- (t2/insert! :model/NotificationSubscription (map #(assoc % :notification_id notification-id) subscriptions)))+ (notification.db/insert-subscriptions! (map #(assoc % :notification_id notification-id) subscriptions)))(doseq [{:keys [recipients template] :as handler} handlers+recipients];; assert can either template_id exists, then template but be nil, and vice versa(when (and template (not (map? template)))(throw (ex-info "Channel template must be a map" {:status-code 400})))(let [template-id (if template- (t2/insert-returning-pk! :model/ChannelTemplate template)+ (notification.db/insert-channel-template! template)(:template_id handler))handler (-> handler(dissoc :recipients :template)(assoc :notification_id notification-id:template_id template-id))- handler-id (t2/insert-returning-pk! :model/NotificationHandler handler)]- (t2/insert! :model/NotificationRecipient (map #(assoc % :notification_handler_id handler-id) recipients))))+ handler-id (notification.db/insert-handler! handler)]+ (notification.db/insert-recipients! (map #(assoc % :notification_handler_id handler-id) recipients))))instance)))(defn update-notification!@@ -735,8 +705,4 @@(defn unsubscribe-user!"Unsubscribe a user from a notification."[notification-id user-id]- (t2/delete! :model/NotificationRecipient- :user_id user-id- :notification_handler_id [:in ^:allow-subquery {:select [:id]- :from [:notification_handler]- :where [:= :notification_id notification-id]}]))+ (notification.db/delete-user-recipients-for-notification! notification-id user-id))diff --git a/src/metabase/notification/payload/core.clj b/src/metabase/notification/payload/core.cljindex 6b01880f6de..f4b862a9a4a 100644--- a/src/metabase/notification/payload/core.clj+++ b/src/metabase/notification/payload/core.clj@@ -2,6 +2,7 @@(:require[clojure.walk :as w][metabase.appearance.core :as appearance]+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.notification.payload.execute :as notification.payload.execute][metabase.notification.payload.temp-storage :as notification.payload.temp-storage]@@ -10,8 +11,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]- [potemkin :as p]- [toucan2.core :as t2]))+ [potemkin :as p]))(p/import-vars[notification.payload.execute@@ -149,7 +149,7 @@"Realize notification-info with :context and :payload."[notification :- ::Notification](assoc (select-keys notification [:payload_type :creator_id])- :creator (t2/select-one [:model/User :id :first_name :last_name :email] (:creator_id notification))+ :creator (notification.db/user-summary (:creator_id notification)):payload (w/prewalk (fn [x](if (and (map? x) (:lib/metadata x))(dissoc x :lib/metadata)diff --git a/src/metabase/notification/payload/execute.clj b/src/metabase/notification/payload/execute.cljindex a089fbfabdf..1eee37a838e 100644--- a/src/metabase/notification/payload/execute.clj+++ b/src/metabase/notification/payload/execute.clj@@ -6,8 +6,8 @@[metabase.channel.urls :as urls][metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.models.interface :as mi]- [metabase.models.serialization :as serdes][metabase.models.visualization-settings :as viz-settings]+ [metabase.notification.db :as notification.db][metabase.notification.payload.temp-storage :as notification.temp-storage][metabase.parameters.shared :as shared.params][metabase.query-processor.card :as qp.card]@@ -41,7 +41,7 @@"Check if a dashboard has more than 1 tab, and thus needs them to be rendered.We don't need to render the tab title if only 1 exists (issue #45123)."[dashboard-or-id]- (< 1 (t2/count :model/DashboardTab :dashboard_id (u/the-id dashboard-or-id))))+ (< 1 (notification.db/dashboard-tab-count (u/the-id dashboard-or-id))))(defn virtual-card-of-type?"Check if dashcard is a virtual with type `ttype`, if `true` returns the dashcard, else returns `nil`.@@ -104,9 +104,7 @@;; the info in viz-settings might be out-of-date(some? (:entity link-card))(let [{:keys [model id]} (:entity link-card)- instance (t2/select-one- (serdes/link-card-model->toucan-model model)- (dashboard-card/link-card-info-query-for-model model id))]+ instance (dashboard-card/link-card-entity model id)](when (mi/can-read? instance)(link-card->text-part (assoc link-card :entity instance))))))(catch Throwable e@@ -199,13 +197,13 @@:or {spill-budget (new-spill-budget)}}](log/with-context {:card_id card_id}(try- (when-let [card (t2/select-one :model/Card :id card_id :archived false)]- (let [dashboard (t2/select-one :model/Dashboard :id dashboard_id)+ (when-let [card (notification.db/unarchived-card card_id)]+ (let [dashboard (notification.db/dashboard dashboard_id)multi-cards (dashboard-card/dashcard->multi-cards dashcard)result-fn (fn [card-id](let [card (if (= card-id (:id card))card- (t2/select-one :model/Card :id card-id))+ (notification.db/card card-id))attached-result? (and attached? (= card-id card_id))]{:card card:dashcard dashcard@@ -343,7 +341,7 @@only-card-ids (filter #(contains? only-card-ids (:card_id %)))))](request/with-current-user user-id(if (render-tabs? dashboard-id)- (let [tabs (t2/hydrate (t2/select :model/DashboardTab :dashboard_id dashboard-id) :tab-cards)+ (let [tabs (t2/hydrate (notification.db/dashboard-tabs dashboard-id) :tab-cards)tabs-with-cards (->> tabs(map #(update % :cards keep-dashcards))(filter #(seq (:cards %))))@@ -355,7 +353,7 @@(when should-render-tab?[(tab->part tab)])(dashcards->part cards parameters opts)))))))- (let [dashcards (keep-dashcards (t2/select :model/DashboardCard :dashboard_id dashboard-id))]+ (let [dashcards (keep-dashcards (notification.db/dashcards-for-dashboard dashboard-id))](log/debugf "Rendering dashboard with %d cards" (count dashcards))(dashcards->part dashcards parameters opts)))))))@@ -363,7 +361,7 @@"Returns the result for a card."[creator-id :- pos-int?card-id :- pos-int?]- (let [card (t2/select-one :model/Card card-id)+ (let [card (notification.db/card card-id)result (request/with-current-user creator-id(-> (qp.card/process-query-for-card card :api;; TODO rename to :notification?diff --git a/src/metabase/notification/payload/impl/card.clj b/src/metabase/notification/payload/impl/card.cljindex f864dc53413..1a66cfc9738 100644--- a/src/metabase/notification/payload/impl/card.clj+++ b/src/metabase/notification/payload/impl/card.clj@@ -2,6 +2,7 @@(:require[metabase.channel.render.core :as channel.render][metabase.events.core :as events]+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.notification.payload.core :as notification.payload][metabase.notification.payload.execute :as notification.execute]@@ -9,8 +10,7 @@[metabase.notification.send :as notification.send][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.ui-logic :as ui-logic]- [toucan2.core :as t2]))+ [metabase.util.ui-logic :as ui-logic]))(mu/defmethod notification.payload/payload :notification/card[{:keys [creator_id payload subscriptions] :as _notification-info} :- ::notification.payload/Notification]@@ -24,7 +24,7 @@:status (:status card-result):error (:error card-result)}))){:card_part part- :card (t2/select-one :model/Card card-id)+ :card (notification.db/card card-id):style {:color_text_dark channel.render/color-text-dark:color_text_light channel.render/color-text-light:color_text_medium channel.render/color-text-medium}@@ -72,7 +72,7 @@(when (and (-> notification-info :payload :send_once)(not skipped?))(log/info "Archiving due to send_once")- (t2/update! :model/Notification (:id notification-info) {:active false}))+ (notification.db/deactivate-notification! (:id notification-info)))(try(when-let [rows (-> notification-payload :payload :card_part :result :data :rows)](notification.payload/cleanup! rows))diff --git a/src/metabase/notification/payload/impl/dashboard.clj b/src/metabase/notification/payload/impl/dashboard.cljindex 56b63327483..2de2e9426bf 100644--- a/src/metabase/notification/payload/impl/dashboard.clj+++ b/src/metabase/notification/payload/impl/dashboard.clj@@ -2,6 +2,7 @@(:require[metabase.channel.render.core :as channel.render][metabase.events.core :as events]+ [metabase.notification.db :as notification.db][metabase.notification.payload.core :as notification.payload][metabase.notification.payload.execute :as notification.execute][metabase.notification.send :as notification.send]@@ -43,7 +44,7 @@[{:keys [creator_id dashboard_subscription handlers] :as _notification-info} :- ::notification.payload/Notification](log/with-context {:dashboard_id (:dashboard_id dashboard_subscription)}(let [dashboard-id (:dashboard_id dashboard_subscription)- dashboard (t2/hydrate (t2/select-one :model/Dashboard dashboard-id) :tabs)+ dashboard (t2/hydrate (notification.db/dashboard dashboard-id) :tabs)parameters (parameters (:parameters dashboard_subscription) (:parameters dashboard))attached-ids (attached-card-ids dashboard_subscription)only-card-ids (when (attachment-only? handlers)diff --git a/src/metabase/notification/payload/impl/system_event.clj b/src/metabase/notification/payload/impl/system_event.cljindex 9785736b2c2..29d437ce8bd 100644--- a/src/metabase/notification/payload/impl/system_event.clj+++ b/src/metabase/notification/payload/impl/system_event.clj@@ -5,14 +5,14 @@[metabase.auth-identity.core :as auth-identity][metabase.channel.email.messages :as messages][metabase.channel.urls :as urls]+ [metabase.notification.db :as notification.db][metabase.notification.payload.core :as notification.payload][metabase.session.core :as session][metabase.sso.core :as sso][metabase.system.core :as system][metabase.users.models.user :as user][metabase.util.i18n :refer [trs]]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(defn- join-url[user-id redirect]@@ -20,7 +20,7 @@(let [reset-token (auth-identity/create-password-reset! user-id)should-link-to-login-page (and (sso/sso-enabled?)(not (session/enable-password-login)))- email (t2/select-one-fn :email [:model/User :email] user-id)]+ email (notification.db/user-email user-id)](if should-link-to-login-page(cond-> (str (system/site-url) "/auth/login")redirect (str "?redirect=" redirect))diff --git a/src/metabase/notification/seed.clj b/src/metabase/notification/seed.cljindex 38c6613acb4..d743f7f833d 100644--- a/src/metabase/notification/seed.clj+++ b/src/metabase/notification/seed.clj@@ -3,6 +3,7 @@No-op if none of the notifications are changed.If a notification is changed, it will be replaced with a new one."(:require+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.permissions.core :as perms][metabase.util :as u]@@ -189,9 +190,9 @@(defn- cleanup-notification![internal-id existing-row]- (t2/delete! :model/Notification :internal_id internal-id)+ (notification.db/delete-notification-by-internal-id! internal-id)(when-let [template-ids (->> existing-row :handlers (keep (comp :id :template)) seq)]- (t2/delete! :model/ChannelTemplate :id [:in template-ids])))+ (notification.db/delete-channel-templates! template-ids)))(defn- create-notification![notification]@@ -199,9 +200,7 @@(if-let [template (:template handler)](-> handler(dissoc :template)- (assoc :template_id (t2/insert-returning-pk!- :model/ChannelTemplate- template)))+ (assoc :template_id (notification.db/insert-channel-template! template)))handler))](models.notification/create-notification!(dissoc notification :handlers :subscriptions)@@ -228,12 +227,11 @@"Hydrate an existing notification row for comparison. Don't use [[models.notification/hydrate-notification]]so we can migrate on schema changes."[notification]- (t2/hydrate notification :creator :payload :subscriptions- [:handlers :channel :template [:recipients :recipients-detail]]))+ (t2/hydrate notification :creator :payload :subscriptions [:handlers :channel :template [:recipients :recipients-detail]]))(defn- sync-notification![{:keys [internal_id] :as row}]- (let [existing-notification (some-> (t2/select-one :model/Notification :internal_id internal_id)+ (let [existing-notification (some-> (notification.db/notification-by-internal-id internal_id)hydrate-existing-notification)](u/prog1 (action existing-notification row)(case <>diff --git a/src/metabase/notification/send.clj b/src/metabase/notification/send.cljindex fb2624f5640..436631e958c 100644--- a/src/metabase/notification/send.clj+++ b/src/metabase/notification/send.clj@@ -5,6 +5,7 @@[metabase.analytics.core :as analytics.core][metabase.channel.core :as channel][metabase.config.core :as config]+ [metabase.notification.db :as notification.db][metabase.notification.models :as models.notification][metabase.notification.payload.core :as notification.payload][metabase.notification.settings :as notification.settings]@@ -151,9 +152,9 @@;; notifications pass through :payload instead and have no :payload_id.(when-let [payload-id (when (= :notification/card payload_type)(:payload_id notification-info))]- (when-not (t2/exists? :model/NotificationCard payload-id)+ (when-not (notification.db/notification-card-exists? payload-id)(log/warnf "Payload for notification %d no longer exists, deleting" id)- (t2/delete! :model/Notification id)+ (notification.db/delete-notification! id)(throw (ex-info "Card no longer exists, notification deleted"{:notification-id id}))))(let [hydrated-notification (hydrate-notification notification-info)@@ -469,7 +470,7 @@(case payload_type:notification/card (when-let [card-id (or (:card_id payload)(some->> payload_id- (t2/select-one-fn :card_id :model/NotificationCard :id)))]+ notification.db/notification-card-card-id))]{:run_type :alert:entity_type :card:entity_id card-iddiff --git a/src/metabase/notification/task/send.clj b/src/metabase/notification/task/send.cljindex ba36213be29..ef7caf94908 100644--- a/src/metabase/notification/task/send.clj+++ b/src/metabase/notification/task/send.clj@@ -6,13 +6,13 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][metabase.driver :as driver]+ [metabase.notification.db :as notification.db][metabase.notification.send :as notification.send][metabase.query-processor.timezone :as qp.timezone][metabase.task-history.core :as task-history][metabase.task.core :as task][metabase.tracing.core :as tracing]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.util TimeZone)(org.quartz CronTrigger DisallowConcurrentExecution JobExecutionContext TriggerKey)))@@ -100,9 +100,9 @@(defn- send-notification*[subscription-id]- (let [subscription (t2/select-one :model/NotificationSubscription subscription-id)+ (let [subscription (notification.db/subscription subscription-id)notification-id (:notification_id subscription)- notification (t2/select-one :model/Notification notification-id)]+ notification (notification.db/notification notification-id)](log/with-context {:subscription-id subscription-id:notification-id notification-id}(cond@@ -135,14 +135,7 @@(defn- active-cron-subscription-id->subscription[]- (t2/select-pk->fn identity :model/NotificationSubscription- :type :notification-subscription/cron- {:select [:ns.*]- :from [[:notification_subscription :ns]]- :join [[:notification :n] [:= :ns.notification_id :n.id]]- :where [:and- [:= :ns.type "notification-subscription/cron"]- [:= :n.active true]]}))+ (notification.db/active-cron-subscriptions-by-id))(defn update-send-notification-triggers-timezone!"Update the timezone of all SendNotification triggers if the report timezone changes."diff --git a/src/metabase/oauth_server/api/admin.clj b/src/metabase/oauth_server/api/admin.cljindex 6970b653479..1dc06509643 100644--- a/src/metabase/oauth_server/api/admin.clj+++ b/src/metabase/oauth_server/api/admin.clj@@ -3,10 +3,10 @@(:require[metabase.api.common :as api][metabase.api.macros :as api.macros]+ [metabase.oauth-server.db :as oauth-server.db][metabase.request.current :as request][metabase.util.json :as json]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)@@ -20,14 +20,6 @@:user_id :user_email :user_first_name :user_last_name])(update :redirect_uris #(some-> % json/decode))))-(defn- event-where-clause- [client-id event-type]- (let [clauses (cond-> []- client-id (conj [:= :c.client_id client-id])- event-type (conj [:= :e.event_type event-type]))]- (when (seq clauses)- (into [:and] clauses))))-(api.macros/defendpoint :get "/authorizations":- [:map[:total ms/IntGreaterThanOrEqualToZero]@@ -43,28 +35,8 @@(api/check-superuser)(let [limit (or (request/limit) 50)offset (or (request/offset) 0)- where (event-where-clause client-id event-type)- total (:count (first (t2/query (cond-> {:select [[[:count :*] :count]]- :from [[:oauth_client_event :e]]- :left-join [[:oauth_client :c] [:= :e.oauth_client_id :c.id]]}- where (assoc :where where)))))- rows (t2/query (cond-> {:select [:e.id :e.oauth_client_id :e.user_id :e.event_type :e.created_at- [:c.client_id :client_id]- [:c.client_name :client_name]- [:c.client_uri :client_uri]- [:c.registration_type :registration_type]- [:c.application_type :application_type]- [:c.redirect_uris :redirect_uris]- [:u.email :user_email]- [:u.first_name :user_first_name]- [:u.last_name :user_last_name]]- :from [[:oauth_client_event :e]]- :left-join [[:oauth_client :c] [:= :e.oauth_client_id :c.id]- [:core_user :u] [:= :e.user_id :u.id]]- :order-by [[:e.created_at :desc] [:e.id :desc]]- :limit limit- :offset offset}- where (assoc :where where)))]+ total (:count (first (oauth-server.db/client-event-count client-id event-type)))+ rows (oauth-server.db/client-events client-id event-type limit offset)]{:total (or total 0):limit limit:offset offsetdiff --git a/src/metabase/oauth_server/core.clj b/src/metabase/oauth_server/core.cljindex 08648aeef6f..be7c0db10b0 100644--- a/src/metabase/oauth_server/core.clj+++ b/src/metabase/oauth_server/core.clj@@ -3,14 +3,14 @@[clojure.string :as str][java-time.api :as t][metabase.mcp.core :as mcp]+ [metabase.oauth-server.db :as oauth-server.db][metabase.oauth-server.scopes :as scopes][metabase.oauth-server.settings :as oauth-settings][metabase.oauth-server.store :as store][metabase.system.core :as system][metabase.util :as u][oidc-provider.core :as oidc]- [oidc-provider.store :as oidc.store]- [toucan2.core :as t2]))+ [oidc-provider.store :as oidc.store]))(set! *warn-on-reflection* true)@@ -113,8 +113,8 @@(when (and (or (nil? expiry)(t/after? (t/instant expiry) (t/instant)));; Fail closed if the issuing client is gone (SEC-863).- (t2/exists? :model/OAuthClient :client_id (:client-id token-data)))+ (oauth-server.db/oauth-client-exists? (:client-id token-data)))(when-let [user-id (some-> (:user-id token-data) parse-long)]- (when (t2/exists? :model/User :id user-id :is_active true)+ (when (oauth-server.db/active-user-exists? user-id){:user-id user-id:scopes (or (some->> (:scope token-data) (into #{})) #{})}))))))))diff --git a/src/metabase/oauth_server/db.clj b/src/metabase/oauth_server/db.cljnew file mode 100644index 00000000000..535165efdd9--- /dev/null+++ b/src/metabase/oauth_server/db.clj@@ -0,0 +1,172 @@+(ns metabase.oauth-server.db+ "Application database queries for the OAuth server module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn- client-event-where+ "The `:where` clause for OAuthClientEvents narrowed by `client-id` and/or `event-type`, or nil for no+ narrowing."+ [client-id event-type]+ (let [clauses (cond-> []+ client-id (conj [:= :c.client_id client-id])+ event-type (conj [:= :e.event_type event-type]))]+ (when (seq clauses)+ (into [:and] clauses))))++(defn client-event-count+ "The number of OAuthClientEvents matching `client-id` and/or `event-type` (all of them when both nil)."+ [client-id event-type]+ (let [where (client-event-where client-id event-type)]+ (t2/query (cond-> {:select [[[:count :*] :count]]+ :from [[:oauth_client_event :e]]+ :left-join [[:oauth_client :c] [:= :e.oauth_client_id :c.id]]}+ where (assoc :where where)))))++(defn client-events+ "Up to `limit` OAuthClientEvents from `offset` matching `client-id` and/or `event-type` (all of them when+ both nil), newest first, with their client and deciding user."+ [client-id event-type limit offset]+ (let [where (client-event-where client-id event-type)]+ (t2/query (cond-> {:select [:e.id :e.oauth_client_id :e.user_id :e.event_type :e.created_at+ [:c.client_id :client_id]+ [:c.client_name :client_name]+ [:c.client_uri :client_uri]+ [:c.registration_type :registration_type]+ [:c.application_type :application_type]+ [:c.redirect_uris :redirect_uris]+ [:u.email :user_email]+ [:u.first_name :user_first_name]+ [:u.last_name :user_last_name]]+ :from [[:oauth_client_event :e]]+ :left-join [[:oauth_client :c] [:= :e.oauth_client_id :c.id]+ [:core_user :u] [:= :e.user_id :u.id]]+ :order-by [[:e.created_at :desc] [:e.id :desc]]+ :limit limit+ :offset offset}+ where (assoc :where where)))))++(defn active-user-exists?+ "Whether an active User with `user-id` exists."+ [user-id]+ (t2/exists? :model/User :id user-id :is_active true))++(defn oauth-client-exists?+ "Whether an OAuthClient with `client-id` exists."+ [client-id]+ (t2/exists? :model/OAuthClient :client_id client-id))++(defn revoke-access-tokens-for-user!+ "Revoke the unrevoked OAuthAccessTokens of the User with `user-id`."+ [user-id]+ (t2/update! :model/OAuthAccessToken {:user_id user-id, :revoked_at nil} {:revoked_at :%now}))++(defn revoke-refresh-tokens-for-user!+ "Revoke the unrevoked OAuthRefreshTokens of the User with `user-id`."+ [user-id]+ (t2/update! :model/OAuthRefreshToken {:user_id user-id, :revoked_at nil} {:revoked_at :%now}))++(defn delete-authorization-codes-for-user!+ "Delete the OAuthAuthorizationCodes of the User with `user-id`."+ [user-id]+ (t2/delete! :model/OAuthAuthorizationCode :user_id user-id))++(defn oauth-client-pk+ "The primary key of the OAuthClient with `client-id`, or nil."+ [client-id]+ (t2/select-one-pk :model/OAuthClient :client_id client-id))++(defn insert-client-event!+ "Insert the OAuthClientEvent `row`."+ [row]+ (t2/insert! :model/OAuthClientEvent row))++(defn oauth-client+ "The OAuthClient with `client-id`, or nil."+ [client-id]+ (t2/select-one :model/OAuthClient :client_id client-id))++(defn insert-oauth-client!+ "Insert the OAuthClient `row`."+ [row]+ (t2/insert! :model/OAuthClient row))++(defn update-oauth-client!+ "Apply `row` to the OAuthClient with primary key `id`."+ [id row]+ (t2/update! :model/OAuthClient id row))++(defn insert-authorization-code!+ "Insert the OAuthAuthorizationCode `row`."+ [row]+ (t2/insert! :model/OAuthAuthorizationCode row))++(defn authorization-code+ "The OAuthAuthorizationCode `code`, or nil."+ [code]+ (t2/select-one :model/OAuthAuthorizationCode :code code))++(defn lock-authorization-code+ "The OAuthAuthorizationCode `code` locked for update, or nil."+ [code]+ (t2/select-one :model/OAuthAuthorizationCode :code code {:for :update}))++(defn delete-authorization-code!+ "Delete the OAuthAuthorizationCode `code`."+ [code]+ (t2/delete! :model/OAuthAuthorizationCode :code code))++(defn insert-access-token!+ "Insert the OAuthAccessToken `row`."+ [row]+ (t2/insert! :model/OAuthAccessToken row))++(defn unrevoked-access-token+ "The unrevoked OAuthAccessToken `token`, or nil."+ [token]+ (t2/select-one :model/OAuthAccessToken :token token :revoked_at nil))++(defn insert-refresh-token!+ "Insert the OAuthRefreshToken `row`."+ [row]+ (t2/insert! :model/OAuthRefreshToken row))++(defn unrevoked-refresh-token+ "The unrevoked OAuthRefreshToken `token`, or nil."+ [token]+ (t2/select-one :model/OAuthRefreshToken :token token :revoked_at nil))++(defn revoke-access-token!+ "Revoke the OAuthAccessToken `token`."+ [token]+ (t2/update! :model/OAuthAccessToken {:token token} {:revoked_at :%now}))++(defn revoke-refresh-token!+ "Revoke the OAuthRefreshToken `token`."+ [token]+ (t2/update! :model/OAuthRefreshToken {:token token} {:revoked_at :%now}))++(defn delete-authorization-codes-expired-before!+ "Delete the OAuthAuthorizationCodes that expired before `now`, returning the number deleted."+ [now]+ (t2/delete! :model/OAuthAuthorizationCode :expiry [:< now]))++(defn delete-access-tokens-expired-before!+ "Delete the OAuthAccessTokens that expired before `now`, returning the number deleted."+ [now]+ (t2/delete! :model/OAuthAccessToken :expiry [:< now]))++(defn delete-revoked-access-tokens!+ "Delete the revoked OAuthAccessTokens, returning the number deleted."+ []+ (t2/delete! :model/OAuthAccessToken :revoked_at [:not= nil]))++(defn delete-refresh-tokens-expired-before!+ "Delete the OAuthRefreshTokens that expired before `now`, returning the number deleted."+ [now]+ (t2/delete! :model/OAuthRefreshToken :expiry [:< now]))++(defn delete-revoked-refresh-tokens!+ "Delete the revoked OAuthRefreshTokens, returning the number deleted."+ []+ (t2/delete! :model/OAuthRefreshToken :revoked_at [:not= nil]))diff --git a/src/metabase/oauth_server/events/revoke_on_deactivation.clj b/src/metabase/oauth_server/events/revoke_on_deactivation.cljindex 833cad6635b..45919847e64 100644--- a/src/metabase/oauth_server/events/revoke_on_deactivation.clj+++ b/src/metabase/oauth_server/events/revoke_on_deactivation.clj@@ -3,14 +3,14 @@can't revive a pre-deactivation token. (SEC-863)"(:require[metabase.events.core :as events]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [metabase.oauth-server.db :as oauth-server.db]+ [methodical.core :as methodical]))(events/derive! ::event :metabase/event)(events/derive! :event/user-credentials-revoked ::event)(methodical/defmethod events/publish-event! ::event[_topic {:keys [user-id] :as _event}]- (t2/update! :model/OAuthAccessToken {:user_id user-id, :revoked_at nil} {:revoked_at :%now})- (t2/update! :model/OAuthRefreshToken {:user_id user-id, :revoked_at nil} {:revoked_at :%now})- (t2/delete! :model/OAuthAuthorizationCode :user_id user-id))+ (oauth-server.db/revoke-access-tokens-for-user! user-id)+ (oauth-server.db/revoke-refresh-tokens-for-user! user-id)+ (oauth-server.db/delete-authorization-codes-for-user! user-id))diff --git a/src/metabase/oauth_server/models/oauth_client_event.clj b/src/metabase/oauth_server/models/oauth_client_event.cljindex b7dbde33af7..6a335d0cc72 100644--- a/src/metabase/oauth_server/models/oauth_client_event.clj+++ b/src/metabase/oauth_server/models/oauth_client_event.clj@@ -6,6 +6,7 @@each decision a user makes via `POST /oauth/authorize/decision`, stamped with the deciding user's`user_id`."(:require+ [metabase.oauth-server.db :as oauth-server.db][metabase.util.log :as log][methodical.core :as methodical][toucan2.core :as t2]))@@ -20,15 +21,15 @@(defn- client-pk"Look up the numeric `oauth_client.id` primary key for the given OAuth `client-id` (UUID)."[client-id]- (t2/select-one-pk :model/OAuthClient :client_id client-id))+ (oauth-server.db/oauth-client-pk client-id))(defn record-registration!"Record a `registered` event for the freshly-registered client identified by `client-id` (the OAuthUUID). No-op (with a warning) if the client row cannot be found."[client-id](if-let [oauth-client-id (client-pk client-id)]- (t2/insert! :model/OAuthClientEvent {:oauth_client_id oauth-client-id- :event_type "registered"})+ (oauth-server.db/insert-client-event! {:oauth_client_id oauth-client-id+ :event_type "registered"})(log/warnf "Cannot record OAuth registration event: no client found for client_id %s" client-id)))(defn record-decision!@@ -36,7 +37,7 @@(with a warning) if the client row cannot be found."[client-id user-id approved?](if-let [oauth-client-id (client-pk client-id)]- (t2/insert! :model/OAuthClientEvent {:oauth_client_id oauth-client-id- :user_id user-id- :event_type (if approved? "approved" "denied")})+ (oauth-server.db/insert-client-event! {:oauth_client_id oauth-client-id+ :user_id user-id+ :event_type (if approved? "approved" "denied")})(log/warnf "Cannot record OAuth decision event: no client found for client_id %s" client-id)))diff --git a/src/metabase/oauth_server/store.clj b/src/metabase/oauth_server/store.cljindex 7c87b1e23be..562c9342541 100644--- a/src/metabase/oauth_server/store.clj+++ b/src/metabase/oauth_server/store.clj@@ -1,6 +1,7 @@(ns metabase.oauth-server.store"Database-backed implementations of OAuth provider storage protocols."(:require+ [metabase.oauth-server.db :as oauth-server.db][metabase.util :as u][oidc-provider.protocol :as proto][toucan2.core :as t2]))@@ -106,7 +107,7 @@(defrecord DbClientStore []proto/ClientStore(get-client [_ client-id]- (-> (t2/select-one :model/OAuthClient :client_id client-id)+ (-> (oauth-server.db/oauth-client client-id)db-row->client-config))(register-client [_ client-config]@@ -126,17 +127,17 @@(-> (assoc :client-secret-hash (:client-secret client-config))(dissoc :client-secret))))row (client-config->db-row config)]- (t2/insert! :model/OAuthClient row)+ (oauth-server.db/insert-oauth-client! row)config))(update-client [_ client-id updated-config]- (let [existing (t2/select-one :model/OAuthClient :client_id client-id)]+ (let [existing (oauth-server.db/oauth-client client-id)](when existing(let [existing-config (db-row->client-config existing)merged (-> (merge existing-config updated-config)(assoc :client-id client-id))row (client-config->db-row merged)]- (t2/update! :model/OAuthClient (:id existing) row)+ (oauth-server.db/update-oauth-client! (:id existing) row)merged)))));;; ----------------------------------------- AuthorizationCodeStore ---------------------------------------------------@@ -144,31 +145,31 @@(defrecord DbAuthorizationCodeStore []proto/AuthorizationCodeStore(save-authorization-code [_ code user-id client-id redirect-uri scope nonce expiry code-challenge code-challenge-method resource]- (t2/insert! :model/OAuthAuthorizationCode- (cond-> {:code code- :user_id (parse-user-id-or-throw user-id)- :client_id client-id- :redirect_uri redirect-uri- :scope (vec scope)- :nonce nonce- :expiry expiry}- code-challenge (assoc :code_challenge code-challenge)- code-challenge-method (assoc :code_challenge_method code-challenge-method)- resource (assoc :resource (vec resource))))+ (oauth-server.db/insert-authorization-code!+ (cond-> {:code code+ :user_id (parse-user-id-or-throw user-id)+ :client_id client-id+ :redirect_uri redirect-uri+ :scope (vec scope)+ :nonce nonce+ :expiry expiry}+ code-challenge (assoc :code_challenge code-challenge)+ code-challenge-method (assoc :code_challenge_method code-challenge-method)+ resource (assoc :resource (vec resource))))true)(get-authorization-code [_ code]- (-> (t2/select-one :model/OAuthAuthorizationCode :code code)+ (-> (oauth-server.db/authorization-code code)db-row->auth-code))(delete-authorization-code [_ code]- (t2/delete! :model/OAuthAuthorizationCode :code code)+ (oauth-server.db/delete-authorization-code! code)true)(consume-authorization-code [_ code](t2/with-transaction [_conn]- (when-let [row (t2/select-one :model/OAuthAuthorizationCode :code code {:for :update})]- (t2/delete! :model/OAuthAuthorizationCode :code code)+ (when-let [row (oauth-server.db/lock-authorization-code code)]+ (oauth-server.db/delete-authorization-code! code)(db-row->auth-code row)))));;; ------------------------------------------------ TokenStore --------------------------------------------------------@@ -176,36 +177,36 @@(defrecord DbTokenStore []proto/TokenStore(save-access-token [_ token user-id client-id scope expiry resource]- (t2/insert! :model/OAuthAccessToken- (cond-> {:token token- :user_id (parse-user-id user-id)- :client_id client-id- :scope (vec scope)- :expiry expiry}- resource (assoc :resource (vec resource))))+ (oauth-server.db/insert-access-token!+ (cond-> {:token token+ :user_id (parse-user-id user-id)+ :client_id client-id+ :scope (vec scope)+ :expiry expiry}+ resource (assoc :resource (vec resource))))true)(get-access-token [_ token]- (-> (t2/select-one :model/OAuthAccessToken :token token :revoked_at nil)+ (-> (oauth-server.db/unrevoked-access-token token)db-row->access-token))(save-refresh-token [_ token user-id client-id scope expiry resource]- (t2/insert! :model/OAuthRefreshToken- (cond-> {:token token- :user_id (parse-user-id user-id)- :client_id client-id- :scope (vec scope)}- expiry (assoc :expiry expiry)- resource (assoc :resource (vec resource))))+ (oauth-server.db/insert-refresh-token!+ (cond-> {:token token+ :user_id (parse-user-id user-id)+ :client_id client-id+ :scope (vec scope)}+ expiry (assoc :expiry expiry)+ resource (assoc :resource (vec resource))))true)(get-refresh-token [_ token]- (-> (t2/select-one :model/OAuthRefreshToken :token token :revoked_at nil)+ (-> (oauth-server.db/unrevoked-refresh-token token)db-row->refresh-token))(revoke-token [_ token]- (t2/update! :model/OAuthAccessToken {:token token} {:revoked_at :%now})- (t2/update! :model/OAuthRefreshToken {:token token} {:revoked_at :%now})+ (oauth-server.db/revoke-access-token! token)+ (oauth-server.db/revoke-refresh-token! token)true));;; ------------------------------------------------ Constructors ------------------------------------------------------diff --git a/src/metabase/oauth_server/task/cleanup_expired_tokens.clj b/src/metabase/oauth_server/task/cleanup_expired_tokens.cljindex 1dddaee3c0f..81e2441b1ee 100644--- a/src/metabase/oauth_server/task/cleanup_expired_tokens.clj+++ b/src/metabase/oauth_server/task/cleanup_expired_tokens.clj@@ -4,10 +4,10 @@[clojurewerkz.quartzite.jobs :as jobs][clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers]+ [metabase.oauth-server.db :as oauth-server.db][metabase.task.core :as task][metabase.tracing.core :as tracing]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -19,11 +19,11 @@;; Issue expiry- and revocation-based deletes as separate statements so each can use the appropriate;; index (expiry / revoked_at). A combined `OR` predicate would prevent the planner from using either;; index and degrade into a table scan as these tables grow.- {:authorization-codes-expired (t2/delete! :model/OAuthAuthorizationCode :expiry [:< now])- :access-tokens-expired (t2/delete! :model/OAuthAccessToken :expiry [:< now])- :access-tokens-revoked (t2/delete! :model/OAuthAccessToken :revoked_at [:not= nil])- :refresh-tokens-expired (t2/delete! :model/OAuthRefreshToken :expiry [:< now])- :refresh-tokens-revoked (t2/delete! :model/OAuthRefreshToken :revoked_at [:not= nil])}))+ {:authorization-codes-expired (oauth-server.db/delete-authorization-codes-expired-before! now)+ :access-tokens-expired (oauth-server.db/delete-access-tokens-expired-before! now)+ :access-tokens-revoked (oauth-server.db/delete-revoked-access-tokens!)+ :refresh-tokens-expired (oauth-server.db/delete-refresh-tokens-expired-before! now)+ :refresh-tokens-revoked (oauth-server.db/delete-revoked-refresh-tokens!)}))(task/defjob ^{:doc "Delete expired and revoked OAuth tokens and authorization codes."}CleanupExpiredOAuthTokens [_]diff --git a/src/metabase/osi/ai_context/api.clj b/src/metabase/osi/ai_context/api.cljindex 7b2a46de099..500ed939fc9 100644--- a/src/metabase/osi/ai_context/api.clj+++ b/src/metabase/osi/ai_context/api.clj@@ -6,11 +6,11 @@[metabase.api.macros :as api.macros][metabase.app-db.core :as app-db][metabase.entity-retrieval.core :as entity-retrieval]+ [metabase.osi.db :as osi.db][metabase.osi.models.osi-ai-context :as osi-ai-context][metabase.request.core :as request][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(def ^:private writable-entity-types"Entity types accepted on writes — the real types callers name. Card flavors (metric/model) are stored@@ -61,9 +61,7 @@"The stored row for an entity, looked up by its normalized key, or nil. The CRUD API speaks the realcard flavors; storage keys on the canonical `card`, so normalize before matching."[entity-type entity-local-id]- (t2/select-one :model/OsiAiContext- :entity_type (entity-retrieval/normalize-entity-type entity-type)- :entity_local_id entity-local-id))+ (osi.db/ai-context (entity-retrieval/normalize-entity-type entity-type) entity-local-id))(def ^:private logical-key-route-schema;; entity-type is any non-blank string at the route level — a write to a non-writable type gets a clear@@ -85,11 +83,8 @@(api/check-superuser)(let [limit (or (request/limit) default-limit)offset (or (request/offset) default-offset)]- {:data (t2/select :model/OsiAiContext- {:order-by [[:entity_type :asc] [:entity_local_id :asc]]- :limit limit- :offset offset})- :total (t2/count :model/OsiAiContext)+ {:data (osi.db/ai-contexts-page limit offset)+ :total (osi.db/ai-context-count):limit limit:offset offset}))@@ -153,7 +148,5 @@_query-params](api/check-superuser)(api/check-404 (get-entry entity-type entity-local-id))- (t2/delete! :model/OsiAiContext- :entity_type (entity-retrieval/normalize-entity-type entity-type)- :entity_local_id entity-local-id)+ (osi.db/delete-ai-context! (entity-retrieval/normalize-entity-type entity-type) entity-local-id)api/generic-204-no-content)diff --git a/src/metabase/osi/db.clj b/src/metabase/osi/db.cljnew file mode 100644index 00000000000..0c6a4a45244--- /dev/null+++ b/src/metabase/osi/db.clj@@ -0,0 +1,33 @@+(ns metabase.osi.db+ "Application database queries for the OSI module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn ai-context+ "The OsiAiContext of the entity with `entity-type` and `entity-local-id`, or nil."+ [entity-type entity-local-id]+ (t2/select-one :model/OsiAiContext :entity_type entity-type :entity_local_id entity-local-id))++(defn ai-contexts-page+ "Up to `limit` OsiAiContexts from `offset`, ordered by entity type and local id."+ [limit offset]+ (t2/select :model/OsiAiContext+ {:order-by [[:entity_type :asc] [:entity_local_id :asc]]+ :limit limit+ :offset offset}))++(defn ai-context-count+ "The number of OsiAiContexts."+ []+ (t2/count :model/OsiAiContext))++(defn delete-ai-context!+ "Delete the OsiAiContext of the entity with `entity-type` and `entity-local-id`."+ [entity-type entity-local-id]+ (t2/delete! :model/OsiAiContext :entity_type entity-type :entity_local_id entity-local-id))++(defn update-ai-context!+ "Apply `changes` to the OsiAiContext of the entity with `entity-type` and `entity-local-id`."+ [entity-type entity-local-id changes]+ (t2/update! :model/OsiAiContext :entity_type entity-type :entity_local_id entity-local-id changes))diff --git a/src/metabase/osi/models/osi_ai_context.clj b/src/metabase/osi/models/osi_ai_context.cljindex daabb4ebe71..354718bf03f 100644--- a/src/metabase/osi/models/osi_ai_context.clj+++ b/src/metabase/osi/models/osi_ai_context.clj@@ -18,6 +18,7 @@[metabase.entity-retrieval.mirror :as mirror][metabase.models.interface :as mi][metabase.models.serialization :as serdes]+ [metabase.osi.db :as osi.db][metabase.util :as u][methodical.core :as methodical][toucan2.core :as t2]))@@ -164,16 +165,11 @@[path];; Resolve the parent path back to a local entity, then find this row by its (entity_type, local-id) key.(when-let [{:keys [entity_type entity_local_id]} (parent-path->entity (pop path))]- (t2/select-one :model/OsiAiContext- :entity_type (entity-retrieval/normalize-entity-type entity_type)- :entity_local_id entity_local_id)))+ (osi.db/ai-context (entity-retrieval/normalize-entity-type entity_type) entity_local_id)))(defmethod serdes/load-update! "OsiAiContext"[_model-name ingested local];; The default keys updates on (first (primary-keys)), which for this compound key is just :entity_type —;; so it would address the wrong rows. Update by the full (entity_type, entity_local_id) key.- (t2/update! :model/OsiAiContext- :entity_type (:entity_type local) :entity_local_id (:entity_local_id local)- ingested)- (t2/select-one :model/OsiAiContext- :entity_type (:entity_type local) :entity_local_id (:entity_local_id local)))+ (osi.db/update-ai-context! (:entity_type local) (:entity_local_id local) ingested)+ (osi.db/ai-context (:entity_type local) (:entity_local_id local)))diff --git a/src/metabase/parameters/chain_filter.clj b/src/metabase/parameters/chain_filter.cljindex a888a116b95..849eb2b03c9 100644--- a/src/metabase/parameters/chain_filter.clj+++ b/src/metabase/parameters/chain_filter.clj@@ -65,7 +65,6 @@[clojure.core.memoize :as memoize][clojure.set :as set][clojure.string :as str]- [honey.sql :as sql][metabase.app-db.core :as mdb][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]@@ -76,6 +75,7 @@[metabase.lib.types.isa :as lib.types.isa][metabase.lib.util :as lib.util][metabase.parameters.chain-filter.dedupe-joins :as dedupe]+ [metabase.parameters.db :as parameters.db][metabase.parameters.field-values :as params.field-values][metabase.parameters.params :as params][metabase.parameters.schema :as parameters.schema]@@ -92,8 +92,7 @@[metabase.util.malli.schema :as ms][metabase.warehouse-schema.metadata-queries :as schema.metadata-queries][metabase.warehouse-schema.models.field :as field]- [metabase.warehouse-schema.models.field-values :as field-values]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.models.field-values :as field-values]));; so the hydration method for name_field is loaded(comment params/keep-me)@@ -547,68 +546,18 @@(get v->human-readable v (get v->human-readable (str v))))values)))-(defn- format-union- "Workaround for https://github.com/seancorfield/honeysql/issues/451. Wrap the subselects in parens, otherwise it will- fail on Postgres."- [_clause exprs]- (let [[sqls args] (sql/format-expr-list exprs)- sql (str/join " UNION " sqls)]- (into [sql] args)))--(sql/register-clause! ::union format-union :union)--(defn- implicit-pk->name-mapping-query- [field-id mapping-type]- ^:allow-subquery- {:select [[:dest.id :id] [^:allow-raw-sql [:inline mapping-type] :mapping_type]]- :from [[:metabase_field :source]]- :left-join [[:metabase_table :table] [:= :source.table_id :table.id]- [:metabase_field :dest] [:= :dest.table_id :table.id]]- :where [:and- [:= :source.id field-id]- (mdb/isa :source.semantic_type :type/PK)- (mdb/isa :dest.semantic_type :type/Name)]- :limit 1})-(def ^:dynamic *allow-implicit-uuid-field-remapping*"Should implicit remapping be allowed _for uuid fields_? Not eg. for`GET /dashboard/:id/params/:param-key/search/:query` to search on actual field that was pickedfor filtering (#59020). Apart from the endpoint it is bound in [[chain-filter-search]]!"true)-(defn- remapped-field-id-query [field-id]- {:select [[:mapping.id :id] [:mapping.mapping_type :mapping_type]]- :from [[^:allow-subquery- {::union (into [;; Explicit FK Field->Field remapping- ^:allow-subquery- {:select [[:dimension.human_readable_field_id :id] [^:allow-raw-sql [:inline "fk->field"] :mapping_type]]- :from [[:dimension :dimension]]- :where [:and- [:= :dimension.field_id field-id]- [:not= :dimension.human_readable_field_id nil]]- :limit 1}]- (when *allow-implicit-uuid-field-remapping*- [;; Implicit FK Field -> PK Field -> [Name] Field remapping- (implicit-pk->name-mapping-query- ^:allow-subquery- {:select [:fk_target_field_id]- :from [:metabase_field]- :where [:and- [:= :id field-id]- (mdb/isa :semantic_type :type/FK)]- :limit 1}- "fk->pk->name")- ;; Implicit PK Field-> [Name] Field remapping- (implicit-pk->name-mapping-query field-id "pk->name")]))}- :mapping]]- :limit 1})-;; TODO -- add some caching here?(mu/defn remapped-field-id :- [:maybe ::lib.schema.id/field]"Efficient query to find the ID of the Field we're remapping `field-id` to, if it has either type of Field -> Fieldremapping."[field-id :- [:maybe ::lib.schema.id/field]]- (:id (t2/query-one (remapped-field-id-query field-id))))+ (:id (parameters.db/remapped-field field-id *allow-implicit-uuid-field-remapping*)))(mu/defn remapping :- [:maybe [:map[:id ::lib.schema.id/field]@@ -616,7 +565,7 @@"Efficient query to find the ID of the Field we're remapping `field-id` to, if it has either type of Field -> Fieldremapping."[field-id :- [:maybe ::lib.schema.id/field]]- (when-let [raw-mapping (t2/query-one (remapped-field-id-query field-id))]+ (when-let [raw-mapping (parameters.db/remapped-field field-id *allow-implicit-uuid-field-remapping*)](-> raw-mapping(dissoc :mapping_type)(assoc :mapping-type (-> raw-mapping :mapping_type keyword)))))@@ -644,8 +593,8 @@;; TODO: why don't we remap the human readable values here?(let [{:keys [values] has-more-values? :has_more_values}(if (empty? constraints)- (params.field-values/get-or-create-field-values-for-current-user! (t2/select-one :model/Field :id field-id))- (params.field-values/get-or-create-linked-filter-field-values! (t2/select-one :model/Field :id field-id) constraints))]+ (params.field-values/get-or-create-field-values-for-current-user! (parameters.db/field field-id))+ (params.field-values/get-or-create-linked-filter-field-values! (parameters.db/field field-id) constraints))]{:values (cond->> valueslimit (take limit)):has_more_values (or (when limit@@ -708,7 +657,7 @@(let [{the-remapped-field-id :id, :keys [mapping-type]} @remapping](if-let [pk-field-id (when (and (= mapping-type :fk->pk->name)relax-fk-requirement?)- (t2/select-one-fn :fk_target_field_id :model/Field field-id))]+ (parameters.db/field-fk-target-field-id field-id))](unremapped-chain-filter the-remapped-field-id(map #(cond-> %(= (:field-id %) field-id) (assoc :field-id pk-field-id))@@ -726,12 +675,12 @@(defn- check-valid-search-field"Before running a search query, make sure the Field actually exists and that it's a Text field."[field-id]- (let [base-type (t2/select-one-fn :base_type :model/Field :id field-id)]+ (let [base-type (parameters.db/field-base-type field-id)](when-not base-type(throw (ex-info (tru "Field {0} does not exist." field-id){:field field-id, :status-code 404})))(when-not (isa? base-type :type/Text)- (let [field-name (t2/select-one-fn :name :model/Field :id field-id)]+ (let [field-name (parameters.db/field-name field-id)](throw (ex-info (tru "Cannot search against non-Text Field {0} {1}" field-id (pr-str field-name)){:status-code 400:field-id field-id@@ -777,22 +726,16 @@:has_more_values false}))(defn- search-cached-field-values? [field-id constraints]- (let [field (t2/select-one :model/Field :id field-id)]+ (let [field (parameters.db/field field-id)](and (use-cached-field-values? field-id)(isa? (:base_type field) :type/Text)- (apply t2/exists? :model/FieldValues (mapcat- identity- (merge {:field_id field-id, :values [:not= nil], :human_readable_values nil}- ;; if we are doing a search, make sure we only use field values- ;; when we're certain the fieldvalues we stored are all the possible values.- ;; otherwise, we should search directly from DB- {:has_more_values false}- (let [hash-input (params.field-values/hash-input-for-field-values field constraints)- hash-key (str (hash hash-input))]- (if (not= hash-input {:field-id field-id})- {:type "advanced"- :hash_key hash-key}- {:type "full"}))))))))+ ;; if we are doing a search, make sure we only use field values when we're certain the fieldvalues we stored+ ;; are all the possible values. otherwise, we should search directly from DB+ (let [hash-input (params.field-values/hash-input-for-field-values field constraints)+ hash-key (str (hash hash-input))]+ (if (not= hash-input {:field-id field-id})+ (parameters.db/advanced-field-values-exist? field-id hash-key)+ (parameters.db/full-field-values-exist? field-id))))))(defn- cached-field-values-search[field-id query constraints {:keys [limit]}]diff --git a/src/metabase/parameters/custom_values.clj b/src/metabase/parameters/custom_values.cljindex 1e0f7770286..d5285bd5bc5 100644--- a/src/metabase/parameters/custom_values.clj+++ b/src/metabase/parameters/custom_values.clj@@ -15,6 +15,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.lib.types.isa :as lib.types.isa][metabase.models.interface :as mi]+ [metabase.parameters.db :as parameters.db][metabase.parameters.schema :as parameters.schema][metabase.query-processor :as qp][metabase.util :as u]@@ -23,8 +24,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]- [metabase.util.performance :as perf]- [toucan2.core :as t2]))+ [metabase.util.performance :as perf]));;; ------------------------------------------------- source=static-list --------------------------------------------------@@ -202,7 +202,7 @@(case (:values_source_type parameter):static-list (static-list-values parameter query-string):card (let [config (:values_source_config parameter)- card (t2/select-one :model/Card :id (:card_id config))]+ card (parameters.db/card (:card_id config))](when-not (mi/can-read? card)(throw (ex-info "You don't have permissions to do that." {:status-code 403})))(or (when-not (:archived card)@@ -222,7 +222,7 @@[field-ids](when (and (seq field-ids) (every? pos-int? field-ids))(let [field-id-set (set field-ids)- fields (t2/select [:model/Field :id :fk_target_field_id :semantic_type] :id [:in field-id-set])]+ fields (parameters.db/fields-fk-info field-id-set)];; when every field could be found and all are keys(when (and (= (count field-id-set) (count fields))(every? (fn [{:keys [semantic_type fk_target_field_id]}]@@ -252,7 +252,7 @@field, the card is unreadable/archived, or no matching row is found."[{config :values_source_config :as _param} value](when-let [label-field (:label_field config)]- (when-let [card (t2/select-one :model/Card :id (:card_id config))]+ (when-let [card (parameters.db/card (:card_id config))](when (and (not (:archived card)) (mi/can-read? card))(when-let [query (card-query (:id card) (not-empty (:dataset_query card)))](when (can-get-card-values? query (:value_field config))diff --git a/src/metabase/parameters/db.clj b/src/metabase/parameters/db.cljnew file mode 100644index 00000000000..06c2d55a2ef--- /dev/null+++ b/src/metabase/parameters/db.clj@@ -0,0 +1,135 @@+(ns metabase.parameters.db+ "Application database queries for the parameters module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (hydration definitions still use `toucan2.core`)."+ (:require+ [clojure.string :as str]+ [honey.sql :as sql]+ [metabase.app-db.core :as mdb]+ [toucan2.core :as t2]))++(defn- format-union+ "Workaround for https://github.com/seancorfield/honeysql/issues/451. Wrap the subselects in parens, otherwise it+ will fail on Postgres."+ [_clause exprs]+ (let [[sqls args] (sql/format-expr-list exprs)+ formatted (str/join " UNION " sqls)]+ (into [formatted] args)))++(sql/register-clause! ::union format-union :union)++(defn- implicit-pk->name-mapping-query+ [field-id mapping-type]+ ^:allow-subquery+ {:select [[:dest.id :id] [^:allow-raw-sql [:inline mapping-type] :mapping_type]]+ :from [[:metabase_field :source]]+ :left-join [[:metabase_table :table] [:= :source.table_id :table.id]+ [:metabase_field :dest] [:= :dest.table_id :table.id]]+ :where [:and+ [:= :source.id field-id]+ (mdb/isa :source.semantic_type :type/PK)+ (mdb/isa :dest.semantic_type :type/Name)]+ :limit 1})++(defn remapped-field+ "The id and mapping-type of the Field that `field-id` remaps to via an explicit Field->Field Dimension, or —+ when `allow-implicit-uuid-remapping?` — an implicit FK->PK->Name or PK->Name mapping, or nil."+ [field-id allow-implicit-uuid-remapping?]+ (t2/query-one+ {:select [[:mapping.id :id] [:mapping.mapping_type :mapping_type]]+ :from [[^:allow-subquery+ {::union (into [;; Explicit FK Field->Field remapping+ ^:allow-subquery+ {:select [[:dimension.human_readable_field_id :id] [^:allow-raw-sql [:inline "fk->field"] :mapping_type]]+ :from [[:dimension :dimension]]+ :where [:and+ [:= :dimension.field_id field-id]+ [:not= :dimension.human_readable_field_id nil]]+ :limit 1}]+ (when allow-implicit-uuid-remapping?+ [;; Implicit FK Field -> PK Field -> [Name] Field remapping+ (implicit-pk->name-mapping-query+ ^:allow-subquery+ {:select [:fk_target_field_id]+ :from [:metabase_field]+ :where [:and+ [:= :id field-id]+ (mdb/isa :semantic_type :type/FK)]+ :limit 1}+ "fk->pk->name")+ ;; Implicit PK Field-> [Name] Field remapping+ (implicit-pk->name-mapping-query field-id "pk->name")]))}+ :mapping]]+ :limit 1}))++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field :id field-id))++(defn fields+ "The Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field :id [:in field-ids]))++(defn fields-fk-info+ "The id, FK target, and semantic type of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :fk_target_field_id :semantic_type] :id [:in field-ids]))++(defn field-fk-target-field-id+ "The FK target Field id of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one-fn :fk_target_field_id :model/Field field-id))++(defn field-base-type+ "The base type of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one-fn :base_type :model/Field :id field-id))++(defn field-name+ "The name of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one-fn :name :model/Field :id field-id))++(defn full-field-values-exist?+ "Whether complete, non-remapped FieldValues of type `full` exist for the Field with `field-id`."+ [field-id]+ (t2/exists? :model/FieldValues+ :field_id field-id, :values [:not= nil], :human_readable_values nil, :has_more_values false+ :type "full"))++(defn advanced-field-values-exist?+ "Whether complete, non-remapped FieldValues of type `advanced` with `hash-key` exist for the Field with `field-id`."+ [field-id hash-key]+ (t2/exists? :model/FieldValues+ :field_id field-id, :values [:not= nil], :human_readable_values nil, :has_more_values false+ :type "advanced", :hash_key hash-key))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn delete-field-values!+ "Delete the FieldValues with `id`."+ [id]+ (t2/delete! :model/FieldValues :id id))++(defn find-or-insert-advanced-field-values!+ "The advanced FieldValues of the Field with `field-id` and `hash-key`, inserting one built by calling+ `insert-fn` if none exists yet."+ [field-id hash-key insert-fn]+ (mdb/select-or-insert! :model/FieldValues {:field_id field-id, :type :advanced, :hash_key hash-key} insert-fn))++(defn active-name-fields-for-tables+ "The `columns` of the active `:type/Name` Fields of the Tables with `table-ids`."+ [columns table-ids]+ (t2/select (into [:model/Field] columns)+ :table_id [:in table-ids]+ :semantic_type (mdb/isa :type/Name)+ :active true))++(defn fields-with-columns+ "The `columns` of the Fields with `field-ids`."+ [columns field-ids]+ (t2/select (into [:model/Field] columns) :id [:in field-ids]))diff --git a/src/metabase/parameters/field.clj b/src/metabase/parameters/field.cljindex 24308057ade..bcd6df90168 100644--- a/src/metabase/parameters/field.clj+++ b/src/metabase/parameters/field.clj@@ -6,6 +6,7 @@[metabase.lib.core :as lib][metabase.lib.schema.id :as lib.schema.id][metabase.parameters.chain-filter :as chain-filter]+ [metabase.parameters.db :as parameters.db][metabase.parameters.field-values :as params.field-values][metabase.parameters.field.search-values-query :as search-values-query][metabase.query-processor.middleware.permissions :as qp.perms]@@ -13,8 +14,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [metabase.warehouse-schema.metadata-from-qp :as warehouse-schema.metadata-from-qp]- [toucan2.core :as t2])+ [metabase.warehouse-schema.metadata-from-qp :as warehouse-schema.metadata-from-qp])(:import(java.text NumberFormat)))@@ -32,7 +32,7 @@[{semantic-type :semantic_type, fk-target-field-id :fk_target_field_id, :as field}](if (and (isa? semantic-type :type/FK)fk-target-field-id)- (t2/select-one :model/Field :id fk-target-field-id)+ (parameters.db/field fk-target-field-id)field))(def ^:private default-max-field-search-limit 1000)@@ -78,7 +78,7 @@(if-let [remapped-field-id (when (= has-field-values-type :list)(chain-filter/remapped-field-id field-id))]{:values (search-values (api/check-404 field)- (api/check-404 (t2/select-one :model/Field :id remapped-field-id)))+ (api/check-404 (parameters.db/field remapped-field-id))):field_id field-id:has_more_values (boolean has_more_values)}(params.field-values/get-or-create-field-values-for-current-user! (api/check-404 field))))@@ -90,10 +90,10 @@(let [field (if qp.perms/*param-values-query*;; When fetching param values for a card/dashboard the user can read, skip the Field;; read-check which requires create-queries permission on the table.- (api/check-404 (t2/select-one :model/Field :id field-id))- (api/read-check (t2/select-one :model/Field :id field-id)))+ (api/check-404 (parameters.db/field field-id))+ (api/read-check (parameters.db/field field-id)))search-field (or (some->> (chain-filter/remapped-field-id field-id)- (t2/select-one :model/Field :id))+ parameters.db/field)field)]{:values (search-values field search-field query-string);; assume there are more if doing a search, otherwise there are no more valuesdiff --git a/src/metabase/parameters/field_values.clj b/src/metabase/parameters/field_values.cljindex d09d3e93824..cd11c0f5efb 100644--- a/src/metabase/parameters/field_values.clj+++ b/src/metabase/parameters/field_values.clj@@ -2,9 +2,9 @@"Code related to fetching FieldValues for Fields to populate parameter widgets. Always used by the fieldvalues (`GET /api/field/:id/values`) endpoint; used by the chain filter endpoints under certain circumstances."(:require- [metabase.app-db.core :as app-db][metabase.classloader.core :as classloader][metabase.models.interface :as mi]+ [metabase.parameters.db :as parameters.db][metabase.util :as u][metabase.warehouse-schema.models.field :as field][metabase.warehouse-schema.models.field-values :as field-values]@@ -40,7 +40,7 @@"OSS implementation; used as a fallback for the EE implementation for any fields that aren't subject to sandboxing."[field-ids](when (seq field-ids)- (let [field-ids (->> (t2/select :model/Field :id [:in (set field-ids)])+ (let [field-ids (->> (parameters.db/fields (set field-ids))field/readable-fields-only(map :id))](when (seq field-ids)@@ -82,7 +82,7 @@Returns `nil` if `field-ids` is empty of no matching FieldValues exist."[field-ids](let [fields (when (seq field-ids)- (t2/hydrate (t2/select :model/Field :id [:in (set field-ids)]) :table))+ (t2/hydrate (parameters.db/fields (set field-ids)) :table)){normal-fields falseadvanced-fields true} (group-by requires-advanced-field-value? fields)](merge@@ -145,14 +145,13 @@advanced-field-value? (not= hash-input {:field-id (u/the-id field)})](if advanced-field-value?(let [hash-key (str (hash hash-input))- select-kvs {:field_id (:id field) :type :advanced :hash_key hash-key}- fv (app-db/select-or-insert! :model/FieldValues select-kvs- #(prepare-advanced-field-values field hash-key constraints))]+ fv (parameters.db/find-or-insert-advanced-field-values!+ (:id field) hash-key #(prepare-advanced-field-values field hash-key constraints))];; If it's expired, delete then try to re-create it(if (some-> fv field-values/advanced-field-values-expired?)(do;; It's possible another process has already recalculated this, but spurious recalculations are OK.- (t2/delete! :model/FieldValues :id (:id fv))+ (parameters.db/delete-field-values! (:id fv))(recur field constraints))fv))(field-values/get-or-create-full-field-values! field)))))diff --git a/src/metabase/parameters/params.clj b/src/metabase/parameters/params.cljindex c3a23890c16..e15a5fa959c 100644--- a/src/metabase/parameters/params.clj+++ b/src/metabase/parameters/params.clj@@ -13,7 +13,6 @@[clojure.set :as set][malli.error :as me][medley.core :as m]- [metabase.app-db.core :as app-db][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -22,6 +21,7 @@[metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.schema.parameter :as lib.schema.parameter][metabase.lib.schema.template-tag :as lib.schema.template-tag]+ [metabase.parameters.db :as parameters.db][metabase.parameters.schema :as parameters.schema][metabase.util :as u][metabase.util.log :as log]@@ -121,10 +121,7 @@cases where more than one name Field exists for a Table, this just adds the first one it finds."[fields](when-let [table-ids (seq (map :table_id fields))]- (m/index-by :table_id (-> (t2/select (into [:model/Field] param-field-columns)- :table_id [:in table-ids]- :semantic_type (app-db/isa :type/Name)- :active true)+ (m/index-by :table_id (-> (parameters.db/active-name-fields-for-tables param-field-columns table-ids);; run [[metabase.lib.field/infer-has-field-values]] on these Fields so their values of;; `has_field_values` will be consistent with what the FE expects. (e.g. we'll return;; `:list` instead of `:auto-list`.)@@ -193,10 +190,8 @@[param-id->field-ids :- [:maybe [:map-of ::lib.schema.parameter/id [:set ::lib.schema.id/field]]]](let [field-ids (into #{} cat (vals param-id->field-ids))field-id->field (when (seq field-ids)- (m/index-by :id (-> (t2/select (into [:model/Field] param-field-columns) :id [:in field-ids])- (t2/hydrate :has_field_values :name_field- [:target :has_field_values :name_field]- [:dimensions [:human_readable_field :has_field_values]])+ (m/index-by :id (-> (parameters.db/fields-with-columns param-field-columns field-ids)+ (t2/hydrate :has_field_values :name_field [:target :has_field_values :name_field] [:dimensions [:human_readable_field :has_field_values]])remove-dimensions-nonpublic-columns)))](->> param-id->field-ids(m/map-vals #(into [] (keep field-id->field) %)))))diff --git a/src/metabase/permissions/db.clj b/src/metabase/permissions/db.cljnew file mode 100644index 00000000000..793580e141f--- /dev/null+++ b/src/metabase/permissions/db.clj@@ -0,0 +1,689 @@+(ns metabase.permissions.db+ "Application database queries for the permissions module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods,+ and transactions."+ (:require+ [metabase.permissions.schema :as permissions.schema]+ [metabase.premium-features.core :as premium-features]+ [metabase.settings.core :as setting]+ [metabase.util :as u]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++;;; --------------------------------------------- DataPermissions ---------------------------------------------++(defn- perm-rows-query-base+ "The FROM/JOIN/WHERE shared by every rank-rows query below: one user's groups' rows for every permission type,+ excluding rows for deactivated tables. `db-ids` of nil means every database."+ [user-id db-ids]+ ^:allow-subquery {:from [[(t2/table-name :model/PermissionsGroupMembership) :pgm]]+ :join [[(t2/table-name :model/PermissionsGroup) :pg] [:= :pg.id :pgm.group_id]+ [(t2/table-name :model/DataPermissions) :p] [:= :p.group_id :pg.id]]+ :left-join [[(t2/table-name :model/Table) :mt] [:= :mt.id :p.table_id]]+ :where [:and+ [:= :pgm.user_id user-id]+ (when (seq db-ids)+ [:in :p.db_id db-ids])+ [:or+ [:= :p.table_id nil]+ [:= :mt.active true]]]})++(def ^:private value-rank-case+ "A HoneySQL CASE expression mapping a data_permissions row's (perm_type, perm_value) to the value's rank in its+ permission type's ordering — 0 = most permissive. MIN/MAX aggregates of this rank are what let SQL collapse+ groups, tables and duplicate values."+ (into [:case]+ cat+ (for [[perm-type {:keys [values]}] permissions.schema/data-permissions+ [i v] (map-indexed vector values)]+ [[:and+ [:= :p.perm_type (u/qualified-name perm-type)]+ [:= :p.perm_value (u/qualified-name v)]]+ [:inline i]])))++(def ^:private db-row-rank-case+ "[[value-rank-case]] but only for database-level rows — NULL for rows that name a table, so MIN/MAX ignore them."+ [:case [:= :p.table_id nil] value-rank-case :else nil])++(def ^:private table-level-case+ "0 for a database-level row, 1 for a table-level row."+ [:case [:= :p.table_id nil] [:inline 0] :else [:inline 1]])++(defn database-permission-rank-rows+ "For each `(perm-type, db-id)` of the DataPermissions rows of the User with `user-id`'s groups (narrowed to+ `db-ids`, or every database when nil), the `[min max]` value rank pairs needed to reconstruct the `:database`,+ `:every-table`, and `:any-table` whole-database permission values."+ [user-id db-ids]+ (let [per-group (-> (perm-rows-query-base user-id db-ids)+ (assoc :select [:p.perm_type :p.db_id :p.group_id+ [[:min value-rank-case] :gmin]+ [[:max value-rank-case] :gmax]+ [[:min db-row-rank-case] :dbmin]+ [[:max db-row-rank-case] :dbmax]]+ :group-by [:p.perm_type :p.db_id :p.group_id]))]+ (t2/query {:select [:i.perm_type :i.db_id+ [[:min :i.gmin] :any_mn] [[:max :i.gmax] :any_mx]+ [[:min :i.gmax] :every_mn] [[:max :i.gmax] :every_mx]+ [[:min :i.dbmin] :db_mn] [[:max :i.dbmax] :db_mx]]+ :from [[per-group :i]]+ :group-by [:i.perm_type :i.db_id]})))++(defn schema-permission-rank-rows+ "For each `(perm-type, db-id, schema-name, table-level)` of the DataPermissions rows of the User with `user-id`'s+ groups (narrowed to `db-ids`, or every database when nil), the `[min max]` value rank pair."+ [user-id db-ids]+ (t2/query (assoc (perm-rows-query-base user-id db-ids)+ :select [:p.perm_type :p.db_id :p.schema_name+ [table-level-case :table_level]+ [[:min value-rank-case] :mn]+ [[:max value-rank-case] :mx]]+ :group-by [:p.perm_type :p.db_id :p.schema_name table-level-case])))++(defn table-permission-rank-rows+ "For each `(perm-type, db-id, table-id)` of the table-granular DataPermissions rows of the User with `user-id`'s+ groups, the `[min max]` value rank pair. Scoped to `table-ids` when given (ignoring `db-ids`), otherwise to+ `db-ids` (or every database when both are nil)."+ [user-id db-ids table-ids]+ (t2/query (-> (perm-rows-query-base user-id (when-not (seq table-ids) db-ids))+ (assoc :select [:p.perm_type :p.db_id :p.table_id+ [[:min value-rank-case] :mn]+ [[:max value-rank-case] :mx]]+ :group-by [:p.perm_type :p.db_id :p.table_id])+ (update :where conj [:not= :p.table_id nil])+ (cond-> (seq table-ids) (update :where conj [:in :p.table_id table-ids])))))++(defn schema-permission-rank-pair+ "The `[min max]` value rank pair summarizing the DataPermissions rows of the User with `user-id`'s groups for+ `perm-type` on the Database with `database-id`, restricted to rows naming the schema `schema-name` or no schema at+ all (database-level rows), or nil when there are no matching rows."+ [user-id perm-type database-id schema-name]+ (let [per-group (-> (perm-rows-query-base user-id [database-id])+ (assoc :select [:p.group_id [[:max value-rank-case] :gmax]]+ :group-by [:p.group_id])+ (update :where conj [:= :p.perm_type (u/qualified-name perm-type)])+ (update :where conj [:or+ [:= :p.table_id nil]+ [:= :p.schema_name schema-name]]))]+ (first (t2/query {:select [[[:min :i.gmax] :mn] [[:max :i.gmax] :mx]]+ :from [[per-group :i]]}))))++(defn table-permission-values-for-groups+ "The set of `perm-type` values `group-ids` hold for the Table with `table-id` or for its whole Database."+ [group-ids perm-type database-id table-id]+ (t2/select-fn-set :value :model/DataPermissions+ {:select [[:p.perm_value :value]]+ :from [[:data_permissions :p]]+ :where [:and+ [:in :p.group_id group-ids]+ [:= :p.perm_type perm-type]+ [:= :p.db_id database-id]+ [:or+ [:= :table_id table-id]+ [:= :table_id nil]]]}))++(defn user-data-permissions+ "The permission type, group, value, database, and table of every DataPermissions row of the groups the User with+ `user-id` belongs to, optionally narrowed to `database-id` and/or `perm-type`."+ [user-id database-id perm-type]+ (t2/select :model/DataPermissions+ {:select [[:p.perm_type :perm-type]+ [:p.group_id :group-id]+ [:p.perm_value :value]+ [:p.db_id :db-id]+ [:p.table_id :table-id]]+ :from [[:permissions_group_membership :pgm]]+ :join [[:permissions_group :pg] [:= :pg.id :pgm.group_id]+ [:data_permissions :p] [:= :p.group_id :pg.id]]+ :where [:and+ [:= :pgm.user_id user-id]+ (when database-id [:= :db_id database-id])+ (when perm-type [:= :perm_type (u/qualified-name perm-type)])]}))++(defn data-permissions-for-groups-and-databases+ "The DataPermissions of `group-ids` on the Databases with `database-ids`."+ [group-ids database-ids]+ (t2/select :model/DataPermissions :group_id [:in group-ids] :db_id [:in database-ids]))++(defn database-level-permission+ "The database-level `perm-type` DataPermissions row of the group with `group-id` on the Database with+ `database-id`, or nil."+ [perm-type group-id database-id]+ (t2/select-one :model/DataPermissions+ {:where [:and+ [:= :perm_type perm-type]+ [:= :group_id group-id]+ [:= :db_id database-id]+ [:= :table_id nil]]}))++(defn database-level-permissions+ "The database-level DataPermissions rows of `perm-types` for `group-ids` on the Database with `database-id`."+ [database-id group-ids perm-types]+ (t2/select :model/DataPermissions+ {:where [:and [:= :db_id database-id] [:= :table_id nil]+ [:in :group_id group-ids] [:in :perm_type perm-types]]}))++(defn distinct-table-level-permission-values+ "The distinct group, permission type, schema, and value combinations of the table-level DataPermissions rows of+ `perm-types` for `group-ids` on the Database with `database-id`."+ [database-id group-ids perm-types]+ (t2/select :model/DataPermissions+ {:select-distinct [:group_id :perm_type :schema_name :perm_value]+ :where [:and [:= :db_id database-id] [:not= :table_id nil]+ [:in :group_id group-ids] [:in :perm_type perm-types]]}))++(defn distinct-database-permission-values-for-group+ "The distinct database, permission type, and value combinations of the DataPermissions rows of the group with+ `group-id`."+ [group-id]+ (t2/select :model/DataPermissions+ {:select-distinct [:db_id :perm_type :perm_value]+ :where [:= :group_id group-id]}))++(defn other-table-permission-values+ "The distinct `perm-type` values of the group with `group-id` on tables of the Database with `database-id` other+ than `table-ids`."+ [group-id database-id perm-type table-ids]+ (t2/query {:select-distinct [:perm_value]+ :from [(t2/table-name :model/DataPermissions)]+ :where [:and+ [:= :group_id group-id]+ [:= :db_id database-id]+ [:= :perm_type perm-type]+ [:not= :table_id nil]+ [:not [:in :table_id table-ids]]]}))++(defn table-permission-ids+ "The IDs of the `perm-type` DataPermissions rows of the group with `group-id` on the Tables with `table-ids`."+ [perm-type group-id table-ids]+ (t2/select [:model/DataPermissions :id]+ {:where [:and+ [:= :perm_type perm-type]+ [:= :group_id group-id]+ [:in :table_id table-ids]]}))++(defn non-audit-permission-values-for-groups+ "The distinct group, permission type, and value combinations of the DataPermissions rows of `group-ids` for+ `perm-types`, excluding rows on the audit Database."+ [group-ids perm-types]+ (t2/query {:select-distinct [:group_id :perm_type :perm_value]+ :from [[(t2/table-name :model/DataPermissions)]]+ :where [:and+ [:in :group_id group-ids]+ [:in :perm_type perm-types]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[(t2/table-name :model/Database) :audit_db]]+ :where [:and+ [:= :audit_db.is_audit true]+ [:= :audit_db.id :data_permissions.db_id]]}]]]}))++(defn insert-data-permissions!+ "Insert the DataPermissions `rows`."+ [rows]+ (t2/insert! :model/DataPermissions rows))++(defn delete-data-permissions!+ "Delete the DataPermissions with `ids`."+ [ids]+ (t2/delete! :model/DataPermissions :id [:in ids]))++;;; ----------------------------------------------- Permissions -----------------------------------------------++(defn group-ids-with-permission-objects+ "The set of group IDs holding a Permissions row for one of `objects`."+ [objects]+ (t2/select-fn-set :group_id :model/Permissions {:where [:in :object objects]}))++(defn- related-permission-objects-where+ [group-id path also-under-paths]+ [:and+ [:= :group_id group-id]+ (into [:or [:like path (h2x/concat :object (h2x/literal "%"))]]+ (map (fn [path-form] [:like :object (str path-form "%")]))+ also-under-paths)])++(defn related-permission-objects+ "The Permissions objects held by the group with `group-id` that are ancestors or descendants of `path` (also+ checking each of `also-under-paths`, e.g. a v2-equivalent path)."+ [group-id path also-under-paths]+ (t2/select-fn-set :object :model/Permissions+ {:where (related-permission-objects-where group-id path also-under-paths)}))++(defn delete-related-permissions!+ "Delete the Permissions rows held by the group with `group-id` that are ancestors or descendants of `path` (also+ checking each of `also-under-paths`, e.g. a v2-equivalent path)."+ [group-id path also-under-paths]+ (t2/delete! :model/Permissions+ {:where (related-permission-objects-where group-id path also-under-paths)}))++(defn insert-permissions!+ "Insert the Permissions `rows`."+ [rows]+ (t2/insert! :model/Permissions rows))++;;; --------------------------------------------- PermissionsGroup ---------------------------------------------++(defn magic-group+ "The ID, name, and type of the magic PermissionsGroup of `magic-group-type`, or nil."+ [magic-group-type]+ (t2/select-one [:model/PermissionsGroup :id :name :magic_group_type] :magic_group_type magic-group-type))++(defn group-by-magic-type+ "The PermissionsGroup of `magic-group-type`, or nil."+ [magic-group-type]+ (t2/select-one :model/PermissionsGroup :magic_group_type magic-group-type))++(defn group-id-by-magic-type+ "The ID of the PermissionsGroup of `magic-group-type`, or nil."+ [magic-group-type]+ (t2/select-one-pk :model/PermissionsGroup :magic_group_type magic-group-type))++(defn group-exists-with-lower-name?+ "Whether a PermissionsGroup whose lower-cased name is `lower-name` exists."+ [lower-name]+ (t2/exists? :model/PermissionsGroup :%lower.name lower-name))++(defn groups-except-magic-type+ "The PermissionsGroups other than the magic group of `magic-group-type`."+ [magic-group-type]+ (t2/select :model/PermissionsGroup :magic_group_type [:not= magic-group-type]))++(defn non-magic-groups+ "The PermissionsGroups that are not magic groups."+ []+ (t2/select :model/PermissionsGroup {:where [:= :magic_group_type nil]}))++(defn tenant-group?+ "Whether the PermissionsGroup with `group-id` is a tenant group."+ [group-id]+ (t2/select-one-fn :is_tenant_group :model/PermissionsGroup :id group-id))++(defn tenant-group-ids+ "The IDs of every tenant PermissionsGroup."+ []+ (t2/select-pks-set :model/PermissionsGroup :is_tenant_group true))++(defn group-tenant-flags+ "A map of group ID to `:is_tenant_group` for `group-ids`."+ [group-ids]+ (t2/select-pk->fn :is_tenant_group [:model/PermissionsGroup :id :is_tenant_group] :id [:in group-ids]))++(defn group-names-like+ "The set of PermissionsGroup names matching the SQL `pattern`."+ [pattern]+ (t2/select-fn-set :name :model/PermissionsGroup :name [:like pattern]))++(defn group-members+ "The active Users in the PermissionsGroups with `group-ids`, with the optional extra `group-manager-column`."+ [group-ids group-manager-column]+ (t2/select :model/User {:select [:u.id+ [:u.id :user_id]+ :u.first_name+ :u.last_name+ :u.email+ :u.is_superuser+ :u.type+ :pgm.group_id+ [:pgm.id :membership_id]+ group-manager-column]+ :from [[:core_user :u]]+ :left-join [[:permissions_group_membership :pgm] [:= :u.id :pgm.user_id]]+ :where [:and+ [:= :u.is_active true]+ [:in :pgm.group_id group-ids]]+ :order-by [[[:lower :u.first_name] :asc]+ [[:lower :u.last_name] :asc]]}))++(defn insert-group!+ "Insert `group` and return the new instance."+ [group]+ (t2/insert-returning-instance! :model/PermissionsGroup group))++(defn update-group!+ "Apply `changes` to the PermissionsGroup with `group-id`."+ [group-id changes]+ (t2/update! :model/PermissionsGroup group-id changes))++;;; ---------------------------------------- PermissionsGroupMembership ----------------------------------------++(defn- insert-group-memberships-from-mapping-query+ [user-id-group-id->is-group-manager?]+ {:insert-into [[:permissions_group_membership [:group_id :user_id :is_group_manager]]+ ^:allow-subquery+ {:select [:g.id :u.id [(into [:case]+ (mapcat (fn [[[user-id group-id] is-group-manager?]]+ [[[:and+ [:= :u.id user-id]+ [:= :g.id group-id]]]+ is-group-manager?])+ user-id-group-id->is-group-manager?))]]+ :from [[:permissions_group :g]]+ :join [[:core_user :u] (into [:or]+ (for [[[user-id group-id] _] user-id-group-id->is-group-manager?]+ [:and+ [:= :u.id user-id]+ [:= :g.id group-id]+ [:=+ :g.is_tenant_group+ [:not= :u.tenant_id nil]]]))]}]})++(defn insert-group-memberships-from-mapping!+ "Insert a PermissionsGroupMembership (with `is_group_manager`) for each `[user-id group-id]` pair in+ `user-id-group-id->is-group-manager?`, matching Users to Groups on tenant status; returns the number of rows+ inserted."+ [user-id-group-id->is-group-manager?]+ (t2/query-one (insert-group-memberships-from-mapping-query user-id-group-id->is-group-manager?)))++(defn group-membership-count+ "The number of memberships of the PermissionsGroup with `group-id`."+ [group-id]+ (t2/count :model/PermissionsGroupMembership :group_id group-id))++(defn other-active-member-count+ "The number of active Users other than `user-id` in the PermissionsGroup with `group-id`."+ [group-id user-id]+ (t2/count :model/PermissionsGroupMembership+ {:join [[:core_user :user] [:= :user.id :user_id]]+ :where [:and+ [:= :group_id group-id]+ [:= :user.is_active true]+ [:not= :user.id user-id]]}))++(defn memberships-for-user+ "The PermissionsGroupMemberships of the User with `user-id`."+ [user-id]+ (t2/select :model/PermissionsGroupMembership :user_id user-id))++(defn memberships-for-user-in-groups+ "The PermissionsGroupMemberships of the User with `user-id` in the groups with `group-ids`."+ [user-id group-ids]+ (t2/select :model/PermissionsGroupMembership :user_id user-id :group_id [:in group-ids]))++(defn memberships-for-group+ "The PermissionsGroupMemberships of the PermissionsGroup with `group-id`."+ [group-id]+ (t2/select :model/PermissionsGroupMembership :group_id group-id))++(defn delete-memberships-for-user!+ "Delete the PermissionsGroupMemberships of the User with `user-id`."+ [user-id]+ (t2/delete! :model/PermissionsGroupMembership :user_id user-id))++(defn delete-memberships-for-user-in-groups!+ "Delete the PermissionsGroupMemberships of the User with `user-id` in the groups with `group-ids`."+ [user-id group-ids]+ (t2/delete! :model/PermissionsGroupMembership :user_id user-id :group_id [:in group-ids]))++(defn delete-memberships-for-group!+ "Delete the PermissionsGroupMemberships of the PermissionsGroup with `group-id`."+ [group-id]+ (t2/delete! :model/PermissionsGroupMembership :group_id group-id))++;;; ------------------------------------------------ Revisions ------------------------------------------------++(defn latest-permissions-revision-id+ "The highest ID of any PermissionsRevision, or nil."+ []+ (:id (t2/select-one [:model/PermissionsRevision [:%max.id :id]])))++(defn latest-collection-permission-graph-revision-id+ "The highest ID of any CollectionPermissionGraphRevision, or nil."+ []+ (:id (t2/select-one [:model/CollectionPermissionGraphRevision [:%max.id :id]])))++(defn latest-application-permissions-revision-id+ "The highest ID of any ApplicationPermissionsRevision, or nil."+ []+ (:id (t2/select-one [:model/ApplicationPermissionsRevision [:%max.id :id]])))++(defn insert-collection-permission-graph-revision!+ "Insert `revision` into CollectionPermissionGraphRevision."+ [revision]+ (t2/insert! :model/CollectionPermissionGraphRevision revision))++(defn insert-collection-permission-graph-revision-returning-instance!+ "Insert `revision` into CollectionPermissionGraphRevision and return the new instance."+ [revision]+ (first (t2/insert-returning-instances! :model/CollectionPermissionGraphRevision revision)))++(defn insert-permissions-revision-returning-instance!+ "Insert `revision` into PermissionsRevision and return the new instance."+ [revision]+ (first (t2/insert-returning-instances! :model/PermissionsRevision revision)))++(defn insert-application-permissions-revision-returning-instance!+ "Insert `revision` into ApplicationPermissionsRevision and return the new instance."+ [revision]+ (first (t2/insert-returning-instances! :model/ApplicationPermissionsRevision revision)))++(defn update-collection-graph-revision!+ "Apply `changes` to the CollectionPermissionGraphRevision with `revision-id`."+ [revision-id changes]+ (t2/update! :model/CollectionPermissionGraphRevision revision-id changes))++;;; ----------------------------------------------- Collections -----------------------------------------------++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn personal-or-descendant-collection-ids+ "The IDs among `collection-ids` that are personal Collections, or descendants of one."+ [collection-ids]+ (t2/select-pks-set :model/Collection+ {:where [:and+ [:in :id collection-ids]+ [:or [:not= :personal_owner_id nil]+ [:exists ^:allow-subquery+ {:select [1]+ :from [[:collection :pc]]+ :where [:and+ [:not= :pc.personal_owner_id nil]+ [:like :collection.location+ [:concat "/" :pc.id "/%"]]]}]]]}))++(defn collection-ids-in-other-namespace+ "The IDs among `collection-ids` that do not belong to `namespace` (nil meaning the default namespace)."+ [collection-ids namespace]+ (t2/select-pks-set :model/Collection+ {:where [:and [:in :id collection-ids]+ (cond->> [[:not= :namespace (some-> namespace name)]]+ (nil? namespace) (into [:and [:not= :namespace "analytics"]])+ (some? namespace) (into [:or [:= :namespace nil]]))]}))++(defn library-collection-ids+ "The IDs of the library Collections."+ []+ (t2/select-pks-set :model/Collection :type [:in ["library" "library-data" "library-metrics"]]))++(defn namespace-clause+ "Honey SQL clause to filter `namespace-keyword` by `namespace-val`, also matching the audit-app and tenant+ namespaces when applicable."+ [namespace-keyword namespace-val & [include-tenant-namespaces?]]+ [:or+ [:= namespace-keyword namespace-val]+ (when (and (nil? namespace-val)+ (premium-features/enable-audit-app?))+ [:= namespace-keyword "analytics"])+ (when (and include-tenant-namespaces? (nil? namespace-val) (setting/get :use-tenants))+ [:= namespace-keyword "shared-tenant-collection"])+ (when (and include-tenant-namespaces? (nil? namespace-val) (setting/get :use-tenants))+ [:= namespace-keyword "tenant-specific"])])++(defn collection-graph-rows+ "Reducible group/collection/writable/readable rows of the collection permissions graph for `collection-namespace`,+ restricted to `ids-without-root` (or every Collection when empty) and `group-ids` (or every group when empty).+ `include-root?` controls whether the root-collection rows are included; `admin-group-id` is the id of the+ Administrators group, which implicitly has write access to every Collection."+ [collection-namespace include-root? root-object ids-without-root group-ids admin-group-id]+ (t2/reducible-query+ {:with [[:eligible_collections+ ^:allow-subquery+ {:select [:id]+ :from [:collection]+ :where [:and+ [:or [:= :type nil] [:not= :type "trash"]]+ (namespace-clause :namespace (u/qualified-name collection-namespace))+ [:not :archived]+ [:= :personal_owner_id nil]+ (when (seq ids-without-root)+ [:in :id ids-without-root])+ [:not [:exists ^:allow-subquery+ {:select [1]+ :from [[:collection :pc]]+ :where [:and+ [:not= :pc.personal_owner_id nil]+ [:like :collection.location+ [:concat "/" :pc.id "/%"]]]}]]]}]+ [:relevant_permissions+ ^:allow-subquery+ {:select [:group_id :collection_id :perm_value]+ :from [:permissions]+ :where (into [:and+ [:= :perm_type "perms/collection-access"]+ [:not= :collection_id nil]]+ (when (seq group-ids)+ [[:in :group_id group-ids]]))}]]+ :union-all+ [;; Query 1: Root collection permissions, exclude this query if collection-ids are supplied+ ;; and :root is not present in that collection+ ^:allow-subquery+ {:select [[:pg.id :group_id]+ [nil :collection_id]+ [[:max [:case [:= :p.object root-object]+ [:inline 1]+ :else [:inline 0]]] :writable]+ [[:max [:case [:= :p.object (str root-object "read/")]+ [:inline 1]+ :else [:inline 0]]] :readable]]+ :from [[:permissions_group :pg]]+ :join [[:permissions :p] [:and+ [:= :p.group_id :pg.id]+ [:or [:= :p.object root-object]+ [:= :p.object (str root-object "read/")]]]]+ :where (into [:and [:inline include-root?]]+ (when (seq group-ids)+ [[:in :pg.id group-ids]]))+ :group-by [:pg.id]}+ ;; Query 2: Regular collection permissions+ ^:allow-subquery+ {:select [[:pg.id :group_id]+ [:c.id :collection_id]+ [[:max [:case [:= :p.perm_value "read-and-write"]+ [:inline 1]+ :else [:inline 0]]] :writable]+ [[:max [:case [:or [:= :p.perm_value "read-and-write"]+ [:= :p.perm_value "read"]]+ [:inline 1]+ :else [:inline 0]]] :readable]]+ :from [[:permissions_group :pg]]+ :join [[:relevant_permissions :p] [:= :p.group_id :pg.id]+ [:eligible_collections :c] [:= :p.collection_id :c.id]]+ :where [:not= :c.id nil]+ :group-by [:pg.id :c.id]}+ ;; Query 3: The Administrators group has write access to all collections+ ;; but does not have any explicit permissions.+ ^:allow-subquery+ {:select [[admin-group-id :group_id]+ [:c.id :collection_id]+ [[:inline 1] :writable]+ [[:inline 1] :readable]]+ :from [[:eligible_collections :c]]}]}))++;;; ------------------------------------------------- Users -------------------------------------------------++(defn user-superuser?+ "Whether the User with `user-id` is a superuser."+ [user-id]+ (t2/select-one-fn :is_superuser :model/User :id user-id))++(defn user-data-analyst?+ "Whether the User with `user-id` is a data analyst."+ [user-id]+ (t2/select-one-fn :is_data_analyst :model/User :id user-id))++(defn user-tenant-ids+ "A map of User ID to `:tenant_id` for `user-ids`."+ [user-ids]+ (t2/select-pk->fn :tenant_id [:model/User :id :tenant_id] :id [:in user-ids]))++(defn earliest-user-join-date+ "The earliest `date_joined` of any User, or nil."+ []+ (:min (t2/select-one [:model/User [:%min.date_joined :min]])))++(defn update-user!+ "Apply `changes` to the User with `user-id`."+ [user-id changes]+ (t2/update! :model/User user-id changes))++(defn update-users!+ "Apply `changes` to the Users with `user-ids`."+ [user-ids changes]+ (t2/update! :model/User :id [:in user-ids] changes))++(defn clear-data-analyst-flags!+ "Unset `is_data_analyst` on every User that has it set."+ []+ (t2/update! :model/User {:is_data_analyst true} {:is_data_analyst false}))++(defn deactivate-active-tenant-users!+ "Deactivate every active tenant User, marking them as deactivated with their tenant."+ []+ (t2/update! :model/User :tenant_id [:not= nil] :is_active true {:is_active false :deactivated_with_tenant true}))++(defn deactivate-all-tenants!+ "Mark every tenant row inactive."+ []+ (t2/query {:update :tenant+ :set {:is_active false}}))++;;; --------------------------------------------- Databases and Tables ---------------------------------------------++(defn non-destination-database-ids+ "The IDs of the Databases that are not routing destinations."+ []+ (t2/select-pks-vec :model/Database :router_database_id nil))++(defn destination-database?+ "Whether the Database with `database-id` is a routing destination."+ [database-id]+ (t2/exists? :model/Database :id database-id :router_database_id [:not= nil]))++(defn table-location+ "The ID, Database ID, and schema of the Table with `table-id`."+ [table-id]+ (t2/select-one [:model/Table :id :db_id :schema] :id table-id))++(defn table-database-id+ "The Database ID of the Table with `table-id`."+ [table-id]+ (t2/select-one-fn :db_id :model/Table table-id))++(defn table-database-ids+ "The ID and Database ID of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :db_id] :id [:in table-ids]))++(defn active-table-locations-for-database+ "The ID, Database ID, and schema of the active Tables of the Database with `database-id`."+ [database-id]+ (t2/select [:model/Table :id :db_id :schema] :db_id database-id :active true))++(defn table-ids-and-schemas-excluding+ "The ID and schema of the Tables of the Database with `database-id` other than `excluded-table-ids`."+ [database-id excluded-table-ids]+ (t2/select [:model/Table :id :schema]+ {:where [:and+ [:= :db_id database-id]+ [:not [:in :id excluded-table-ids]]]}))++(defn field-visibility-info+ "The ID, visibility type, and Table ID of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :visibility_type :table_id] :id [:in field-ids]))++(defn instance-by-id+ "The instance of `model` with `id`, or nil."+ [model id]+ (t2/select-one model :id id))diff --git a/src/metabase/permissions/metric.clj b/src/metabase/permissions/metric.cljindex 864af6e2e58..6e221cfd3c4 100644--- a/src/metabase/permissions/metric.clj+++ b/src/metabase/permissions/metric.clj@@ -9,8 +9,8 @@[metabase.api.common :as api][metabase.lib.metadata :as lib.metadata][metabase.permissions.core :as perms]- [metabase.premium-features.core :refer [defenterprise]]- [toucan2.core :as t2]))+ [metabase.permissions.db :as permissions.db]+ [metabase.premium-features.core :refer [defenterprise]]))(set! *warn-on-reflection* true)@@ -23,8 +23,7 @@(when (seq field-ids)(into {}(map (fn [f] [(:id f) (select-keys f [:visibility_type :table_id])]))- (t2/select [:model/Field :id :visibility_type :table_id]- :id [:in field-ids]))))+ (permissions.db/field-visibility-info field-ids))))(defn- batch-table-db-ids"Batch-fetch db_id for a set of table IDs.@@ -33,8 +32,7 @@(when (seq table-ids)(into {}(map (fn [t] [(:id t) (:db_id t)]))- (t2/select [:model/Table :id :db_id]- :id [:in table-ids]))))+ (permissions.db/table-database-ids table-ids))));;; ------------------------------------------------- Permission Predicates -------------------------------------------------diff --git a/src/metabase/permissions/models/application_permissions_revision.clj b/src/metabase/permissions/models/application_permissions_revision.cljindex 71e2a81a82b..819955dafcd 100644--- a/src/metabase/permissions/models/application_permissions_revision.clj+++ b/src/metabase/permissions/models/application_permissions_revision.clj@@ -1,6 +1,7 @@(ns metabase.permissions.models.application-permissions-revision(:require[metabase.models.interface :as mi]+ [metabase.permissions.db :as permissions.db][metabase.util.i18n :refer [tru]][methodical.core :as methodical][toucan2.core :as t2]))@@ -23,5 +24,5 @@"Return the ID of the newest `ApplicationPermissionsRevision`, or zero if none have been made yet.(This is used by the permissions graph update logic that checks for changes since the original graph was fetched)."[]- (or (:id (t2/select-one [:model/ApplicationPermissionsRevision [:%max.id :id]]))+ (or (permissions.db/latest-application-permissions-revision-id)0))diff --git a/src/metabase/permissions/models/collection/graph.clj b/src/metabase/permissions/models/collection/graph.cljindex 10a2a5653a8..e70f0b5d937 100644--- a/src/metabase/permissions/models/collection/graph.clj+++ b/src/metabase/permissions/models/collection/graph.clj@@ -6,6 +6,7 @@[clojure.set :as set][metabase.api.common :as api][metabase.audit-app.core :as audit]+ [metabase.permissions.db :as permissions.db][metabase.permissions.models.collection-permission-graph-revision :as c-perm-revision][metabase.permissions.models.permissions :as perms][metabase.permissions.models.permissions-group :as perms-group]@@ -23,15 +24,13 @@;; PostgreSQL limits prepared statements to 65,535 bind parameters.(def ^:private max-in-clause-size 20000)-(defn- chunked-select-pks- "Like `t2/select-pks-set` but chunks large ID sets to avoid exceeding the bind parameter limit.- `where-fn` takes a set of IDs and returns a HoneySQL where clause."- [model ids where-fn]+(defn- chunked+ "Applies `f` (a function from a set of IDs to a set of IDs) to `ids`, chunking large ID sets to avoid exceeding the+ bind parameter limit."+ [ids f](if (<= (count ids) max-in-clause-size)- (t2/select-pks-set model {:where (where-fn ids)})- (into #{} (mapcat (fn [chunk]- (t2/select-pks-set model {:where (where-fn (set chunk))})))- (partition-all max-in-clause-size ids))))+ (f (set ids))+ (into #{} (mapcat #(f (set %))) (partition-all max-in-clause-size ids))));;; ---------------------------------------------------- Schemas -----------------------------------------------------@@ -82,80 +81,9 @@(= readable 1) :read:else :none)))accum- (t2/reducible-query- {:with [[:eligible_collections- ^:allow-subquery- {:select [:id]- :from [:collection]- :where [:and- [:or [:= :type nil] [:not= :type "trash"]]- (perms/namespace-clause- :namespace (u/qualified-name collection-namespace))- [:not :archived]- [:= :personal_owner_id nil]- (when (seq ids-without-root)- [:in :id ids-without-root])- [:not [:exists ^:allow-subquery- {:select [1]- :from [[:collection :pc]]- :where [:and- [:not= :pc.personal_owner_id nil]- [:like :collection.location- [:concat "/" :pc.id "/%"]]]}]]]}]- [:relevant_permissions- ^:allow-subquery- {:select [:group_id :collection_id :perm_value]- :from [:permissions]- :where (into [:and- [:= :perm_type "perms/collection-access"]- [:not= :collection_id nil]]- (when (seq group-ids)- [[:in :group_id group-ids]]))}]]- :union-all- [;; Query 1: Root collection permissions, exclude this query if collection-ids are supplied- ;; and :root is not present in that collection- ^:allow-subquery- {:select [[:pg.id :group_id]- [nil :collection_id]- [[:max [:case [:= :p.object root-object]- [:inline 1]- :else [:inline 0]]] :writable]- [[:max [:case [:= :p.object (str root-object "read/")]- [:inline 1]- :else [:inline 0]]] :readable]]- :from [[:permissions_group :pg]]- :join [[:permissions :p] [:and- [:= :p.group_id :pg.id]- [:or [:= :p.object root-object]- [:= :p.object (str root-object "read/")]]]]- :where (into [:and [:inline include-root?]]- (when (seq group-ids)- [[:in :pg.id group-ids]]))- :group-by [:pg.id]}- ;; Query 2: Regular collection permissions- ^:allow-subquery- {:select [[:pg.id :group_id]- [:c.id :collection_id]- [[:max [:case [:= :p.perm_value "read-and-write"]- [:inline 1]- :else [:inline 0]]] :writable]- [[:max [:case [:or [:= :p.perm_value "read-and-write"]- [:= :p.perm_value "read"]]- [:inline 1]- :else [:inline 0]]] :readable]]- :from [[:permissions_group :pg]]- :join [[:relevant_permissions :p] [:= :p.group_id :pg.id]- [:eligible_collections :c] [:= :p.collection_id :c.id]]- :where [:not= :c.id nil]- :group-by [:pg.id :c.id]}- ;; Query 3: The Administrators group has write access to all collections- ;; but does not have any explicit permissions.- ^:allow-subquery- {:select [[(u/the-id (perms-group/admin)) :group_id]- [:c.id :collection_id]- [[:inline 1] :writable]- [[:inline 1] :readable]]- :from [[:eligible_collections :c]]}]})))+ (permissions.db/collection-graph-rows+ collection-namespace include-root? root-object ids-without-root group-ids+ (u/the-id (perms-group/admin)))))(mu/defn graph :- PermissionsGraph"Fetch a sparse graph representing the current permissions status for groups and collections with permissions.@@ -253,36 +181,24 @@revision number, which is used for consistency checks when updating the graph."[current-revision-number](when api/*current-user-id*- (first (t2/insert-returning-instances! :model/CollectionPermissionGraphRevision- :id (inc current-revision-number)- :user_id api/*current-user-id*- :before ""- :after ""))))+ (permissions.db/insert-collection-permission-graph-revision-returning-instance!+ {:id (inc current-revision-number)+ :user_id api/*current-user-id*+ :before ""+ :after ""})))(defn fill-revision-details!"Updates perm revision, this is used for logging/auditing purposes, and can be quite expensive, so in practice iscalled after the revision number is updated."[revision-id before changes]- (future (t2/update! :model/CollectionPermissionGraphRevision revision-id {:before before :after changes})))+ (future (permissions.db/update-collection-graph-revision! revision-id {:before before :after changes})))(defn- personal-collection-ids"Return a set of IDs from `collection-ids` that are personal Collections or descendants of personal Collections.These should never appear in permission graphs or be editable via the graph API."[collection-ids](when-let [ids (seq (disj collection-ids :root))]- (chunked-select-pks- :model/Collection ids- (fn [id-set]- [:and- [:in :id id-set]- [:or [:not= :personal_owner_id nil]- [:exists ^:allow-subquery- {:select [1]- :from [[:collection :pc]]- :where [:and- [:not= :pc.personal_owner_id nil]- [:like :collection.location- [:concat "/" :pc.id "/%"]]]}]]]))))+ (chunked ids permissions.db/personal-or-descendant-collection-ids)))(defn- remove-personal-collections-from-graph"Remove any personal collection IDs from the graph. Personal collections cannot be edited via the graph API."@@ -296,13 +212,7 @@[graph collection-ids namespace](let [ids (disj collection-ids :root)other-ns-ids (when (seq ids)- (chunked-select-pks- :model/Collection ids- (fn [id-set]- [:and [:in :id id-set]- (cond->> [[:not= :namespace (some-> namespace name)]]- (nil? namespace) (into [:and [:not= :namespace "analytics"]])- (some? namespace) (into [:or [:= :namespace nil]]))])))]+ (chunked ids #(permissions.db/collection-ids-in-other-namespace % namespace)))](cond-> graph(seq other-ns-ids) (update :groups update-vals #(apply dissoc % other-ns-ids)))))@@ -311,8 +221,7 @@Data Analysts always have full read-write access to library collections."[changes](let [data-analyst-group-id (u/the-id (perms-group/data-analyst))- library-collection-ids (t2/select-pks-set :model/Collection- :type [:in ["library" "library-data" "library-metrics"]])]+ library-collection-ids (permissions.db/library-collection-ids)](when-let [group-changes (get changes data-analyst-group-id)](let [changed-collection-ids (set (keys group-changes))library-changes (set/intersection changed-collection-ids library-collection-ids)]diff --git a/src/metabase/permissions/models/collection_permission_graph_revision.clj b/src/metabase/permissions/models/collection_permission_graph_revision.cljindex d3676bb58b5..393c9cdb719 100644--- a/src/metabase/permissions/models/collection_permission_graph_revision.clj+++ b/src/metabase/permissions/models/collection_permission_graph_revision.clj@@ -1,6 +1,7 @@(ns metabase.permissions.models.collection-permission-graph-revision(:require[metabase.models.interface :as mi]+ [metabase.permissions.db :as permissions.db][methodical.core :as methodical][toucan2.core :as t2]))@@ -18,5 +19,5 @@"Return the ID of the newest `CollectionPermissionGraphRevision`, or zero if none have been made yet.(This is used by the collection graph update logic that checks for changes since the original graph was fetched)."[]- (or (:id (t2/select-one [:model/CollectionPermissionGraphRevision [:%max.id :id]]))+ (or (permissions.db/latest-collection-permission-graph-revision-id)0))diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.cljindex 155e0619be0..87a89013bc2 100644--- a/src/metabase/permissions/models/data_permissions.clj+++ b/src/metabase/permissions/models/data_permissions.clj@@ -9,6 +9,7 @@[metabase.config.core :as config][metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi]+ [metabase.permissions.db :as permissions.db][metabase.permissions.published-tables :as published-tables][metabase.permissions.schema :as permissions.schema][metabase.premium-features.core :refer [defenterprise]]@@ -190,7 +191,8 @@;;; [[with-relevant-permissions-for-user]] and key `:perms` by user ID so we NEVER accidentally use the cache of the;;; wrong user.;;;-;;; All coalescing happens in SQL: each permission value is mapped to its rank (see [[value-rank-case]]) and rows+;;; All coalescing happens in SQL: each permission value is mapped to its rank (see `permissions.db`'s+;;; `value-rank-case`) and rows;;; are aggregated with GROUP BY, so result sets scale with tables/schemas/databases rather than with raw;;; data_permissions row counts (dbs x groups x tables x duplicate values). A bucket's (min, max) rank pair is;;; enough to reconstruct [[coalesce]] exactly (see [[ranks->most-permissive-value]]), and the@@ -201,40 +203,6 @@;;; written, so code that mutates permissions and re-checks them within the same request scope reads pre-write;;; answers, and the caches may observe a concurrent write at different first-load moments.-(defn- perm-rows-query-base- "The FROM/JOIN/WHERE shared by every cache load: one user's groups' rows for every permission type, excluding rows- for deactivated tables. All caches must select from this same row set so they can never answer the same permission- question differently — change the row set here, not in one of the queries. `db-ids` of nil means every database."- [user-id db-ids]- ^:allow-subquery {:from [[(t2/table-name :model/PermissionsGroupMembership) :pgm]]- :join [[(t2/table-name :model/PermissionsGroup) :pg] [:= :pg.id :pgm.group_id]- [(t2/table-name :model/DataPermissions) :p] [:= :p.group_id :pg.id]]- :left-join [[(t2/table-name :model/Table) :mt] [:= :mt.id :p.table_id]]- :where [:and- [:= :pgm.user_id user-id]- (when (seq db-ids)- [:in :p.db_id db-ids])- [:or- [:= :p.table_id nil]- [:= :mt.active true]]]})--(def ^:private value-rank-case- "A HoneySQL CASE expression mapping a data_permissions row's (perm_type, perm_value) to the value's rank in its- permission type's ordering — 0 = most permissive. MIN/MAX aggregates of this rank are what let SQL collapse- groups, tables and duplicate values."- (into [:case]- cat- (for [[perm-type {:keys [values]}] permissions.schema/data-permissions- [i v] (map-indexed vector values)]- [[:and- [:= :p.perm_type (u/qualified-name perm-type)]- [:= :p.perm_value (u/qualified-name v)]]- [:inline i]])))--(def ^:private db-row-rank-case- "[[value-rank-case]] but only for database-level rows — NULL for rows that name a table, so MIN/MAX ignore them."- [:case [:= :p.table_id nil] value-rank-case :else nil])-(defn- ranks->most-permissive-value"Reconstructs [[coalesce]] over a bucket of values from the bucket's `[min-rank max-rank]` pair. Verifiedexhaustively against [[coalesce]] for every permission type and value subset: the most permissive value is the one@@ -329,14 +297,14 @@[user-id](if (= user-id api/*current-user-id*)api/*is-superuser?*- (t2/select-one-fn :is_superuser :model/User :id user-id)))+ (permissions.db/user-superuser? user-id)))(defn is-data-analyst?"Returns true if the given user ID is a data analyst. Avoids a DB query when checking the current user."[user-id](if (= user-id api/*current-user-id*)api/*is-data-analyst?*- (t2/select-one-fn :is_data_analyst :model/User :id user-id)))+ (permissions.db/user-data-analyst? user-id)));;; --------------------------------------------- Database level cache ---------------------------------------------@@ -362,7 +330,7 @@before they coalesce across groups — a user can hold `:unrestricted` on every table without any single groupgranting it on all of them.- All three are aggregations of the same rows (see [[perm-rows-query-base]]), so one query computes all of them, for+ All three are aggregations of the same rows (see `permissions.db`'s `perm-rows-query-base`), so one query computes all of them, forevery database it is asked about, at once. `:db-ids` records which those were: this cache only ever answers for adatabase it actually loaded, so one created later is fetched rather than read as having no permissions.@@ -378,14 +346,7 @@(defn- load-database-perms"Whole-database values for `db-ids`, or for every database when nil."[user-id db-ids]- (let [per-group (-> (perm-rows-query-base user-id db-ids)- (assoc :select [:p.perm_type :p.db_id :p.group_id- [[:min value-rank-case] :gmin]- [[:max value-rank-case] :gmax]- [[:min db-row-rank-case] :dbmin]- [[:max db-row-rank-case] :dbmax]]- :group-by [:p.perm_type :p.db_id :p.group_id]))- value (fn [perm-type mn mx] (when mn (ranks->most-permissive-value perm-type [mn mx])))]+ (let [value (fn [perm-type mn mx] (when mn (ranks->most-permissive-value perm-type [mn mx])))](reduce (fn [m {:keys [perm_type db_id any_mn any_mx every_mn every_mx db_mn db_mx]}](let [perm-type (keyword perm_type)](assoc-in m [perm-type db_id]@@ -393,12 +354,7 @@:every-table (value perm-type every_mn every_mx):any-table (value perm-type any_mn any_mx)}))){}- (t2/query {:select [:i.perm_type :i.db_id- [[:min :i.gmin] :any_mn] [[:max :i.gmax] :any_mx]- [[:min :i.gmax] :every_mn] [[:max :i.gmax] :every_mx]- [[:min :i.dbmin] :db_mn] [[:max :i.dbmax] :db_mx]]- :from [[per-group :i]]- :group-by [:i.perm_type :i.db_id]}))))+ (permissions.db/database-permission-rank-rows user-id db-ids))))(defn- load-database-perms!"Load `db-ids` into [[*db-permission-cache*]] and return the resulting per-user map."@@ -466,19 +422,13 @@(defn- load-schema-permission-perms[user-id db-ids]- (let [table-level-case [:case [:= :p.table_id nil] [:inline 0] :else [:inline 1]]- folded (reduce (fn [m {:keys [perm_type db_id schema_name table_level mn mx]}]+ (let [folded (reduce (fn [m {:keys [perm_type db_id schema_name table_level mn mx]}](if (pos? table_level)(update-in m [(keyword perm_type) db_id :schemas (or schema_name "")]combine-rank-pairs [mn mx])(assoc-in m [(keyword perm_type) db_id :db-level] [mn mx]))){}- (t2/query (assoc (perm-rows-query-base user-id db-ids)- :select [:p.perm_type :p.db_id :p.schema_name- [table-level-case :table_level]- [[:min value-rank-case] :mn]- [[:max value-rank-case] :mx]]- :group-by [:p.perm_type :p.db_id :p.schema_name table-level-case])))]+ (permissions.db/schema-permission-rank-rows user-id db-ids))](into {}(map (fn [[perm-type db-id->folded]][perm-type@@ -540,13 +490,7 @@(assoc-in m [(keyword perm_type) db_id table_id](ranks->most-permissive-value (keyword perm_type) [mn mx]))){}- (t2/query (-> (perm-rows-query-base user-id (when-not (seq table-ids) db-ids))- (assoc :select [:p.perm_type :p.db_id :p.table_id- [[:min value-rank-case] :mn]- [[:max value-rank-case] :mx]]- :group-by [:p.perm_type :p.db_id :p.table_id])- (update :where conj [:not= :p.table_id nil])- (cond-> (seq table-ids) (update :where conj [:in :p.table_id table-ids]))))))+ (permissions.db/table-permission-rank-rows user-id db-ids table-ids)))(defn- merge-table-perms"Merge freshly loaded table permissions into cached ones, unioning the per-database table maps rather than replacing@@ -732,15 +676,7 @@Selecting the schema's table rows and the database-level rows together is what keeps this a single flat aggregate:a database-level row applies to every schema, so restricting to one schema needs no expansion step."[user-id perm-type database-id schema-name]- (let [per-group (-> (perm-rows-query-base user-id [database-id])- (assoc :select [:p.group_id [[:max value-rank-case] :gmax]]- :group-by [:p.group_id])- (update :where conj [:= :p.perm_type (u/qualified-name perm-type)])- (update :where conj [:or- [:= :p.table_id nil]- [:= :p.schema_name schema-name]]))- {:keys [mn mx]} (first (t2/query {:select [[[:min :i.gmax] :mn] [[:max :i.gmax] :mx]]- :from [[per-group :i]]}))]+ (let [{:keys [mn mx]} (permissions.db/schema-permission-rank-pair user-id perm-type database-id schema-name)](when mn [mn mx])))(mu/defn full-schema-permission-for-user :- ::permissions.schema/data-permission-value@@ -908,17 +844,10 @@(when (not= :model/Table (model-by-perm-type perm-type))(throw (ex-info (tru "Permission type {0} is not a table-level permission." perm-type){perm-type (permissions.schema/data-permissions perm-type)})))- (let [perm-values (t2/select-fn-set :value- :model/DataPermissions- {:select [[:p.perm_value :value]]- :from [[:data_permissions :p]]- :where [:and- [:in :p.group_id group-ids]- [:= :p.perm_type (u/qualified-name perm-type)]- [:= :p.db_id database-id]- [:or- [:= :table_id table-id]- [:= :table_id nil]]]})]+ (let [perm-values (permissions.db/table-permission-values-for-groups group-ids+ (u/qualified-name perm-type)+ database-id+ table-id)](or (coalesce perm-type (conj perm-values (get-additional-table-permission! {:db-id database-id :table-id table-id}perm-type)))(least-permissive-value perm-type))))@@ -935,7 +864,7 @@"Returns the graph representing admin permissions for all groups"[& {:keys [db-id perm-type]}];; destination databases are reachable only through their router and never carry permissions of their own- (let [db-ids (if db-id [db-id] (t2/select-pks-vec :model/Database :router_database_id nil))+ (let [db-ids (if db-id [db-id] (permissions.db/non-destination-database-ids))perm-types (if perm-type [perm-type] (keys permissions.schema/data-permissions))](into {} (map (fn [db-id][db-id (into {} (map (fn [perm] [perm (most-permissive-value perm)])@@ -951,19 +880,7 @@[user-id & {:keys [db-id perm-type]}](if (is-superuser? user-id)(admin-permission-graph :db-id db-id :perm-type perm-type)- (let [data-perms (t2/select :model/DataPermissions- {:select [[:p.perm_type :perm-type]- [:p.group_id :group-id]- [:p.perm_value :value]- [:p.db_id :db-id]- [:p.table_id :table-id]]- :from [[:permissions_group_membership :pgm]]- :join [[:permissions_group :pg] [:= :pg.id :pgm.group_id]- [:data_permissions :p] [:= :p.group_id :pg.id]]- :where [:and- [:= :pgm.user_id user-id]- (when db-id [:= :db_id db-id])- (when perm-type [:= :perm_type (u/qualified-name perm-type)])]})+ (let [data-perms (permissions.db/user-data-permissions user-id db-id perm-type)path->perms (group-by (fn [{:keys [db-id perm-type table-id]}](if table-id[db-id perm-type table-id]@@ -1019,7 +936,7 @@"Whether `db-id` is a destination database — one with `router_database_id` set."(mdb/memoize-for-application-db(fn [db-id]- (t2/exists? :model/Database :id db-id :router_database_id [:not= nil]))))+ (permissions.db/destination-database? db-id))))(defn assert-no-destination-db-permissions!"Throws if any row in `perm-rows` targets a destination database — one with `router_database_id`@@ -1103,14 +1020,14 @@;; are ever inserted by a path that bypasses the hook (e.g. t2/query).#_(assert-no-destination-db-permissions! new-perms)(doseq [batched-new-perms (partition-all permission-batch-size new-perms)]- (t2/insert! :model/DataPermissions batched-new-perms)))+ (permissions.db/insert-data-permissions! batched-new-perms)))(defn batch-delete-permissions!"Much like on insert, sometimes we have to delete more permission models than the psql limit of MAX 16-bit parameters.This batches our deletes into groups of `permission-batch-size`."[to-delete-ids](doseq [batched-to-delete-ids (partition-all permission-batch-size to-delete-ids)]- (t2/delete! :model/DataPermissions :id [:in batched-to-delete-ids])))+ (permissions.db/delete-data-permissions! batched-to-delete-ids)))(defn index-database-permissions"Given seqs of `group-ids` and `db-ids`, computes an index of all relevant permissions.@@ -1125,7 +1042,7 @@[group-ids db-ids](when (and (seq group-ids) (seq db-ids))(group-by (juxt :group_id :db_id :perm_type)- (t2/select :model/DataPermissions :group_id [:in group-ids] :db_id [:in db-ids]))))+ (permissions.db/data-permissions-for-groups-and-databases group-ids db-ids))))(mu/defn set-database-permission!"Set a single permission to a specified value for a given group and database. If a permission value already exists@@ -1180,7 +1097,7 @@(let [{:keys [id db_id schema]}(if (map? table)table- (t2/select-one [:model/Table :id :db_id :schema] :id table))]+ (permissions.db/table-location table))]{:perm_type perm-type:group_id group-id:perm_value value@@ -1219,14 +1136,9 @@{:to-delete [] :to-insert []};; If we're setting any table permissions to a value that is different from the database-level permission,;; we need to replace it with individual permission rows for every table in the database instead.- (let [other-new-perms (->> (t2/select [:model/Table :id :schema]- {:where- [:and- [:= :db_id db-id]- ;; We can't filter out *everything* here because- ;; max number of parameters is capped. But we might- ;; as well filter out what we can (conservatively).- [:not [:in :id (take 10000 table-ids)]]]})+ ;; We can't filter out *everything* in the database because the max number of parameters is capped. But we+ ;; might as well filter out what we can (conservatively).+ (let [other-new-perms (->> (permissions.db/table-ids-and-schemas-excluding db-id (take 10000 table-ids))(keep (fn [table];; See above: we filtered out what we could in the database, but if;; the number of tables is large we need to filter them out in@@ -1250,14 +1162,10 @@[group-id db-id perm-type table-ids values new-perms](let [existing-table-values (into #{}(map (comp keyword :perm_value))- (t2/query {:select-distinct [:perm_value]- :from [(t2/table-name :model/DataPermissions)]- :where [:and- [:= :group_id group-id]- [:= :db_id db-id]- [:= :perm_type (u/qualified-name perm-type)]- [:not= :table_id nil]- [:not [:in :table_id table-ids]]]}))]+ (permissions.db/other-table-permission-values group-id+ db-id+ (u/qualified-name perm-type)+ table-ids))](if (and (= (count existing-table-values) 1)(= values existing-table-values));; If all tables would have the same permissions after we update these ones, we can replace all of the table@@ -1266,11 +1174,7 @@group-id db-id perm-type (first values));; Otherwise, just replace the rows for the individual table perm;; only :id is consumed downstream (see [[set-table-permissions-internal!]]), so don't fetch full rows- (let [table-perms-to-delete (t2/select [:model/DataPermissions :id]- {:where [:and- [:= :perm_type (u/qualified-name perm-type)]- [:= :group_id group-id]- [:in :table_id table-ids]]})]+ (let [table-perms-to-delete (permissions.db/table-permission-ids (u/qualified-name perm-type) group-id table-ids)]{:to-delete table-perms-to-delete:to-insert new-perms}))))@@ -1302,13 +1206,7 @@;; implications include `view-data :unrestricted`, and the recursive table-level `view-data`;; call coalesces to that same DB-level row.(apply merge-perm-changes- (if-let [existing-db-perm (t2/select-one :model/DataPermissions- {:where- [:and- [:= :perm_type (u/qualified-name perm-type)]- [:= :group_id group-id]- [:= :db_id db-id]- [:= :table_id nil]]})]+ (if-let [existing-db-perm (permissions.db/database-level-permission (u/qualified-name perm-type) group-id db-id)](handle-existing-db-permission existing-db-permvaluesgroup-id@@ -1352,7 +1250,7 @@(let [table-or-id (first (keys table-perms))db-id (if (map? table-or-id)(:db_id table-or-id)- (t2/select-one-fn :db_id :model/Table table-or-id))]+ (permissions.db/table-database-id table-or-id))](with-cluster-lock {:perm-type (u/qualified-name perm-type):db-id db-id}(set-table-permissions-internal! group-or-id perm-type table-perms))))@@ -1399,11 +1297,8 @@:perm_value perm-value:db_id db-id}));; Regular groups: compute based on All Users group- (let [au-id (t2/select-one-pk :model/PermissionsGroup- :magic_group_type "all-internal-users")- au-perms (t2/select :model/DataPermissions- {:select-distinct [:db_id :perm_type :perm_value]- :where [:= :group_id au-id]})+ (let [au-id (permissions.db/group-id-by-magic-type "all-internal-users")+ au-perms (permissions.db/distinct-database-permission-values-for-group au-id)au-by-db (reduce (fn [acc {:keys [db_id perm_type perm_value]}](update-in acc [db_id perm_type] (fnil conj #{}) perm_value)){}@@ -1446,16 +1341,9 @@;; Batch-fetch distinct (group, perm-type, value) triples — we only need the set of unique values per;; group to find the most restrictive level;all-perms (when-not is-audit- (t2/query {:select-distinct [:group_id :perm_type :perm_value]- :from [[(t2/table-name :model/DataPermissions)]]- :where [:and- [:in :group_id group-ids]- [:in :perm_type ["perms/create-queries" "perms/download-results"]]- [:not [:exists ^:allow-subquery {:select [1]- :from [[(t2/table-name :model/Database) :audit_db]]- :where [:and- [:= :audit_db.is_audit true]- [:= :audit_db.id :data_permissions.db_id]]}]]]}))+ (permissions.db/non-audit-permission-values-for-groups+ group-ids+ ["perms/create-queries" "perms/download-results"]));; Group by (group_id, perm_type) → set of valuesperms-by-grp (when all-perms(reduce (fn [acc {:keys [group_id perm_type perm_value]}]@@ -1522,24 +1410,19 @@for new tables on `db-id`."[db-id group-ids perm-types](let [qn (mapv u/qualified-name perm-types)- db-level (t2/select :model/DataPermissions- {:where [:and [:= :db_id db-id] [:= :table_id nil]- [:in :group_id group-ids] [:in :perm_type qn]]})+ db-level (permissions.db/database-level-permissions db-id group-ids qn);; `schema-vals-idx` only needs the set of distinct perm-values per;; (group, perm-type, schema). Selecting DISTINCT on those four columns;; keeps the result bounded by groups × perm-types × schemas × values;; instead of growing with the table count, which can be millions of;; rows on databases with very many tables (see #76077).- table-level (t2/select :model/DataPermissions- {:select-distinct [:group_id :perm_type :schema_name :perm_value]- :where [:and [:= :db_id db-id] [:not= :table_id nil]- [:in :group_id group-ids] [:in :perm_type qn]]})]+ table-level (permissions.db/distinct-table-level-permission-values db-id group-ids qn)]{:db-id db-id:db-level-idx (into {} (map (juxt (juxt :group_id :perm_type) identity)) db-level):schema-vals-idx (reduce (fn [acc {:keys [group_id perm_type schema_name perm_value]}](update-in acc [group_id perm_type schema_name] (fnil conj #{}) perm_value)){} table-level)- :all-db-tables (t2/select [:model/Table :id :db_id :schema] :db_id db-id :active true)+ :all-db-tables (permissions.db/active-table-locations-for-database db-id):view-data-levels (new-table-view-data-permission-levels db-id group-ids)}))(defn- compute-actual-value@@ -1632,7 +1515,7 @@[table group-perm-defaults](let [table (if (map? table)table- (t2/select-one [:model/Table :id :db_id :schema] :id table))]+ (permissions.db/table-location table))](set-default-table-permissions-bulk! (:db_id table) [[table group-perm-defaults]])))(defenterprise download-perms-leveldiff --git a/src/metabase/permissions/models/permissions.clj b/src/metabase/permissions/models/permissions.cljindex 78097b3bff2..09e664d5100 100644--- a/src/metabase/permissions/models/permissions.clj+++ b/src/metabase/permissions/models/permissions.clj@@ -164,15 +164,14 @@[metabase.audit-app.core :as audit][metabase.config.core :as config][metabase.models.interface :as mi]+ [metabase.permissions.db :as permissions.db][metabase.permissions.models.permissions-group :as perms-group][metabase.permissions.path :as permissions.path][metabase.permissions.user :as permissions.user][metabase.permissions.util :as perms.u][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.remote-sync.core :as remote-sync]- [metabase.settings.core :as setting][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [tru]][metabase.util.log :as log][metabase.util.malli :as mu]@@ -296,10 +295,9 @@[collection-id :- [:maybe ms/PositiveInt]](let [collection-or-root (or collection-id{:metabase.collections.models.collection.root/is-root? true})]- (or (t2/select-fn-set :group_id :model/Permissions- {:where [:in :object- [(permissions.path/collection-read-path collection-or-root)- (permissions.path/collection-readwrite-path collection-or-root)]]})+ (or (permissions.db/group-ids-with-permission-objects+ [(permissions.path/collection-read-path collection-or-root)+ (permissions.path/collection-readwrite-path collection-or-root)])#{})))(doto :perms/use-parent-collection-perms@@ -328,7 +326,7 @@(defmethod mi/can-create? :perms/use-parent-collection-perms[_model m](if-let [collection-id (:collection_id m)]- (mi/can-write? (t2/select-one :model/Collection :id collection-id))+ (mi/can-write? (permissions.db/collection collection-id))(mi/can-write? (var-get (requiring-resolve 'metabase.collections.models.collection/root-collection)))));;; +----------------------------------------------------------------------------------------------------------------+@@ -396,34 +394,23 @@In short, it will delete any permissions that contain `/db/1/schema/` as a prefix, or that themeselves are prefixesfor `/db/1/schema/`.- You can optionally include `other-conditions`, which are anded into the filter clause, to further restrict what is- deleted.-NOTE: This function is meant for internal usage in this namespace only; use one of the other functions like`revoke-data-perms!` elsewhere instead of calling this directly."- [group-or-id :- [:or :map ms/PositiveInt] path :- perms.u/PathSchema & other-conditions]- (let [paths (conj (perms.u/->v2-path path) path)- where {:where (apply list- :and- [:= :group_id (u/the-id group-or-id)]- (into [:or- [:like path (h2x/concat :object (h2x/literal "%"))]]- (map (fn [path-form] [:like :object (str path-form "%")])- paths))- other-conditions)}]- (when-let [revoked (t2/select-fn-set :object :model/Permissions where)]- (log/debug (u/format-color 'red "Revoking permissions for group %d: %s" (u/the-id group-or-id) revoked))- (t2/delete! :model/Permissions where)+ [group-or-id :- [:or :map ms/PositiveInt] path :- perms.u/PathSchema]+ (let [group-id (u/the-id group-or-id)+ paths (conj (perms.u/->v2-path path) path)]+ (when-let [revoked (permissions.db/related-permission-objects group-id path paths)]+ (log/debug (u/format-color 'red "Revoking permissions for group %d: %s" group-id revoked))+ (permissions.db/delete-related-permissions! group-id path paths)(clear-current-user-cached-permissions!))))(defn grant-permissions!"Grant permissions for `group-or-id` and return the inserted permissions. Two-arity grants any arbitrary Permissions `path`."[group-or-id path](try- (t2/insert! :model/Permissions- (map (fn [path-object]- {:group_id (u/the-id group-or-id) :object path-object})- (distinct (conj (perms.u/->v2-path path) path))))+ (permissions.db/insert-permissions! (map (fn [path-object]+ {:group_id (u/the-id group-or-id) :object path-object})+ (distinct (conj (perms.u/->v2-path path) path))))(clear-current-user-cached-permissions!);; on some occasions through weirdness we might accidentally try to insert a key that's already been inserted(catch Throwable e@@ -436,18 +423,9 @@;;;; Audit Permissions helper fns-(defn namespace-clause+(def namespace-clause"SQL clause to filter namespaces depending on if audit app is enabled or not, and if the namespace is the default one."- [namespace-keyword namespace-val & [include-tenant-namespaces?]]- [:or- [:= namespace-keyword namespace-val]- (when (and (nil? namespace-val)- (premium-features/enable-audit-app?))- [:= namespace-keyword "analytics"])- (when (and include-tenant-namespaces? (nil? namespace-val) (setting/get :use-tenants))- [:= namespace-keyword "shared-tenant-collection"])- (when (and include-tenant-namespaces? (nil? namespace-val) (setting/get :use-tenants))- [:= namespace-keyword "tenant-specific"])])+ permissions.db/namespace-clause)(defn can-read-via-parent-collection?"Read permission for rows whose read policy is a pure function of `:collection_id` and current user perms.@@ -532,7 +510,7 @@`(do(defmethod mi/can-read? ~target([instance#] (can-read-via-parent-collection? (:collection_id instance#)))- ([_# pk#] (mi/can-read? (t2/select-one ~target :id pk#))))+ ([_# pk#] (mi/can-read? (permissions.db/instance-by-id ~target pk#))))(register-collection-id-only-read-method! ~target (get-method mi/can-read? ~target)))(string? target)@@ -577,7 +555,7 @@[collection-or-id](if (map? collection-or-id)collection-or-id- (t2/select-one :model/Collection :id (u/the-id collection-or-id))))+ (permissions.db/collection (u/the-id collection-or-id))))(mu/defn- check-is-modifiable-collection"Check whether `collection-or-id` refers to a collection that can have permissions modified. Personal collections, thediff --git a/src/metabase/permissions/models/permissions_group.clj b/src/metabase/permissions/models/permissions_group.cljindex dac50c8f5e2..11cee32a358 100644--- a/src/metabase/permissions/models/permissions_group.clj+++ b/src/metabase/permissions/models/permissions_group.clj@@ -11,6 +11,7 @@[clojure.set :as set][metabase.app-db.core :as mdb][metabase.models.interface :as mi]+ [metabase.permissions.db :as permissions.db][metabase.permissions.models.data-permissions :as data-perms][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting]@@ -38,7 +39,7 @@(defn- magic-group [magic-group-type](mdb/memoize-for-application-db(fn []- (u/prog1 (t2/select-one [:model/PermissionsGroup :id :name :magic_group_type] :magic_group_type magic-group-type)+ (u/prog1 (permissions.db/magic-group magic-group-type);; normally it is impossible to delete the magic [[all-users]] or [[admin]] Groups -- see;; [[check-not-magic-group]]. This assertion is here to catch us if we do something dumb when hacking on;; the MB code -- to make tests fail fast. For that reason it's not i18n'ed.@@ -84,8 +85,7 @@"Does a `PermissionsGroup` with `group-name` exist in the DB? (case-insensitive)"^Boolean [group-name]{:pre [((some-fn keyword? string?) group-name)]}- (t2/exists? :model/PermissionsGroup- :%lower.name (u/lower-case-en (name group-name))))+ (permissions.db/group-exists-with-lower-name? (u/lower-case-en (name group-name))))(defn- check-name-not-already-taken[group-name]@@ -119,7 +119,7 @@(defn- set-default-permission-values]+ (let [db-ids (permissions.db/non-destination-database-ids)](data-perms/set-default-group-permissions! group db-ids (not (:is_tenant_group group))))))(t2/define-after-insert :model/PermissionsGroup@@ -154,42 +154,27 @@[_model k groups](mi/instances-with-hydrated-datagroups k- #(group-by :group_id (t2/select :model/User {:select [:u.id- ;; user_id is for legacy reasons, we should remove it- [:u.id :user_id]- :u.first_name- :u.last_name- :u.email- :u.is_superuser- :u.type- :pgm.group_id- [:pgm.id :membership_id]- (when (premium-features/enable-advanced-permissions?)- [:pgm.is_group_manager :is_group_manager])]- :from [[:core_user :u]]- :left-join [[:permissions_group_membership :pgm] [:= :u.id :pgm.user_id]]- :where [:and- [:= :u.is_active true]- [:in :pgm.group_id (map :id groups)]]- :order-by [[[:lower :u.first_name] :asc]- [[:lower :u.last_name] :asc]]}))+ ;; `user_id` in the result is for legacy reasons, we should remove it+ #(group-by :group_id (permissions.db/group-members (map :id groups)+ (when (premium-features/enable-advanced-permissions?)+ [:pgm.is_group_manager :is_group_manager]))):id{:default []}))(defn non-admin-groups"Return a set of the IDs of all `PermissionsGroups`, aside from the admin group."[]- (t2/select :model/PermissionsGroup :magic_group_type [:not= admin-magic-group-type]))+ (permissions.db/groups-except-magic-type admin-magic-group-type))(defn non-magic-groups"Return a set of the IDs of all `PermissionsGroups`, aside from the admin group and the All Users group."[]- (t2/select :model/PermissionsGroup {:where [:= :magic_group_type nil]}))+ (permissions.db/non-magic-groups))(defn is-tenant-group?"Returns a boolean representing whether this group is a tenant group."[group-id]- (t2/select-one-fn :is_tenant_group :model/PermissionsGroup :id (u/the-id group-id)))+ (permissions.db/tenant-group? (u/the-id group-id)))(defn hidden-tenant-group-ids"Returns the subset of `group-ids` that are tenant groups while the Tenants feature is disabled@@ -199,7 +184,7 @@(if (or (setting/get :use-tenants) (empty? group-ids))#{}(set/intersection (set (map u/the-id group-ids))- (t2/select-pks-set :model/PermissionsGroup :is_tenant_group true))))+ (permissions.db/tenant-group-ids))))(defn check-tenant-groups-visible!"Throws a 400 if any of `group-ids` is a tenant group while the Tenants feature is disabled.@@ -239,8 +224,7 @@[group-name](let [base-name (format "%s (converted)" group-name)like-pattern (str base-name "%")- existing-names (t2/select-fn-set :name :model/PermissionsGroup- :name [:like like-pattern])]+ existing-names (permissions.db/group-names-like like-pattern)](if-not (contains? existing-names base-name)base-name(loop [n 2]@@ -252,32 +236,29 @@(defn- grant-library-permissions!"Grant write permissions on all library collections to a group."[group-id]- (when-let [collection-ids (seq (t2/select-pks-set :model/Collection- :type [:in ["library" "library-data" "library-metrics"]]))]- (t2/insert! :model/Permissions- (for [coll-id collection-ids]- {:group_id group-id- :object (str "/collection/" coll-id "/")}))))+ (when-let [collection-ids (seq (permissions.db/library-collection-ids))]+ (permissions.db/insert-permissions! (for [coll-id collection-ids]+ {:group_id group-id+ :object (str "/collection/" coll-id "/")}))))(defn- do-sync-conversion!"Convert the Data Analysts magic group (if it has members) to a normal visible group, and create a fresh emptymagic group in its place. This ensures that we don't have an invisible group that affects permissions on OSS."[]- (when-let [existing-group (t2/select-one :model/PermissionsGroup :magic_group_type data-analyst-magic-group-type)]- (when (pos? (t2/count :model/PermissionsGroupMembership :group_id (:id existing-group)))+ (when-let [existing-group (permissions.db/group-by-magic-type data-analyst-magic-group-type)]+ (when (pos? (permissions.db/group-membership-count (:id existing-group)))(log/info "Converting Data Analysts group to normal group for OSS")(binding [*allow-modifying-magic-groups* true](t2/with-transaction [_conn];; Rename and demote the existing group to a normal visible group- (t2/update! :model/PermissionsGroup (:id existing-group)- {:name (unique-converted-group-name (:name existing-group))- :magic_group_type nil})+ (permissions.db/update-group! (:id existing-group)+ {:name (unique-converted-group-name (:name existing-group))+ :magic_group_type nil});; Create new empty magic group with default library permissions, reusing the old name- (let [{new-group-id :id} (t2/insert-returning-instance! :model/PermissionsGroup- {:name (:name existing-group)- :magic_group_type data-analyst-magic-group-type})]+ (let [{new-group-id :id} (permissions.db/insert-group! {:name (:name existing-group)+ :magic_group_type data-analyst-magic-group-type})](grant-library-permissions! new-group-id))- (t2/update! :model/User {:is_data_analyst true} {:is_data_analyst false}))))))+ (permissions.db/clear-data-analyst-flags!))))))(def ^:private seconds-to-sleep-per-attempt 1)diff --git a/src/metabase/permissions/models/permissions_group_membership.clj b/src/metabase/permissions/models/permissions_group_membership.cljindex 257d0961b3a..a99dd8a4642 100644--- a/src/metabase/permissions/models/permissions_group_membership.clj+++ b/src/metabase/permissions/models/permissions_group_membership.clj@@ -3,6 +3,7 @@[medley.core :as m][metabase.api.common :as api][metabase.events.core :as events]+ [metabase.permissions.db :as permissions.db][metabase.permissions.models.permissions-group :as perms-group][metabase.util :as u][metabase.util.i18n :refer [deferred-tru tru]]@@ -63,12 +64,7 @@archived or have their admin status removed."[user-id](when (zero?- (t2/count :model/PermissionsGroupMembership- {:join [[:core_user :user] [:= :user.id :user_id]]- :where [:and- [:= :group_id (u/the-id (perms-group/admin))]- [:= :user.is_active true]- [:not= :user.id user-id]]}))+ (permissions.db/other-active-member-count (u/the-id (perms-group/admin)) user-id))(throw (ex-info (str fail-to-remove-last-admin-msg){:status-code 400}))))@@ -99,10 +95,10 @@(throw-if-last-admin! user_id);; ...otherwise we're ok. Unset the `:is_superuser` flag for the user whose membership was revoked(when *update-user-when-added-to-admin-group?*- (t2/update! 'User user_id {:is_superuser false})))+ (permissions.db/update-user! user_id {:is_superuser false})));; If this is the Data Analysts group, unset the `:is_data_analyst` flag(when (= group_id (:id (perms-group/data-analyst)))- (t2/update! 'User user_id {:is_data_analyst false})))+ (permissions.db/update-user! user_id {:is_data_analyst false})))(defmacro without-is-superuser-sync-on-add-to-admin-group"When inserting a superuser, we don't want the group membership insert to trigger a recursive update on the@@ -120,31 +116,6 @@(dissoc membership:__test-only-sigil-allowing-direct-insertion-of-permissions-group-memberships)))-(mu/defn- add-users-to-groups-sql- "Generates SQL for adding users to groups"- [user-id-group-id->is-group-manager? :- [:map-of- [:tuple pos-int? pos-int?]- :boolean]]- (when (seq user-id-group-id->is-group-manager?)- {:insert-into [[:permissions_group_membership [:group_id :user_id :is_group_manager]]- ^:allow-subquery- {:select [:g.id :u.id [(into [:case]- (mapcat (fn [[[user-id group-id] is-group-manager?]]- [[[:and- [:= :u.id user-id]- [:= :g.id group-id]]]- is-group-manager?])- user-id-group-id->is-group-manager?))]]- :from [[:permissions_group :g]]- :join [[:core_user :u] (into [:or]- (for [[[user-id group-id] _] user-id-group-id->is-group-manager?]- [:and- [:= :u.id user-id]- [:= :g.id group-id]- [:=- :g.is_tenant_group- [:not= :u.tenant_id nil]]]))]}]}))-(mu/defn add-users-to-groups!"Creates permission group memberships from aa sequence of maps of users, groups and is-group-manager?."[pgms :- [:sequential@@ -176,12 +147,8 @@[(conj uids user-id)(conj gids group-id)])[#{} #{}]))- group-id->tenant? (t2/select-pk->fn (comp boolean :is_tenant_group)- [:model/PermissionsGroup :id :is_tenant_group]- :id [:in group-ids])- user-id->tenant? (t2/select-pk->fn (comp (complement nil?) :tenant_id)- [:model/User :id :tenant_id]- :id [:in user-ids])+ group-id->tenant? (update-vals (permissions.db/group-tenant-flags group-ids) boolean)+ user-id->tenant? (update-vals (permissions.db/user-tenant-ids user-ids) some?)bad-user-group-pairs (->> (keys user-id-group-id->is-group-manager?)(keep (fn [[user-id group-id]]@@ -214,20 +181,18 @@keys(keep (fn [[user-id group-id]](when (= group-id (:id (perms-group/data-analyst)))- user-id))))-- sql (add-users-to-groups-sql user-id-group-id->is-group-manager?)]+ user-id))))](t2/with-transaction [_conn]- (when (< (t2/query-one sql)+ (when (< (permissions.db/insert-group-memberships-from-mapping! user-id-group-id->is-group-manager?)(count user-id-group-id->is-group-manager?));; Theoretically, there could be a race condition in the above check: a user or group may be changed to a tenant;; user/group or vice versa AFTER we check (above) but BEFORE the insert (below). So just make sure that the;; number of inserted rows is correct - if not, throw an exception and we'll roll back.(throw (ex-info (tru "Error inserting Permissions Group Membership") {})))(when (seq new-admin-ids)- (t2/update! :model/User :id [:in new-admin-ids] {:is_superuser true}))+ (permissions.db/update-users! new-admin-ids {:is_superuser true}))(when (seq new-data-analyst-ids)- (t2/update! :model/User :id [:in new-data-analyst-ids] {:is_data_analyst true}))+ (permissions.db/update-users! new-data-analyst-ids {:is_data_analyst true}));; Publish events for each new membership(doseq [[[user-id group-id] is-group-manager?] user-id-group-id->is-group-manager?](events/publish-event! :event/group-membership-create@@ -257,11 +222,9 @@(when (seq group-ids-or-groups)(let [user-id (u/the-id user-id-or-user)group-ids (map u/the-id group-ids-or-groups)- memberships (t2/select :model/PermissionsGroupMembership- :user_id user-id- :group_id [:in group-ids])]+ memberships (permissions.db/memberships-for-user-in-groups user-id group-ids)](binding [*allow-direct-deletion* true]- (t2/delete! :model/PermissionsGroupMembership :user_id user-id :group_id [:in group-ids]))+ (permissions.db/delete-memberships-for-user-in-groups! user-id group-ids))(doseq [membership memberships](events/publish-event! :event/group-membership-delete {:object membership:user-id api/*current-user-id*})))))@@ -274,9 +237,9 @@(defn remove-all-users-from-group!"Removes all users from a group."[group-id]- (let [memberships (t2/select :model/PermissionsGroupMembership :group_id group-id)]+ (let [memberships (permissions.db/memberships-for-group group-id)](binding [*allow-direct-deletion* true]- (t2/delete! :model/PermissionsGroupMembership :group_id group-id))+ (permissions.db/delete-memberships-for-group! group-id))(doseq [membership memberships](events/publish-event! :event/group-membership-delete {:object membership:user-id api/*current-user-id*}))))@@ -284,9 +247,9 @@(defn remove-user-from-all-groups!"Removes a user from all groups."[user-id]- (let [memberships (t2/select :model/PermissionsGroupMembership :user_id user-id)]+ (let [memberships (permissions.db/memberships-for-user user-id)](binding [*allow-direct-deletion* true]- (t2/delete! :model/PermissionsGroupMembership :user_id user-id))+ (permissions.db/delete-memberships-for-user! user-id))(doseq [membership memberships](events/publish-event! :event/group-membership-delete {:object membership:user-id api/*current-user-id*}))))diff --git a/src/metabase/permissions/models/permissions_revision.clj b/src/metabase/permissions/models/permissions_revision.cljindex 1b93ed44c5b..509dde7db19 100644--- a/src/metabase/permissions/models/permissions_revision.clj+++ b/src/metabase/permissions/models/permissions_revision.clj@@ -1,6 +1,7 @@(ns metabase.permissions.models.permissions-revision(:require[metabase.models.interface :as mi]+ [metabase.permissions.db :as permissions.db][metabase.util.i18n :refer [tru]][methodical.core :as methodical][toucan2.core :as t2]))@@ -23,5 +24,5 @@"Return the ID of the newest `PermissionsRevision`, or zero if none have been made yet. (This is used by thepermissions graph update logic that checks for changes since the original graph was fetched)."[]- (or (:id (t2/select-one [:model/PermissionsRevision [:%max.id :id]]))+ (or (permissions.db/latest-permissions-revision-id)0))diff --git a/src/metabase/permissions/settings.clj b/src/metabase/permissions/settings.cljindex 9d8e5272f8b..8392f9fc228 100644--- a/src/metabase/permissions/settings.clj+++ b/src/metabase/permissions/settings.clj@@ -2,9 +2,9 @@(:require[java-time.api :as t][metabase.app-db.core :as mdb]+ [metabase.permissions.db :as permissions.db][metabase.settings.core :as setting :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru]]- [toucan2.core :as t2]))+ [metabase.util.i18n :refer [deferred-tru]]));;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; v50 Permissions Tutorial settings@@ -15,7 +15,7 @@;; We should come back around and delete them from the master branch in a few months.(defn- instance-create-time []- (->> (t2/select-one [:model/User [:%min.date_joined :min]]) :min t/local-date-time))+ (t/local-date-time (permissions.db/earliest-user-join-date)))(defn- v-fifty-migration-time [](let [v50-migration-id "v50.2024-01-04T13:52:51"]@@ -56,12 +56,9 @@(defn- update-use-tenants! [new-val](when-not new-val;; deactivate all tenants- (t2/query {:update :tenant- :set {:is_active false}})+ (permissions.db/deactivate-all-tenants!);; deactivate all tenant users, so if the tenant is reactivated someday they'll come back too- (t2/update! :model/User :tenant_id [:not= nil]- :is_active true- {:is_active false :deactivated_with_tenant true}))+ (permissions.db/deactivate-active-tenant-users!))(setting/set-value-of-type! :boolean :use-tenants new-val))(defsetting use-tenantsdiff --git a/src/metabase/permissions/util.clj b/src/metabase/permissions/util.cljindex 8c967fac141..e44fd6b0c1c 100644--- a/src/metabase/permissions/util.clj+++ b/src/metabase/permissions/util.clj@@ -4,14 +4,14 @@(:require[clojure.string :as str][metabase.api.common :as api]+ [metabase.permissions.db :as permissions.db][metabase.permissions.models.collection-permission-graph-revision :as collection-permission-graph-revision][metabase.premium-features.core :refer [defenterprise]][metabase.util.i18n :refer [tru]][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.regex :as u.regex]- [toucan2.core :as t2]))+ [metabase.util.regex :as u.regex]));;; +----------------------------------------------------------------------------------------------------------------+;;; | API-level helpers |@@ -45,13 +45,15 @@* `changes` -- set of changes applied in this revision."[model current-revision before changes](when api/*current-user-id*- (first (t2/insert-returning-instances! model- ;; manually specify ID here so if one was somehow inserted in the meantime in the fraction of a second since we- ;; called `check-revision-numbers` the PK constraint will fail and the transaction will abort- :id (inc current-revision)- :before before- :after changes- :user_id api/*current-user-id*))))+ ;; manually specify ID here so if one was somehow inserted in the meantime in the fraction of a second since we+ ;; called `check-revision-numbers` the PK constraint will fail and the transaction will abort+ (let [revision {:id (inc current-revision)+ :before before+ :after changes+ :user_id api/*current-user-id*}]+ (case model+ :model/PermissionsRevision (permissions.db/insert-permissions-revision-returning-instance! revision)+ :model/ApplicationPermissionsRevision (permissions.db/insert-application-permissions-revision-returning-instance! revision)))))(mu/defn increment-implicit-perms-revision!"Save changes made to permissions that are NOT due to an explicit update to the permissions graph, but rather due to@@ -62,11 +64,14 @@[model :- [:enum :model/CollectionPermissionGraphRevision]remark :- :string](when api/*current-user-id*- (t2/insert! model {:id (inc (collection-permission-graph-revision/latest-id))- :before {}- :after {}- :user_id api/*current-user-id*- :remark remark})))+ (case model+ :model/CollectionPermissionGraphRevision+ (permissions.db/insert-collection-permission-graph-revision!+ {:id (inc (collection-permission-graph-revision/latest-id))+ :before {}+ :after {}+ :user_id api/*current-user-id*+ :remark remark}))));;; +----------------------------------------------------------------------------------------------------------------+;;; | PATH CLASSIFICATION + VALIDATION |diff --git a/src/metabase/permissions_rest/api.clj b/src/metabase/permissions_rest/api.cljindex 4bb474328d4..9f312f839aa 100644--- a/src/metabase/permissions_rest/api.clj+++ b/src/metabase/permissions_rest/api.clj@@ -2,11 +2,11 @@"/api/permissions endpoints."(:require[clojure.data :as data]- [honey.sql.helpers :as sql.helpers][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.events.core :as events][metabase.permissions-rest.data-permissions.graph :as data-perms.graph]+ [metabase.permissions-rest.db :as permissions-rest.db][metabase.permissions-rest.schema :as permissions-rest.schema][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features :refer [defenterprise]]@@ -118,12 +118,8 @@(defn- ordered-groups"Return a sequence of ordered `PermissionsGroups`."- [limit offset query]- (t2/select :model/PermissionsGroup- (cond-> {:order-by [:%lower.name]}- (some? limit) (sql.helpers/limit limit)- (some? offset) (sql.helpers/offset offset)- (some? query) (sql.helpers/where query))))+ [limit offset opts]+ (permissions-rest.db/permissions-groups limit offset opts))(defn- maybe-fix-name"With Tenants enabled, we refer to the `all-internal-users` group as \"All internal users\", but@@ -166,30 +162,15 @@(perms/check-group-manager)(catch clojure.lang.ExceptionInfo _e(perms/check-has-application-permission :setting)))- (let [base-where- [:and- (when (and (not api/*is-superuser?*)- (premium-features/enable-advanced-permissions?)- api/*is-group-manager?*)- [:in :id ^:allow-subquery {:select [:group_id]- :from [:permissions_group_membership]- :where [:and- [:= :user_id api/*current-user-id*]- [:= :is_group_manager true]]}])- (when-not (setting/get :use-tenants)- [:not :is_tenant_group])- (when-not (premium-features/enable-advanced-permissions?)- [:or- [:= nil :magic_group_type]- [:not= "data-analyst" :magic_group_type]])]- where (case tenancy- "external" (if (setting/get :use-tenants)- [:and base-where [:= :is_tenant_group true]]- [:= 1 0]) ; Return no results when tenants disabled but external requested- "internal" [:and base-where [:or [:= :is_tenant_group false]- [:= :is_tenant_group nil]]]- base-where)]- (-> (ordered-groups (request/limit) (request/offset) where)+ (let [manager-user-id (when (and (not api/*is-superuser?*)+ (premium-features/enable-advanced-permissions?)+ api/*is-group-manager?*)+ api/*current-user-id*)]+ (-> (ordered-groups (request/limit) (request/offset)+ {:tenancy tenancy+ :manager-user-id manager-user-id+ :tenants-enabled? (setting/get :use-tenants)+ :advanced-permissions-enabled? (premium-features/enable-advanced-permissions?)})(t2/hydrate :member_count)(maybe-fix-names))))@@ -204,7 +185,7 @@(perms/check-manager-of-group id)(api/check-404 (empty? (perms/hidden-tenant-group-ids [id])))(api/check-404- (some-> (t2/select-one :model/PermissionsGroup :id id)+ (some-> (permissions-rest.db/permissions-group id)(t2/hydrate :members)(maybe-fix-name (setting/get :use-tenants)))))@@ -244,9 +225,7 @@(when-not (setting/get :use-tenants)(throw (ex-info (tru "Tenant groups cannot be created while the Tenants feature is disabled."){:status-code 400}))))- (u/prog1 (t2/insert-returning-instance! :model/PermissionsGroup- :name name- :is_tenant_group (boolean is_tenant_group))+ (u/prog1 (permissions-rest.db/insert-permissions-group! name (boolean is_tenant_group))(events/publish-event! :event/group-create {:object <>:user-id api/*current-user-id*})))@@ -263,12 +242,11 @@[:name ms/NonBlankString]]](perms/check-manager-of-group group-id)(api/check-404 (empty? (perms/hidden-tenant-group-ids [group-id])))- (let [group (t2/select-one :model/PermissionsGroup :id group-id)]+ (let [group (permissions-rest.db/permissions-group group-id)](api/check-404 group)- (t2/update! :model/PermissionsGroup group-id- {:name name})+ (permissions-rest.db/rename-permissions-group! group-id name);; return the updated group- (u/prog1 (t2/select-one :model/PermissionsGroup :id group-id)+ (u/prog1 (permissions-rest.db/permissions-group group-id)(events/publish-event! :event/group-update{:user-id api/*current-user-id*:object <>@@ -284,8 +262,8 @@[:group-id ms/PositiveInt]]](perms/check-manager-of-group group-id)(api/check-404 (empty? (perms/hidden-tenant-group-ids [group-id])))- (let [group (t2/select-one :model/PermissionsGroup :id group-id)]- (t2/delete! :model/PermissionsGroup :id group-id)+ (let [group (permissions-rest.db/permissions-group group-id)]+ (permissions-rest.db/delete-permissions-group! group-id)(events/publish-event! :event/group-delete {:object group:user-id api/*current-user-id*}))api/generic-204-no-content)@@ -305,23 +283,13 @@:is_group_manager boolean}]}"[](perms/check-group-manager)- (group-by :user_id (t2/select [:model/PermissionsGroupMembership [:id :membership_id] :group_id :user_id :is_group_manager]- (cond-> {}- (and (not api/*is-superuser?*)- api/*is-group-manager?*)- (sql.helpers/where- [:in :group_id ^:allow-subquery {:select [:group_id]- :from [:permissions_group_membership]- :where [:and- [:= :user_id api/*current-user-id*]- [:= :is_group_manager true]]}])- (not (premium-features/enable-advanced-permissions?))- (sql.helpers/where [:not= :group_id (u/the-id (perms/data-analyst-group))])- (not (setting/get :use-tenants))- (sql.helpers/where [:not-in :group_id ^:allow-subquery- {:select [:id]- :from [:permissions_group]- :where [:= :is_tenant_group true]}])))))+ (group-by :user_id+ (permissions-rest.db/group-memberships+ {:manager-user-id (when (and (not api/*is-superuser?*) api/*is-group-manager?*)+ api/*current-user-id*)+ :excluded-group-id (when-not (premium-features/enable-advanced-permissions?)+ (u/the-id (perms/data-analyst-group)))+ :exclude-tenant-groups? (not (setting/get :use-tenants))})));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -342,13 +310,12 @@;; enable `is_group_manager` require advanced-permissions enabled(perms/check-advanced-permissions-enabled :group-manager)(api/check- (t2/exists? :model/User :id user_id :is_superuser false)+ (permissions-rest.db/non-admin-user-exists? user_id)[400 (tru "Admin cannot be a group manager.")]))(perms/add-user-to-group! user_id group_id is_group_manager);; TODO - it's a bit silly to return the entire list of members for the group, just return the newly created one and;; let the frontend add it as appropriate- (:members (t2/hydrate (t2/instance :model/PermissionsGroup {:id group_id})- :members))))+ (:members (t2/hydrate (t2/instance :model/PermissionsGroup {:id group_id}) :members))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -365,16 +332,15 @@(perms/check-advanced-permissions-enabled :group-manager);; Make sure only Super user or Group Managers can call this(perms/check-group-manager)- (let [old (t2/select-one :model/PermissionsGroupMembership :id id)]+ (let [old (permissions-rest.db/group-membership id)](api/check-404 old)(perms/check-tenant-groups-visible! [(:group_id old)])(perms/check-manager-of-group (:group_id old))(api/check- (t2/exists? :model/User :id (:user_id old) :is_superuser false)+ (permissions-rest.db/non-admin-user-exists? (:user_id old))[400 (tru "Admin cannot be a group manager.")])- (t2/update! :model/PermissionsGroupMembership (:id old)- {:is_group_manager is_group_manager})- (t2/select-one :model/PermissionsGroupMembership :id (:id old))))+ (permissions-rest.db/set-group-membership-manager! (:id old) is_group_manager)+ (permissions-rest.db/group-membership (:id old))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -385,7 +351,7 @@[{:keys [group-id]} :- [:map[:group-id ms/PositiveInt]]](perms/check-manager-of-group group-id)- (api/check-404 (t2/exists? :model/PermissionsGroup :id group-id))+ (api/check-404 (permissions-rest.db/permissions-group-exists? group-id))(api/check-400 (not= group-id (u/the-id (perms/admin-group))))(perms/check-tenant-groups-visible! [group-id])(perms/remove-all-users-from-group! group-id)@@ -399,7 +365,7 @@"Remove a User from a PermissionsGroup (delete their membership)."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (let [membership (t2/select-one :model/PermissionsGroupMembership :id id)]+ (let [membership (permissions-rest.db/group-membership id)](api/check-404 membership)(perms/check-tenant-groups-visible! [(:group_id membership)])(perms/check-manager-of-group (:group_id membership))diff --git a/src/metabase/permissions_rest/data_permissions/graph.clj b/src/metabase/permissions_rest/data_permissions/graph.cljindex a0d66b44d98..232c3212965 100644--- a/src/metabase/permissions_rest/data_permissions/graph.clj+++ b/src/metabase/permissions_rest/data_permissions/graph.clj@@ -10,6 +10,7 @@[clojure.string :as str][medley.core :as m][metabase.audit-app.core :as audit]+ [metabase.permissions-rest.db :as permissions-rest.db][metabase.permissions-rest.schema :as permissions-rest.schema][metabase.permissions.core :as perms][metabase.permissions.schema :as permissions.schema]@@ -18,7 +19,6 @@[metabase.util.i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [toucan2.core :as t2][toucan2.realize :as t2.realize]))(set! *warn-on-reflection* true)@@ -130,10 +130,7 @@For every db in the incoming graph, adds on admin permissions."[api-graph {:keys [db-id group-ids group-id audit?]}](let [admin-group-id (u/the-id (perms/admin-group))- db-ids (if db-id [db-id] (t2/select-pks-vec :model/Database- {:where [:and- (when-not audit? [:not= :id audit/audit-db-id])- [:= :router_database_id nil]]}))]+ db-ids (if db-id [db-id] (permissions-rest.db/non-destination-database-ids (when-not audit? audit/audit-db-id)))];; Don't add admin perms when we're fetching the perms for a specific non-admin group or set of groups(if (or (= group-id admin-group-id)(contains? (set group-ids) admin-group-id)@@ -151,10 +148,7 @@This is not stored in the data-permissions table, so we add it to the graph for the API."[api-graph {:keys [db-id group-ids group-id audit?]}](let [data-analyst-group-id (u/the-id (perms/data-analyst-group))- db-ids (if db-id [db-id] (t2/select-pks-vec :model/Database- {:where [:and- (when-not audit? [:not= :id audit/audit-db-id])- [:= :router_database_id nil]]}))]+ db-ids (if db-id [db-id] (permissions-rest.db/non-destination-database-ids (when-not audit? audit/audit-db-id)))];; Don't add data analyst perms when we're fetching perms for a specific non-data-analyst group(if (or (= group-id data-analyst-group-id)(contains? (set group-ids) data-analyst-group-id)@@ -219,26 +213,12 @@(-> (t2.realize/realize row)(update :type keyword)(update :value keyword))))- (t2/reducible-query- {:select [[:perm_type :type]- [:group_id :group-id]- [:perm_value :value]- [:db_id :db-id]- [:schema_name :schema]- [:table_id :table-id]]- :from [(t2/table-name :model/DataPermissions)]- :where [:and- (when perm-type [:= :perm_type (u/qualified-name perm-type)])- (when db-id [:= :db_id db-id])- (when group-id [:= :group_id group-id])- (when group-ids [:in :group_id group-ids])- (when-not audit? [:not= :db_id audit/audit-db-id])- [:not [:exists ^:allow-subquery {:select [1]- :from [[(t2/table-name :model/Database) :router_db]]- :where [:and- [:not= :router_db.router_database_id nil]- [:= :router_db.id :db_id]]}]]]- :order-by [:group_id :db_id]})))+ (permissions-rest.db/data-permissions-reducible+ {:perm-type perm-type+ :db-id db-id+ :group-id group-id+ :group-ids group-ids+ :excluded-database-id (when-not audit? audit/audit-db-id)})))(defn- add-perm"Reducing step that accumulates one `data_permissions` row's value into its (group, db) `perm-map`, at either a@@ -626,8 +606,7 @@(let [affected-group-ids (keys graph)affected-db-ids (into #{} (mapcat keys) (vals graph))all-tables (when (seq affected-db-ids)- (t2/select [:model/Table :id :db_id :schema]- :db_id [:in affected-db-ids]))+ (permissions-rest.db/tables-for-databases affected-db-ids))tables-by-db-schema (group-by (juxt :db_id :schema) all-tables)tables-by-db (group-by :db_id all-tables)current-perms (or (perms/index-database-permissions affected-group-ids affected-db-ids) {})diff --git a/src/metabase/permissions_rest/db.clj b/src/metabase/permissions_rest/db.cljnew file mode 100644index 00000000000..7ea1d9e39f1--- /dev/null+++ b/src/metabase/permissions_rest/db.clj@@ -0,0 +1,134 @@+(ns metabase.permissions-rest.db+ "Application database queries for the permissions REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn- managed-groups-clause+ [group-id-column manager-user-id]+ (when manager-user-id+ [:in group-id-column ^:allow-subquery {:select [:group_id]+ :from [:permissions_group_membership]+ :where [:and+ [:= :user_id manager-user-id]+ [:= :is_group_manager true]]}]))++(defn permissions-groups+ "Up to `limit` PermissionsGroups starting at `offset` (both optional), ordered by lower-cased name.++ `tenancy` (\"external\"/\"internal\"/nil) narrows to tenant/non-tenant groups (nil returns both); when+ `tenancy` is \"external\" and `tenants-enabled?` is false, no groups are returned. `manager-user-id`, when given,+ restricts to the groups that User manages. `advanced-permissions-enabled?` false excludes the data-analyst magic+ group. `tenants-enabled?` false also excludes tenant groups outright, independent of `tenancy`."+ [limit offset {:keys [tenancy manager-user-id tenants-enabled? advanced-permissions-enabled?]}]+ (let [base-where [:and+ (managed-groups-clause :id manager-user-id)+ (when-not tenants-enabled? [:not :is_tenant_group])+ (when-not advanced-permissions-enabled?+ [:or [:= nil :magic_group_type] [:not= "data-analyst" :magic_group_type]])]+ where (case tenancy+ "external" (if tenants-enabled?+ [:and base-where [:= :is_tenant_group true]]+ [:= 1 0])+ "internal" [:and base-where [:or [:= :is_tenant_group false] [:= :is_tenant_group nil]]]+ base-where)]+ (t2/select :model/PermissionsGroup+ (cond-> {:where where :order-by [:%lower.name]}+ limit (assoc :limit limit)+ offset (assoc :offset offset)))))++(defn permissions-group+ "The PermissionsGroup with `id`, or nil."+ [id]+ (t2/select-one :model/PermissionsGroup :id id))++(defn permissions-group-exists?+ "Whether a PermissionsGroup with `id` exists."+ [id]+ (t2/exists? :model/PermissionsGroup :id id))++(defn insert-permissions-group!+ "Insert a PermissionsGroup and return the inserted instance."+ [group-name tenant-group?]+ (t2/insert-returning-instance! :model/PermissionsGroup :name group-name :is_tenant_group tenant-group?))++(defn rename-permissions-group!+ "Set the name of the PermissionsGroup with `id`."+ [id group-name]+ (t2/update! :model/PermissionsGroup id {:name group-name}))++(defn delete-permissions-group!+ "Delete the PermissionsGroup with `id`."+ [id]+ (t2/delete! :model/PermissionsGroup :id id))++(defn group-memberships+ "The membership id, group id, user id, and group manager flag of every PermissionsGroupMembership, optionally+ restricted to the groups `manager-user-id` manages, excluding `excluded-group-id`, and excluding tenant groups+ when `exclude-tenant-groups?`."+ [{:keys [manager-user-id excluded-group-id exclude-tenant-groups?]}]+ (t2/select [:model/PermissionsGroupMembership [:id :membership_id] :group_id :user_id :is_group_manager]+ {:where (into [:and]+ (keep identity)+ [(managed-groups-clause :group_id manager-user-id)+ (when excluded-group-id [:not= :group_id excluded-group-id])+ (when exclude-tenant-groups?+ [:not-in :group_id ^:allow-subquery {:select [:id]+ :from [:permissions_group]+ :where [:= :is_tenant_group true]}])])}))++(defn non-admin-user-exists?+ "Whether the User with `user-id` exists and is not a superuser."+ [user-id]+ (t2/exists? :model/User :id user-id :is_superuser false))++(defn group-membership+ "The PermissionsGroupMembership with `id`, or nil."+ [id]+ (t2/select-one :model/PermissionsGroupMembership :id id))++(defn set-group-membership-manager!+ "Set the group manager flag of the PermissionsGroupMembership with `id`."+ [id group-manager?]+ (t2/update! :model/PermissionsGroupMembership id {:is_group_manager group-manager?}))++(defn non-destination-database-ids+ "The ids of the Databases that are not routing destinations, excluding `excluded-database-id` (nil for no+ exclusion)."+ [excluded-database-id]+ (t2/select-pks-vec :model/Database {:where [:and+ (when excluded-database-id [:not= :id excluded-database-id])+ [:= :router_database_id nil]]}))++(defn data-permissions-reducible+ "A reducible of the type, group id, value, database id, schema, and table id of the DataPermissions rows of+ non-destination Databases, optionally narrowed to `perm-type`, `db-id`, `group-id`, `group-ids`, and excluding+ `excluded-database-id` (nil for no restriction), ordered by group and database."+ [{:keys [perm-type db-id group-id group-ids excluded-database-id]}]+ (t2/reducible-query+ {:select [[:perm_type :type]+ [:group_id :group-id]+ [:perm_value :value]+ [:db_id :db-id]+ [:schema_name :schema]+ [:table_id :table-id]]+ :from [(t2/table-name :model/DataPermissions)]+ :where (conj (into [:and]+ (keep identity)+ [(when perm-type [:= :perm_type (u/qualified-name perm-type)])+ (when db-id [:= :db_id db-id])+ (when group-id [:= :group_id group-id])+ (when group-ids [:in :group_id group-ids])+ (when excluded-database-id [:not= :db_id excluded-database-id])])+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[(t2/table-name :model/Database) :router_db]]+ :where [:and+ [:not= :router_db.router_database_id nil]+ [:= :router_db.id :db_id]]}]])+ :order-by [:group_id :db_id]}))++(defn tables-for-databases+ "The id, Database id, and schema of the Tables of the Databases with `database-ids`."+ [database-ids]+ (t2/select [:model/Table :id :db_id :schema] :db_id [:in database-ids]))diff --git a/src/metabase/premium_features/db.clj b/src/metabase/premium_features/db.cljnew file mode 100644index 00000000000..9376de29290--- /dev/null+++ b/src/metabase/premium_features/db.clj@@ -0,0 +1,35 @@+(ns metabase.premium-features.db+ "Application database queries for the premium features module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself."+ (:require+ [toucan2.core :as t2]))++(defn active-personal-user-count+ "The number of active personal Users."+ []+ ;; Because this count is needed *during* token checks, it uses `t2/table-name` to avoid the `after-select` method on+ ;; users, which calls an EE method that needs ... a token check :|+ (t2/count (t2/table-name :model/User) :is_active true, :type "personal"))++(defn token-status-cache+ "The `:token_status_hash` and `:updated_at` cached for `token-hash`, or nil."+ [token-hash]+ (t2/select-one [:model/PremiumFeaturesCache :token_status_hash :updated_at] :token_hash token-hash))++(defn update-token-status-cache!+ "Set the cached status hash for `token-hash`, returning the number of rows updated."+ [token-hash token-status-hash updated-at]+ (t2/update! :model/PremiumFeaturesCache :token_hash token-hash+ {:token_status_hash token-status-hash, :updated_at updated-at}))++(defn insert-token-status-cache!+ "Insert a cached status hash for `token-hash`."+ [token-hash token-status-hash updated-at]+ (t2/insert! :model/PremiumFeaturesCache {:token_hash token-hash+ :token_status_hash token-status-hash+ :updated_at updated-at}))++(defn delete-token-status-cache!+ "Delete every cached token status."+ []+ (t2/delete! :model/PremiumFeaturesCache))diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.cljindex aba68916440..f4a20616f04 100644--- a/src/metabase/premium_features/token_check.clj+++ b/src/metabase/premium_features/token_check.clj@@ -20,6 +20,7 @@[metabase.config.core :as config][metabase.events.core :as events][metabase.internal-stats.core :as internal-stats]+ [metabase.premium-features.db :as premium-features.db][metabase.premium-features.defenterprise :refer [defenterprise]][metabase.premium-features.settings :as premium-features.settings][metabase.settings.core :as setting]@@ -76,10 +77,7 @@;; force this to use a new Connection, it seems to be getting called in situations where the Connection;; is from a different thread and is invalid by the time we get to use it(let [result (binding [t2.conn/*current-connectable* nil]- ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid- ;; the `after-select` method on users, which calls an EE method that needs ... a token- ;; check :|- (t2/count (t2/table-name :model/User) :is_active true :type "personal"))]+ (premium-features.db/active-personal-user-count))](log/debug (u/colorize :green "=>") result)result))lock (Object.)]@@ -244,9 +242,7 @@(when (pos? max-users) max-users)))))(defn- active-user-count []- ;; Because we need this count *during* token checks, this uses `t2/table-name` to avoid the `after-select` method- ;; on users, which calls an EE method that needs ... a token check :|- (t2/count (t2/table-name :model/User) :is_active true, :type "personal"))+ (premium-features.db/active-personal-user-count))(defn assert-valid-airgap-user-count!"Asserts that, in an airgap context, the current user count does not exceed the allowed maximum.@@ -365,7 +361,7 @@(defn- read-cache-from-db"Read a cached token status hash from the premium_features_token_cache table. Returns nil if not found."[token-hash]- (t2/select-one [:model/PremiumFeaturesCache :token_status_hash :updated_at] :token_hash token-hash))+ (premium-features.db/token-status-cache token-hash))(defn- write-cache-to-db!"Upsert a token status hash into the premium_features_token_cache table.@@ -374,23 +370,19 @@[token-hash result-hash](t2/with-connection [_conn (app-db/app-db)](let [now (t/offset-date-time)- updated (t2/update! :model/PremiumFeaturesCache :token_hash token-hash- {:token_status_hash result-hash :updated_at now})]+ updated (premium-features.db/update-token-status-cache! token-hash result-hash now)](when (zero? updated) ;; even though toucan2 returns 0 if we match a row but don't update it;; we should always be updating this row with the timestamp if it's there.(try- (t2/insert! :model/PremiumFeaturesCache {:token_hash token-hash- :token_status_hash result-hash- :updated_at now})+ (premium-features.db/insert-token-status-cache! token-hash result-hash now)(catch Exception _e;; Another instance inserted first — update instead.- (t2/update! :model/PremiumFeaturesCache :token_hash token-hash- {:token_status_hash result-hash :updated_at now})))))))+ (premium-features.db/update-token-status-cache! token-hash result-hash now)))))))(defn- clear-db-cache!"Delete all rows from the premium_features_token_cache table."[]- (t2/delete! :model/PremiumFeaturesCache))+ (premium-features.db/delete-token-status-cache!))(defn- extract-locks"Project a `:meters` map to `{meter-keyword -> boolean}` of `:is-locked` values.diff --git a/src/metabase/product_feedback/db.clj b/src/metabase/product_feedback/db.cljnew file mode 100644index 00000000000..37142444086--- /dev/null+++ b/src/metabase/product_feedback/db.clj@@ -0,0 +1,64 @@+(ns metabase.product-feedback.db+ "Application database queries for the product feedback module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn creator-sentiment-candidates+ "The email, join date, first name, and content counts of the active personal Users who created content in the past+ 2 months, with at least 10 Cards (2 native), and at least 1 Dashboard. When `only-superusers?` is true, only+ superusers are considered."+ [only-superusers?]+ (let [created-after (h2x/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]+ (t2/query {:select [[:u.email :email]+ [:u.date_joined :created_at]+ [:u.first_name :first_name]+ [[:count [:distinct [:case [:= :d.archived false] :d.id]]] :num_dashboards]+ [[:count [:distinct [:case [:and [:= :rc.type "question"] [:= :rc.archived false]] :rc.id]]] :num_questions]+ [[:count [:distinct [:case [:and [:= :rc.type "model"] [:= :rc.archived false]] :rc.id]]] :num_models]]+ :from [[:core_user :u]]+ :join [[:report_card :rc] [:= :rc.creator_id :u.id]+ [:report_dashboard :d] [:= :d.creator_id :u.id]]+ :where [:and+ [:>= :rc.created_at created-after]+ [:>= :d.created_at created-after]+ [:= :u.is_active true]+ [:= :u.type "personal"]+ (when only-superusers? [:= :u.is_superuser true])]+ :group-by [:u.id]+ :having [:and+ [:>= [:count [:distinct :rc.id]] 10]+ [:>= [:count [:distinct [:case [:= :rc.query_type "native"] :rc.id]]] 2]+ [:>= [:count [:distinct :d.id]] 1]]})))++(defn active-personal-user-count+ "The number of active personal Users."+ []+ (t2/count :model/User :is_active true, :type "personal"))++(defn unarchived-dashboard-count+ "The number of unarchived Dashboards."+ []+ (t2/count :model/Dashboard :archived false))++(defn non-audit-database-count+ "The number of Databases other than the audit Database."+ []+ (t2/count :model/Database :is_audit false))++(defn unarchived-card-count+ "The number of unarchived Cards of `card-type`."+ [card-type]+ (t2/count :model/Card :archived false :type card-type))++(defn oldest-active-admin+ "The earliest-joined active superuser, or nil."+ []+ (t2/select-one :model/User :is_superuser true, :is_active true, {:order-by [:date_joined]}))++(defn earliest-user-date-joined+ "The join date of the earliest-joined User, or nil."+ []+ (t2/select-one-fn :date_joined :model/User, {:order-by [[:date_joined :asc]]}))diff --git a/src/metabase/product_feedback/task/creator_sentiment_emails.clj b/src/metabase/product_feedback/task/creator_sentiment_emails.cljindex 4994a97f90a..f19ff108e2d 100644--- a/src/metabase/product_feedback/task/creator_sentiment_emails.clj+++ b/src/metabase/product_feedback/task/creator_sentiment_emails.clj@@ -5,15 +5,13 @@[clojurewerkz.quartzite.triggers :as triggers][java-time.api :as t][metabase.analytics.core :as analytics]- [metabase.app-db.core :as mdb][metabase.channel.email.messages :as messages][metabase.channel.settings :as channel.settings][metabase.config.core :as config][metabase.premium-features.core :as premium-features]+ [metabase.product-feedback.db :as product-feedback.db][metabase.task.core :as task]- [metabase.util.honey-sql-2 :as h2x]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.time.temporal WeekFields)(java.util Locale)))@@ -27,26 +25,7 @@- Created at least 1 dashboard- Only admins if whitelabeling is enabled"[has-whitelabelling?]- (t2/query {:select [[:u.email :email]- [:u.date_joined :created_at]- [:u.first_name :first_name]- [[:count [:distinct [:case [:= :d.archived false] :d.id]]] :num_dashboards]- [[:count [:distinct [:case [:and [:= :rc.type "question"] [:= :rc.archived false]] :rc.id]]] :num_questions]- [[:count [:distinct [:case [:and [:= :rc.type "model"] [:= :rc.archived false]] :rc.id]]] :num_models]]- :from [[:core_user :u]]- :join [[:report_card :rc] [:= :rc.creator_id :u.id]- [:report_dashboard :d] [:= :d.creator_id :u.id]]- :where [:and- [:>= :rc.created_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]- [:>= :d.created_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]- [:= :u.is_active true]- [:= :u.type "personal"]- (when has-whitelabelling? [:= :u.is_superuser true])]- :group-by [:u.id]- :having [:and- [:>= [:count [:distinct :rc.id]] 10]- [:>= [:count [:distinct [:case [:= :rc.query_type "native"] :rc.id]]] 2]- [:>= [:count [:distinct :d.id]] 1]]}))+ (product-feedback.db/creator-sentiment-candidates has-whitelabelling?))(defn fetch-plan-info"Figure out what plan this Metabase instance is on."@@ -64,11 +43,11 @@{:created_at (analytics/instance-creation):plan (fetch-plan-info):version (config/mb-version-info :tag)- :num_users (t2/count :model/User :is_active true, :type "personal")- :num_dashboards (t2/count :model/Dashboard :archived false)- :num_databases (t2/count :model/Database :is_audit false)- :num_questions (t2/count :model/Card :archived false :type "question")- :num_models (t2/count :model/Card :archived false :type "model")})+ :num_users (product-feedback.db/active-personal-user-count)+ :num_dashboards (product-feedback.db/unarchived-dashboard-count)+ :num_databases (product-feedback.db/non-audit-database-count)+ :num_questions (product-feedback.db/unarchived-card-count "question")+ :num_models (product-feedback.db/unarchived-card-count "model")})(defn- user-instance-info"Create a blob of instance/user data to be sent to the creator sentiment survey."diff --git a/src/metabase/product_feedback/task/follow_up_emails.clj b/src/metabase/product_feedback/task/follow_up_emails.cljindex 636d18e249c..ca69064ece1 100644--- a/src/metabase/product_feedback/task/follow_up_emails.clj+++ b/src/metabase/product_feedback/task/follow_up_emails.clj@@ -8,11 +8,11 @@[metabase.analytics.core :as analytics][metabase.channel.email.messages :as messages][metabase.channel.settings :as channel.settings]+ [metabase.product-feedback.db :as product-feedback.db][metabase.product-feedback.settings :as product-feedback.settings][metabase.task.core :as task][metabase.util.date-2 :as u.date]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -27,7 +27,7 @@(not (product-feedback.settings/follow-up-email-sent)));; grab the oldest admins email address (likely the user who created this MB instance), that's who we'll send to;; TODO - Does it make to send to this user instead of `(system/admin-email)`?- (when-let [admin (t2/select-one :model/User :is_superuser true, :is_active true, {:order-by [:date_joined]})]+ (when-let [admin (product-feedback.db/oldest-active-admin)](try(messages/send-follow-up-email! (:email admin))(catch Throwable e@@ -38,7 +38,7 @@(defn- instance-creation-timestamp"The date this Metabase instance was created. We use the `:date_joined` of the first `User` to determine this."^java.time.temporal.Temporal []- (t2/select-one-fn :date_joined :model/User, {:order-by [[:date_joined :asc]]}))+ (product-feedback.db/earliest-user-date-joined))(task/defjob ^{:doc "Sends out a general 2 week email follow up email"} FollowUpEmail [_];; if we've already sent the follow-up email then we are donediff --git a/src/metabase/public_sharing/core.clj b/src/metabase/public_sharing/core.cljindex cb7758ed147..b4068da6b51 100644--- a/src/metabase/public_sharing/core.clj+++ b/src/metabase/public_sharing/core.clj@@ -1,6 +1,7 @@(ns metabase.public-sharing.core(:require[medley.core :as m]+ [metabase.public-sharing.db :as public-sharing.db][metabase.public-sharing.settings :as public-sharing.settings][toucan2.core :as t2]))@@ -60,12 +61,16 @@resolving."[model uuid](when uuid- (some (fn [{:keys [id public_uuid]}]- (when (= uuid public_uuid)- id))- (t2/select [model :id :public_uuid]- :public_uuid_prefix (public-uuid-prefix uuid)- :archived false))))+ (let [prefix (public-uuid-prefix uuid)+ candidates (case model+ :model/Card (public-sharing.db/unarchived-card-ids-and-public-uuids-by-prefix prefix)+ :model/Dashboard (public-sharing.db/unarchived-dashboard-ids-and-public-uuids-by-prefix prefix)+ :model/Action (public-sharing.db/unarchived-action-ids-and-public-uuids-by-prefix prefix)+ :model/Document (public-sharing.db/unarchived-document-ids-and-public-uuids-by-prefix prefix))]+ (some (fn [{:keys [id public_uuid]}]+ (when (= uuid public_uuid)+ id))+ candidates))))(defn public-uuid->model"Resolve a shared entity's public `uuid` to the full matching `model` row, or nil. Like [[public-uuid->id]] but@@ -76,7 +81,10 @@e.g. a plaintext uuid forged via raw SQL — fails the strict decrypting read and errors out rather than resolving."[model uuid](when uuid- (m/find-first #(= uuid (:public_uuid %))- (t2/select model- :public_uuid_prefix (public-uuid-prefix uuid)- :archived false))))+ (let [prefix (public-uuid-prefix uuid)+ candidates (case model+ :model/Card (public-sharing.db/unarchived-cards-by-public-uuid-prefix prefix)+ :model/Dashboard (public-sharing.db/unarchived-dashboards-by-public-uuid-prefix prefix)+ :model/Action (public-sharing.db/unarchived-actions-by-public-uuid-prefix prefix)+ :model/Document (public-sharing.db/unarchived-documents-by-public-uuid-prefix prefix))]+ (m/find-first #(= uuid (:public_uuid %)) candidates))))diff --git a/src/metabase/public_sharing/db.clj b/src/metabase/public_sharing/db.cljnew file mode 100644index 00000000000..0cce80652e2--- /dev/null+++ b/src/metabase/public_sharing/db.clj@@ -0,0 +1,45 @@+(ns metabase.public-sharing.db+ "Application database queries for the public sharing module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn unarchived-card-ids-and-public-uuids-by-prefix+ "The `:id` and `:public_uuid` of the unarchived Cards whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select [:model/Card :id :public_uuid] :public_uuid_prefix prefix :archived false))++(defn unarchived-dashboard-ids-and-public-uuids-by-prefix+ "The `:id` and `:public_uuid` of the unarchived Dashboards whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select [:model/Dashboard :id :public_uuid] :public_uuid_prefix prefix :archived false))++(defn unarchived-action-ids-and-public-uuids-by-prefix+ "The `:id` and `:public_uuid` of the unarchived Actions whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select [:model/Action :id :public_uuid] :public_uuid_prefix prefix :archived false))++(defn unarchived-document-ids-and-public-uuids-by-prefix+ "The `:id` and `:public_uuid` of the unarchived Documents whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select [:model/Document :id :public_uuid] :public_uuid_prefix prefix :archived false))++(defn unarchived-cards-by-public-uuid-prefix+ "The unarchived Cards whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select :model/Card :public_uuid_prefix prefix :archived false))++(defn unarchived-dashboards-by-public-uuid-prefix+ "The unarchived Dashboards whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select :model/Dashboard :public_uuid_prefix prefix :archived false))++(defn unarchived-actions-by-public-uuid-prefix+ "The unarchived Actions whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select :model/Action :public_uuid_prefix prefix :archived false))++(defn unarchived-documents-by-public-uuid-prefix+ "The unarchived Documents whose public uuid prefix is `prefix`."+ [prefix]+ (t2/select :model/Document :public_uuid_prefix prefix :archived false))diff --git a/src/metabase/public_sharing_rest/api.clj b/src/metabase/public_sharing_rest/api.cljindex c2a0918c72d..97d22d72804 100644--- a/src/metabase/public_sharing_rest/api.clj+++ b/src/metabase/public_sharing_rest/api.clj@@ -19,6 +19,7 @@[metabase.parameters.dashboard :as parameters.dashboard][metabase.parameters.params :as params][metabase.parameters.schema :as parameters.schema]+ [metabase.public-sharing-rest.db :as public-sharing-rest.db][metabase.public-sharing.core :as public-sharing][metabase.public-sharing.validation :as public-sharing.validation][metabase.queries.core :as queries]@@ -109,13 +110,12 @@params/remove-param-fields-non-public-columns))))(defn public-card- "Return the public Card with the given `card-id` (plus any extra key-value `conditions`), removing all columns that- should not be visible to the general public. Throws a 404 if the Card doesn't exist."- [card-id & conditions]+ "Return the public Card with the given `card-id`, removing all columns that should not be visible to the general+ public. Throws a 404 if the Card doesn't exist. With `:enable-embedding? true`, additionally requires embedding+ to be enabled."+ [card-id & {:as options}](binding [params/*ignore-current-user-perms-and-return-all-field-values* true]- (-> (api/check-404 (apply t2/select-one [:model/Card :id :dataset_query :description :display :name :parameters- :visualization_settings :card_schema]- :id card-id, :archived false, conditions))+ (-> (api/check-404 (public-sharing-rest.db/public-card card-id options))combine-parameters-and-template-tags(t2/hydrate :param_fields)keep-param-fields-for-parameters@@ -180,7 +180,7 @@(mu/defn process-query-for-card-with-id"Run the query for pre-loaded Card `card` with `parameters` and other query options (e.g. `:constraints`).- Callers are responsible for resolving `card` themselves with a fresh `t2/select-one` call (each endpoint should+ Callers are responsible for resolving `card` themselves with a fresh `public-sharing-rest.db/active-card` call (each endpoint shouldselect the Card exactly once and thread the loaded entity here). Returns a `StreamingResponse`."[cardexport-format@@ -280,13 +280,13 @@(select-keys action-public-keys))))(mu/defn public-dashboard :- ::dashboards.schema/dashboard- "Return the public Dashboard with the given `dashboard-id` (plus any extra key-value `conditions`), removing all- columns that should not be visible to the general public. Throws a 404 if the Dashboard doesn't exist."- [dashboard-id & conditions]- {:pre [(even? (count conditions))]}+ "Return the public Dashboard with the given `dashboard-id`, removing all columns that should not be visible to+ the general public. Throws a 404 if the Dashboard doesn't exist. With `:enable-embedding? true`, additionally+ requires embedding to be enabled."+ [dashboard-id & {:as options}](binding [params/*ignore-current-user-perms-and-return-all-field-values* trueparams/*field-id-context* (atom params/empty-field-id-context)]- (-> (api/check-404 (apply t2/select-one [:model/Dashboard :name :description :id :parameters :auto_apply_filters :width], :id dashboard-id, :archived false, conditions))+ (-> (api/check-404 (public-sharing-rest.db/public-dashboard dashboard-id options))(t2/hydrate [:dashcards :card :series :dashcard/action] :tabs :param_fields)keep-param-fields-for-parametersparams/remove-param-fields-non-public-columns@@ -391,9 +391,9 @@[:parameters {:optional true} [:maybe ::parameters.schema/api.parameter-values]][:ignore_cache {:optional true} [:maybe ms/BooleanValue]]]](public-sharing.validation/check-public-sharing-enabled)- (let [card (api/check-404 (t2/select-one :model/Card :id card-id :archived false))+ (let [card (api/check-404 (public-sharing-rest.db/active-card card-id))dashboard (api/check-404 (public-sharing/public-uuid->model :model/Dashboard uuid))- dashcard (api/check-404 (t2/select-one :model/DashboardCard :id dashcard-id))]+ dashcard (api/check-404 (public-sharing-rest.db/dashcard dashcard-id))](process-query-for-dashcard:dashboard dashboard:card card@@ -421,9 +421,9 @@[:pivot_results {:default false} ms/BooleanValue][:csv_include_bom {:optional true} [:maybe ms/BooleanValue]]]](public-sharing.validation/check-public-sharing-enabled)- (let [card (api/check-404 (t2/select-one :model/Card :id card-id :archived false))+ (let [card (api/check-404 (public-sharing-rest.db/active-card card-id))dashboard (api/check-404 (public-sharing/public-uuid->model :model/Dashboard uuid))- dashcard (api/check-404 (t2/select-one :model/DashboardCard :id dashcard-id))]+ dashcard (api/check-404 (public-sharing-rest.db/dashcard dashcard-id))](u/prog1 (process-query-for-dashcard:dashboard dashboard:card card@@ -447,7 +447,7 @@[:parameters ::actions.schema/prefetch-parameter-values]]](public-sharing.validation/check-public-sharing-enabled)(let [dashboard-id (api/check-404 (public-sharing/public-uuid->id :model/Dashboard uuid))]- (api/check-404 (t2/select-one-pk :model/DashboardCard :id dashcard-id :dashboard_id dashboard-id))+ (api/check-404 (public-sharing-rest.db/dashcard-id-in-dashboard dashcard-id dashboard-id))(actions/fetch-values(api/check-404 (actions/dashcard->action dashcard-id))parameters)))@@ -673,9 +673,9 @@[:parameters {:optional true} [:maybe ::parameters.schema/api.parameter-values]][:ignore_cache {:optional true} [:maybe ms/BooleanValue]]]](public-sharing.validation/check-public-sharing-enabled)- (let [card (api/check-404 (t2/select-one :model/Card :id card-id :archived false))+ (let [card (api/check-404 (public-sharing-rest.db/active-card card-id))dashboard (api/check-404 (public-sharing/public-uuid->model :model/Dashboard uuid))- dashcard (api/check-404 (t2/select-one :model/DashboardCard :id dashcard-id))]+ dashcard (api/check-404 (public-sharing-rest.db/dashcard dashcard-id))](process-query-for-dashcard:dashboard dashboard:card card@@ -782,8 +782,8 @@[:lonField ::api.tiles/legacy-ref]]](public-sharing.validation/check-public-sharing-enabled)(let [dashboard (api/check-404 (public-sharing/public-uuid->model :model/Dashboard uuid))- dashcard (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- card (api/check-404 (t2/select-one :model/Card :id card-id :archived false))]+ dashcard (api/check-404 (public-sharing-rest.db/dashcard dashcard-id))+ card (api/check-404 (public-sharing-rest.db/active-card card-id))](process-tiles-query-for-dashcard dashboard dashcard cardparameters zoom x y latField lonField)))@@ -806,8 +806,7 @@once before exposing them to unauthenticated users. The document and all cards must not be archived to beaccessible publicly."[document-id]- (let [document (-> (api/check-404 (t2/select-one [:model/Document :id :name :document :content_type :created_at :updated_at]- :id document-id, :archived false))+ (let [document (-> (api/check-404 (public-sharing-rest.db/public-document document-id));; Hydrate cards via Toucan batched hydration to avoid N+1 queries(t2/hydrate :cards))embedded-ids (set (prose-mirror/card-ids document))]@@ -827,9 +826,9 @@Returns the loaded `:model/Card` entity so the caller can thread it downstream without re-selecting it."[uuid card-id]- (let [document (api/check-404 (t2/select-one [:model/Document :id :document :content_type] :id (public-sharing/public-uuid->id :model/Document uuid)))]+ (let [document (api/check-404 (public-sharing-rest.db/document-content (public-sharing/public-uuid->id :model/Document uuid)))](api/check-404 (when (contains? (set (prose-mirror/card-ids document)) card-id)- (t2/select-one :model/Card :id card-id :document_id (:id document) :archived false)))))+ (public-sharing-rest.db/active-card-in-document card-id (:id document))))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/public_sharing_rest/db.clj b/src/metabase/public_sharing_rest/db.cljnew file mode 100644index 00000000000..aaebbc585fc--- /dev/null+++ b/src/metabase/public_sharing_rest/db.clj@@ -0,0 +1,63 @@+(ns metabase.public-sharing-rest.db+ "Application database queries for the public sharing REST module. Every function here is a direct Toucan 2 call with+ no additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++;;; ------------------------------------------------------ Cards -------------------------------------------------------++(defn public-card+ "The non-archived Card with `card-id`, restricted to the columns safe to expose publicly, or nil. With+ `:enable-embedding? true`, additionally requires embedding to be enabled."+ [card-id & {:keys [enable-embedding?]}]+ (t2/select-one [:model/Card :id :dataset_query :description :display :name :parameters :visualization_settings+ :card_schema]+ {:where [:and+ [:= :id card-id]+ [:= :archived false]+ (when enable-embedding? [:= :enable_embedding true])]}))++(defn active-card+ "The non-archived Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id :archived false))++(defn active-card-in-document+ "The non-archived Card with `card-id` that belongs to the Document with `document-id`, or nil."+ [card-id document-id]+ (t2/select-one :model/Card :id card-id :document_id document-id :archived false))++;;; ---------------------------------------------------- Dashboards ----------------------------------------------------++(defn public-dashboard+ "The non-archived Dashboard with `dashboard-id`, restricted to the columns safe to expose publicly, or nil. With+ `:enable-embedding? true`, additionally requires embedding to be enabled."+ [dashboard-id & {:keys [enable-embedding?]}]+ (t2/select-one [:model/Dashboard :name :description :id :parameters :auto_apply_filters :width]+ {:where [:and+ [:= :id dashboard-id]+ [:= :archived false]+ (when enable-embedding? [:= :enable_embedding true])]}))++(defn dashcard+ "The DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one :model/DashboardCard :id dashcard-id))++(defn dashcard-id-in-dashboard+ "`dashcard-id` if that DashboardCard belongs to the Dashboard with `dashboard-id`, otherwise nil."+ [dashcard-id dashboard-id]+ (t2/select-one-pk :model/DashboardCard :id dashcard-id :dashboard_id dashboard-id))++;;; ----------------------------------------------------- Documents ----------------------------------------------------++(defn public-document+ "The non-archived Document with `document-id`, restricted to the columns safe to expose publicly."+ [document-id]+ (t2/select-one [:model/Document :id :name :document :content_type :created_at :updated_at]+ :id document-id, :archived false))++(defn document-content+ "The id, content, and content type of the Document with `document-id`, or nil."+ [document-id]+ (t2/select-one [:model/Document :id :document :content_type] :id document-id))diff --git a/src/metabase/pulse/api/alert.clj b/src/metabase/pulse/api/alert.cljindex d632d6f5e77..a56ed499a97 100644--- a/src/metabase/pulse/api/alert.clj+++ b/src/metabase/pulse/api/alert.clj@@ -9,9 +9,9 @@[metabase.classloader.core :as classloader][metabase.config.core :as config][metabase.notification.api :as notification.api]+ [metabase.pulse.db :as pulse.db][metabase.util.cron :as u.cron]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)@@ -23,7 +23,7 @@[notification](let [subscription (-> notification :subscriptions first)notification-card (-> notification :payload)- card (->> notification :payload :card_id (t2/select-one :model/Card))]+ card (->> notification :payload :card_id pulse.db/card)](merge(select-keys notification [:id :creator_id :creator :created_at :updated_at]){:name nildiff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.cljindex 91cc6fcfee5..27e17a216c1 100644--- a/src/metabase/pulse/api/pulse.clj+++ b/src/metabase/pulse/api/pulse.clj@@ -20,6 +20,7 @@[metabase.parameters.schema :as parameters.schema][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features]+ [metabase.pulse.db :as pulse.db][metabase.pulse.models.pulse :as models.pulse][metabase.pulse.models.pulse-channel :as pulse-channel][metabase.pulse.send :as pulse.send]@@ -82,7 +83,7 @@(update pulse :cards(fn [cards](mapv (fn [card] (assoc card :download_perms (case (perms/download-perms-level- (or (:dataset_query card) (t2/select-one-fn :dataset_query [:model/Card :dataset_query] (:id card)))+ (or (:dataset_query card) (pulse.db/card-query (:id card)))api/*current-user-id*):no :none:ten-thousand-rows :limited@@ -327,7 +328,7 @@(let [chan-types (-> pulse-channel/channel-types(assoc-in [:slack :configured] (channel.settings/slack-configured?))(assoc-in [:email :configured] (channel.settings/email-configured?))- (assoc-in [:http :configured] (t2/exists? :model/Channel :type :channel/http :active true)))]+ (assoc-in [:http :configured] (pulse.db/active-http-channel-exists?)))]{:channels (cond(perms/sandboxed-or-impersonated-user?)(dissoc chan-types :slack)@@ -403,10 +404,10 @@"For users to unsubscribe themselves from a pulse subscription."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (api/let-404 [pulse-id (t2/select-one-pk :model/Pulse :id id)- pc-id (t2/select-one-pk :model/PulseChannel :pulse_id pulse-id :channel_type "email")- pcr-id (t2/select-one-pk :model/PulseChannelRecipient :pulse_channel_id pc-id :user_id api/*current-user-id*)]- (t2/delete! :model/PulseChannelRecipient :id pcr-id))+ (api/let-404 [pulse-id (pulse.db/pulse-id id)+ pc-id (pulse.db/email-pulse-channel-id pulse-id)+ pcr-id (pulse.db/pulse-channel-recipient-id pc-id api/*current-user-id*)]+ (pulse.db/delete-pulse-channel-recipient! pcr-id))api/generic-204-no-content)(def ^{:arglists '([request respond raise])} routesdiff --git a/src/metabase/pulse/api/unsubscribe.clj b/src/metabase/pulse/api/unsubscribe.cljindex 5000de276ce..56516a81e7f 100644--- a/src/metabase/pulse/api/unsubscribe.clj+++ b/src/metabase/pulse/api/unsubscribe.clj@@ -7,6 +7,7 @@[metabase.channel.email.messages :as messages][metabase.config.core :as config][metabase.events.core :as events]+ [metabase.pulse.db :as pulse.db][metabase.pulse.models.pulse :as models.pulse][metabase.request.core :as request][metabase.util.i18n :refer [tru]]@@ -41,10 +42,10 @@request](check-hash pulse-id email hash (request/ip-address request))(t2/with-transaction [_conn]- (api/let-404 [pulse-channel (t2/select-one :model/PulseChannel :pulse_id pulse-id :channel_type "email")]+ (api/let-404 [pulse-channel (pulse.db/email-pulse-channel pulse-id)](let [emails (get-in pulse-channel [:details :emails])](if (some #{email} emails)- (t2/update! :model/PulseChannel (:id pulse-channel) (update-in pulse-channel [:details :emails] #(remove #{email} %)))+ (pulse.db/update-pulse-channel! (:id pulse-channel) (update-in pulse-channel [:details :emails] #(remove #{email} %)))(throw (ex-info (tru "Email for pulse-id doesn''t exist."){:type type:status-code 400}))))@@ -66,12 +67,12 @@request](check-hash pulse-id email hash (request/ip-address request))(t2/with-transaction [_conn]- (api/let-404 [pulse-channel (t2/select-one :model/PulseChannel :pulse_id pulse-id :channel_type "email")]+ (api/let-404 [pulse-channel (pulse.db/email-pulse-channel pulse-id)](let [emails (get-in pulse-channel [:details :emails])](if (some #{email} emails)(throw (ex-info (tru "Email for pulse-id already exists."){:type type:status-code 400}))- (t2/update! :model/PulseChannel (:id pulse-channel) (update-in pulse-channel [:details :emails] conj email))))+ (pulse.db/update-pulse-channel! (:id pulse-channel) (update-in pulse-channel [:details :emails] conj email))))(events/publish-event! :event/subscription-unsubscribe-undo {:object {:email email}}){:status :success :title (:name (models.pulse/retrieve-notification pulse-id :archived false))})))diff --git a/src/metabase/pulse/db.clj b/src/metabase/pulse/db.cljnew file mode 100644index 00000000000..21f61fd80a9--- /dev/null+++ b/src/metabase/pulse/db.clj@@ -0,0 +1,360 @@+(ns metabase.pulse.db+ "Application database queries for the pulse module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card card-id))++(defn card-query+ "The query of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :dataset_query [:model/Card :dataset_query] card-id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn dashboard-collection-id+ "The Collection id of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one-fn :collection_id :model/Dashboard, :id dashboard-id))++(defn dashcard-ids-by-card+ "A map of Card id to DashboardCard id for the DashboardCards of the Dashboard with `dashboard-id` showing one of+ `card-ids`."+ [dashboard-id card-ids]+ (t2/select-fn->pk :card_id :model/DashboardCard :dashboard_id dashboard-id :card_id [:in card-ids]))++(defn channel+ "The Channel with `channel-id`, or nil."+ [channel-id]+ (t2/select-one :model/Channel :id channel-id))++(defn active-http-channel-exists?+ "Whether an active HTTP Channel exists."+ []+ (t2/exists? :model/Channel :type :channel/http :active true))++(defn superusers+ "The superusers."+ []+ (t2/select :model/User :is_superuser true))++(defn user-emails-by-id+ "A map of User id to email for the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn :email :model/User, :id [:in user-ids]))++(defn pulse+ "The Pulse with `pulse-id`, or nil."+ [pulse-id]+ (t2/select-one :model/Pulse :id pulse-id))++(defn pulse-id+ "The id of the Pulse with `pulse-id` if it exists, or nil."+ [pulse-id]+ (t2/select-one-pk :model/Pulse :id pulse-id))++(defn unarchived-pulse+ "The unarchived Pulse with `pulse-id`, or nil."+ [pulse-id]+ (t2/select-one :model/Pulse :id pulse-id :archived false))++(defn unarchived-non-alert-pulse+ "The unarchived, non-alert Pulse with `pulse-id`, or nil."+ [pulse-id]+ (t2/select-one :model/Pulse :id pulse-id :archived false :alert_condition nil))++(defn alert+ "The Pulse with `pulse-id` if it is an alert, or nil."+ [pulse-id]+ (t2/select-one :model/Pulse, :id pulse-id, :alert_condition [:not= nil]))++(defn alerts+ "The alert-type Pulses (unarchived unless `archived?`), optionally narrowed to those with a recipient or creator+ `user-id`, ordered by lower-cased name."+ [archived? user-id]+ (t2/select :model/Pulse+ (merge {:select-distinct [:p.* [[:lower :p.name] :lower-name]]+ :from [[:pulse :p]]+ :where [:and+ [:not= :p.alert_condition nil]+ [:= :p.archived archived?]+ (when user-id+ [:or+ [:= :p.creator_id user-id]+ [:= :pcr.user_id user-id]])]+ :order-by [[:lower-name :asc]]}+ (when user-id+ {:left-join [[:pulse_channel :pchan] [:= :p.id :pchan.pulse_id]+ [:pulse_channel_recipient :pcr] [:= :pchan.id :pcr.pulse_channel_id]]}))))++(defn pulses+ "The dashboard-subscription Pulses (unarchived unless `archived?`), optionally narrowed to `dashboard-id` and/or+ those with a recipient or creator `user-id`, ordered by lower-cased name."+ [archived? dashboard-id user-id]+ (t2/select :model/Pulse+ {:select-distinct [:p.* [[:lower :p.name] :lower-name]]+ :from [[:pulse :p]]+ :left-join (concat+ [[:report_dashboard :d] [:= :p.dashboard_id :d.id]]+ (when user-id+ [[:pulse_channel :pchan] [:= :p.id :pchan.pulse_id]+ [:pulse_channel_recipient :pcr] [:= :pchan.id :pcr.pulse_channel_id]]))+ :where [:and+ [:= :p.alert_condition nil]+ [:= :p.archived archived?]+ [:or+ [:= :p.dashboard_id nil]+ [:= :d.archived false]]+ (when dashboard-id+ [:= :p.dashboard_id dashboard-id])+ (when user-id+ [:and+ [:not= :p.dashboard_id nil]+ [:or+ [:= :p.creator_id user-id]+ [:= :pcr.user_id user-id]]])]+ :order-by [[:lower-name :asc]]}))++(defn alerts-for-card-and-user+ "The alert-type Pulses (unarchived unless `archived?`) on the Card with `card-id` that the User with `user-id` is+ set to receive."+ [card-id user-id archived?]+ (t2/select :model/Pulse+ {:select [:p.*]+ :from [[:pulse :p]]+ :join [[:pulse_card :pc] [:= :p.id :pc.pulse_id]+ [:pulse_channel :pchan] [:= :pchan.pulse_id :p.id]+ [:pulse_channel_recipient :pcr] [:= :pchan.id :pcr.pulse_channel_id]]+ :where [:and+ [:not= :p.alert_condition nil]+ [:= :pc.card_id card-id]+ [:= :pcr.user_id user-id]+ [:= :p.archived archived?]]}))++(defn alerts-for-cards+ "The alert-type Pulses (unarchived unless `archived?`) on any of the Cards with `card-ids`."+ [card-ids archived?]+ (t2/select :model/Pulse+ {:select [:p.*]+ :from [[:pulse :p]]+ :join [[:pulse_card :pc] [:= :p.id :pc.pulse_id]]+ :where [:and+ [:not= :p.alert_condition nil]+ [:in :pc.card_id card-ids]+ [:= :p.archived archived?]]}))++(defn legacy-pulse-count+ "The number of unarchived Pulses that are neither dashboard subscriptions nor alerts."+ []+ (t2/count :model/Pulse :dashboard_id nil :alert_condition nil :archived false))++(defn legacy-pulses+ "The unarchived Pulses that are neither dashboard subscriptions nor alerts."+ []+ (t2/select :model/Pulse :dashboard_id nil :alert_condition nil :archived false))++(defn insert-pulse!+ "Insert the Pulse `pulse` and return the inserted instance."+ [pulse]+ (t2/insert-returning-instance! :model/Pulse pulse))++(defn update-pulse!+ "Apply `changes` to the Pulse with `pulse-id`."+ [pulse-id changes]+ (t2/update! :model/Pulse pulse-id changes))++(defn update-pulses-for-dashboard!+ "Apply `changes` to the Pulses of the Dashboard with `dashboard-id`."+ [dashboard-id changes]+ (t2/update! :model/Pulse {:dashboard_id dashboard-id} changes))++(defn pulse-cards-for-pulses+ "The Cards of the Pulses with `pulse-ids` together with their PulseCard options, in position order. Excludes+ archived Cards unless `include-archived?`."+ [pulse-ids include-archived?]+ (t2/select+ :model/Card+ {:select [:c.id :c.name :c.description :c.collection_id :c.display :pc.include_csv :pc.include_xls :pc.format_rows :pc.pivot_results+ :pc.dashboard_card_id :dc.dashboard_id [nil :parameter_mappings] [:p.id :pulse_id]] ;; :dc.parameter_mappings - how do you select this?+ :from [[:pulse :p]]+ :join [[:pulse_card :pc] [:= :p.id :pc.pulse_id]+ [:report_card :c] [:= :c.id :pc.card_id]]+ :left-join [[:report_dashboardcard :dc] [:= :pc.dashboard_card_id :dc.id]]+ :where [:and+ [:in :p.id pulse-ids]+ (when-not include-archived? [:= :c.archived false])]+ :order-by [[:pc.position :asc]]}))++(defn pulse-card-refs+ "The Card id (as `:id`), export options, and DashboardCard id of the PulseCards of the Pulse with `pulse-id`, in+ position order."+ [pulse-id]+ (t2/select [:model/PulseCard [:card_id :id] :include_csv :include_xls :dashboard_card_id]+ :pulse_id pulse-id+ {:order-by [[:position :asc]]}))++(defn max-pulse-card-position+ "The `:max` position of the PulseCards of the Pulse with `pulse-id`."+ [pulse-id]+ (t2/select-one [:model/PulseCard [:%max.position :max]] :pulse_id pulse-id))++(defn insert-pulse-cards!+ "Insert the PulseCard `rows`."+ [rows]+ (t2/insert! :model/PulseCard rows))++(defn delete-pulse-cards-for-pulse!+ "Delete the PulseCards of the Pulse with `pulse-id`."+ [pulse-id]+ (t2/delete! :model/PulseCard :pulse_id pulse-id))++(defn pulse-channels-for-pulse+ "The PulseChannels of the Pulse with `pulse-id`."+ [pulse-id]+ (t2/select :model/PulseChannel :pulse_id pulse-id))++(defn pulse-channels-for-pulses+ "The PulseChannels of the Pulses with `pulse-ids`."+ [pulse-ids]+ (t2/select :model/PulseChannel :pulse_id [:in pulse-ids]))++(defn email-pulse-channel+ "The email PulseChannel of the Pulse with `pulse-id`, or nil."+ [pulse-id]+ (t2/select-one :model/PulseChannel :pulse_id pulse-id :channel_type "email"))++(defn email-pulse-channel-id+ "The id of the email PulseChannel of the Pulse with `pulse-id`, or nil."+ [pulse-id]+ (t2/select-one-pk :model/PulseChannel :pulse_id pulse-id :channel_type "email"))++(defn pulse-channel-details+ "The details of the PulseChannel with `channel-id`, or nil."+ [channel-id]+ (t2/select-one-fn :details :model/PulseChannel :id channel-id))++(defn pulse-channels-without-recipients+ "The id, details, Channel, and type of the PulseChannels of the Pulse with `pulse-id` that have no recipients."+ [pulse-id]+ (t2/select [:model/PulseChannel :id :details :channel_id :channel_type]+ {:where [:and+ [:= :pulse_id pulse-id]+ [:not [:exists ^:allow-subquery+ {:select [1]+ :from [:pulse_channel_recipient]+ :where [:= :pulse_channel_recipient.pulse_channel_id+ :pulse_channel.id]}]]]}))++(defn enabled-pulse-channel-ids+ "The ids among `channel-ids` of enabled PulseChannels, or nil."+ [channel-ids]+ (t2/select-pks-set :model/PulseChannel :id [:in channel-ids] :enabled true))++(defn active-dashboard-subscription-channels+ "The enabled PulseChannels of dashboard subscriptions whose Dashboard is not archived."+ []+ (t2/select :model/PulseChannel+ {:select [:pc.*]+ :from [[:pulse_channel :pc]]+ :left-join [[:pulse :p] [:= :pc.pulse_id :p.id]+ [:report_dashboard :d] [:= :p.dashboard_id :d.id]]+ :where [:and+ [:= :pc.enabled true]+ ;; only do this for dashboard subscriptions, alert has been+ ;; migrated to notifications+ [:not= :p.dashboard_id nil]+ [:= :d.archived false]]}))++(defn other-pulse-channel-count+ "The number of PulseChannels of the Pulse with `pulse-id` other than `channel-id`."+ [pulse-id channel-id]+ (t2/count :model/PulseChannel :pulse_id pulse-id, :id [:not= channel-id]))++(defn insert-pulse-channel!+ "Insert the PulseChannel `row` and return its id."+ [row]+ (t2/insert-returning-pk! :model/PulseChannel row))++(defn update-pulse-channel!+ "Apply `changes` to the PulseChannel with `channel-id`."+ [channel-id changes]+ (t2/update! :model/PulseChannel channel-id changes))++(defn set-pulse-channels-enabled!+ "Set the enabled flag of the PulseChannels of the Pulse with `pulse-id`."+ [pulse-id enabled?]+ (t2/update! :model/PulseChannel :pulse_id pulse-id {:enabled enabled?}))++(defn delete-pulse-channel!+ "Delete the PulseChannel with `channel-id`."+ [channel-id]+ (t2/delete! :model/PulseChannel :id channel-id))++(defn delete-pulse-channels!+ "Delete the PulseChannels with `channel-ids`."+ [channel-ids]+ (t2/delete! :model/PulseChannel :id [:in channel-ids]))++(defn delete-pulse-channels-for-pulse!+ "Delete the PulseChannels of the Pulse with `pulse-id`."+ [pulse-id]+ (t2/delete! :model/PulseChannel :pulse_id pulse-id))++(defn active-recipients-for-channels+ "The id, email, name, and PulseChannel id of the active User recipients of the PulseChannels with `channel-ids`, in+ User id order."+ [channel-ids]+ (t2/select [:model/User :id :email :first_name :last_name :pcr.pulse_channel_id]+ {:left-join [[:pulse_channel_recipient :pcr] [:= :core_user.id :pcr.user_id]]+ :where [:and+ [:in :pcr.pulse_channel_id channel-ids]+ [:= :core_user.is_active true]]+ :order-by [[:core_user.id :asc]]}))++(defn pulse-channel-recipient-id+ "The id of the PulseChannelRecipient of the User with `user-id` on the PulseChannel with `channel-id`, or nil."+ [channel-id user-id]+ (t2/select-one-pk :model/PulseChannelRecipient :pulse_channel_id channel-id :user_id user-id))++(defn pulse-channel-recipient-user-ids+ "The User ids of the PulseChannelRecipients of the PulseChannel with `channel-id`."+ [channel-id]+ (t2/select-fn-set :user_id :model/PulseChannelRecipient, :pulse_channel_id channel-id))++(defn other-pulse-channel-recipient-count+ "The number of PulseChannelRecipients of the PulseChannel with `channel-id` other than `recipient-id`."+ [channel-id recipient-id]+ (t2/count :model/PulseChannelRecipient :pulse_channel_id channel-id :id [:not= recipient-id]))++(defn insert-pulse-channel-recipients!+ "Insert the PulseChannelRecipient `rows`."+ [rows]+ (t2/insert! :model/PulseChannelRecipient rows))++(defn delete-pulse-channel-recipient!+ "Delete the PulseChannelRecipient with `recipient-id`."+ [recipient-id]+ (t2/delete! :model/PulseChannelRecipient :id recipient-id))++(defn delete-pulse-channel-recipients-raw!+ "Delete the PulseChannelRecipients of the Users with `user-ids` on the PulseChannel with `channel-id`, without+ running model hooks."+ [channel-id user-ids]+ (t2/delete! (t2/table-name :model/PulseChannelRecipient) :pulse_channel_id channel-id :user_id [:in user-ids]))++(defn delete-notifications!+ "Delete the Notifications with `notification-ids`."+ [notification-ids]+ (t2/delete! :model/Notification :id [:in notification-ids]))++(defn user-tenant-ids+ "A map of User ID to `:tenant_id` for `user-ids`."+ [user-ids]+ (t2/select-pk->fn :tenant_id :model/User :id [:in user-ids]))diff --git a/src/metabase/pulse/events/dashboard_subscription.clj b/src/metabase/pulse/events/dashboard_subscription.cljindex d70fdf5edd1..987a08b5bff 100644--- a/src/metabase/pulse/events/dashboard_subscription.clj+++ b/src/metabase/pulse/events/dashboard_subscription.clj@@ -3,6 +3,7 @@[clojure.set :as set][metabase.app-db.core :as app-db][metabase.events.core :as events]+ [metabase.pulse.db :as pulse.db][metabase.pulse.models.pulse :as models.pulse][metabase.pulse.models.pulse-card :as pulse-card][metabase.util :as u]@@ -35,8 +36,7 @@set)cards-to-add (set/difference correct-card-ids stale-card-ids)card-id->dashcard-id (when (seq cards-to-add)- (t2/select-fn->pk :card_id :model/DashboardCard :dashboard_id dashboard-id- :card_id [:in cards-to-add]))+ (pulse.db/dashcard-ids-by-card dashboard-id cards-to-add))positions-for (fn [pulse-id] (drop (pulse-card/next-position-for pulse-id)(range)))new-pulse-cards (for [pulse-id pulse-ids@@ -49,13 +49,13 @@:position position})](t2/with-transaction [_conn](binding [models.pulse/*allow-moving-dashboard-subscriptions* true]- (t2/update! :model/Pulse {:dashboard_id dashboard-id}- ;; TODO we probably don't need this anymore- ;; pulse.name is no longer used for generating title.- ;; pulse.collection_id is a thing for the old "Pulse" feature, but it was removed- {:name (:name dashboard)- :collection_id (:collection_id dashboard)- ;; not allowing updated_at to change because this is usually triggered after a "last_viewed_at" update on dashboard which doesn't warrant a pulse update.- ;; plus, the name and collection_id are not really used for anything so it's fine they don't trigger a pulse update_at change even if they do change.- :updated_at :updated_at})+ (pulse.db/update-pulses-for-dashboard! dashboard-id+ ;; TODO we probably don't need this anymore+ ;; pulse.name is no longer used for generating title.+ ;; pulse.collection_id is a thing for the old "Pulse" feature, but it was removed+ {:name (:name dashboard)+ :collection_id (:collection_id dashboard)+ ;; not allowing updated_at to change because this is usually triggered after a "last_viewed_at" update on dashboard which doesn't warrant a pulse update.+ ;; plus, the name and collection_id are not really used for anything so it's fine they don't trigger a pulse update_at change even if they do change.+ :updated_at :updated_at})(pulse-card/bulk-create! new-pulse-cards)))))))diff --git a/src/metabase/pulse/models/pulse.clj b/src/metabase/pulse/models/pulse.cljindex 734f3542f21..7d32604ac04 100644--- a/src/metabase/pulse/models/pulse.clj+++ b/src/metabase/pulse/models/pulse.clj@@ -25,6 +25,7 @@[metabase.events.core :as events][metabase.models.interface :as mi][metabase.permissions.core :as perms]+ [metabase.pulse.db :as pulse.db][metabase.pulse.models.pulse-channel :as pulse-channel][metabase.util :as u][metabase.util.i18n :refer [deferred-tru tru]]@@ -63,7 +64,7 @@(let [defaults {:parameters []}dashboard-id (:dashboard_id notification)collection-id (if dashboard-id- (t2/select-one-fn :collection_id 'Dashboard, :id dashboard-id)+ (pulse.db/dashboard-collection-id dashboard-id)(:collection_id notification))notification (->> (for [[k v] notification:when (some? v)]@@ -91,8 +92,8 @@(throw (ex-info (tru "collection ID of a dashboard subscription cannot be directly modified") notification)))(when (contains? changes :archived)(if (:archived changes)- (t2/update! :model/PulseChannel :pulse_id (u/the-id notification) {:enabled false})- (t2/update! :model/PulseChannel :pulse_id (u/the-id notification) {:enabled true})))+ (pulse.db/set-pulse-channels-enabled! (u/the-id notification) false)+ (pulse.db/set-pulse-channels-enabled! (u/the-id notification) true)))(when (and dashboard_id(contains? notification :dashboard_id)(not= (:dashboard_id notification) dashboard_id))@@ -104,7 +105,7 @@(t2/define-before-delete :model/Pulse[pulse];; to trigger deleting the scheduled jobs- (t2/delete! :model/PulseChannel :pulse_id (u/the-id pulse)))+ (pulse.db/delete-pulse-channels-for-pulse! (u/the-id pulse)))(defn- alert->card"Return the Card associated with an Alert, fetching it if needed, for permissions-checking purposes."@@ -172,7 +173,7 @@"Return true if the card has attachments and those can be read. If it has no attachments, return true"[card](if (or (:include_csv card) (:include_xls card))- (let [level (perms/download-perms-level (or (:dataset_query card) (t2/select-one-fn :dataset_query :model/Card :id (:id card))) api/*current-user-id*)]+ (let [level (perms/download-perms-level (or (:dataset_query card) (pulse.db/card-query (:id card))) api/*current-user-id*)](and level (not= level :no)))true))@@ -243,7 +244,7 @@[_model k pulses](mi/instances-with-hydrated-datapulses k- #(group-by :pulse_id (t2/select :model/PulseChannel :pulse_id [:in (map :id pulses)]))+ #(group-by :pulse_id (pulse.db/pulse-channels-for-pulses (map :id pulses))):id{:default []}))@@ -254,19 +255,7 @@(mu/defn- cards* :- [:sequential HybridPulseCard][pulse-ids]- (t2/select- :model/Card- {:select [:c.id :c.name :c.description :c.collection_id :c.display :pc.include_csv :pc.include_xls :pc.format_rows :pc.pivot_results- :pc.dashboard_card_id :dc.dashboard_id [nil :parameter_mappings] [:p.id :pulse_id]] ;; :dc.parameter_mappings - how do you select this?- :from [[:pulse :p]]- :join [[:pulse_card :pc] [:= :p.id :pc.pulse_id]- [:report_card :c] [:= :c.id :pc.card_id]]- :left-join [[:report_dashboardcard :dc] [:= :pc.dashboard_card_id :dc.id]]- :where [:and- [:in :p.id pulse-ids]- (when-not *allow-hydrate-archived-cards*- [:= :c.archived false])]- :order-by [[:pc.position :asc]]}))+ (pulse.db/pulse-cards-for-pulses pulse-ids *allow-hydrate-archived-cards*))(methodical/defmethod t2/batched-hydrate [:model/Pulse :cards][_model k pulses]@@ -305,7 +294,7 @@"Fetch a single *Pulse*, and hydrate it with a set of 'standard' hydrations; remove Alert columns, since this is a*Pulse* and they will all be unset."[pulse-or-id]- (some-> (t2/select-one :model/Pulse :id (u/the-id pulse-or-id))+ (some-> (pulse.db/pulse (u/the-id pulse-or-id))hydrate-notificationnotification->pulse))@@ -314,8 +303,13 @@`:cards`."[notification-or-id & additional-conditions]{:pre [(even? (count additional-conditions))]}- (some-> (apply t2/select-one :model/Pulse :id (u/the-id notification-or-id), additional-conditions)- hydrate-notification))+ (let [id (u/the-id notification-or-id)+ opts (apply hash-map additional-conditions)]+ (some-> (cond+ (contains? opts :alert_condition) (pulse.db/unarchived-non-alert-pulse id)+ (contains? opts :archived) (pulse.db/unarchived-pulse id)+ :else (pulse.db/pulse id))+ hydrate-notification)))(mu/defn- notification->alert :- (ms/InstanceOf :model/Pulse)"Take a generic `Notification` and put it in the standard `Alert` format the frontend expects. This really just@@ -331,13 +325,10 @@(mu/defn retrieve-alert :- [:maybe (ms/InstanceOf :model/Pulse)]"Fetch a single Alert by its `id` value, do the standard hydrations, and put it in the standard `Alert` format."[alert-or-id]- (some-> (t2/select-one :model/Pulse, :id (u/the-id alert-or-id), :alert_condition [:not= nil])+ (some-> (pulse.db/alert (u/the-id alert-or-id))hydrate-notificationnotification->alert))-(defn- query-as [model query]- (t2/select model query))-(mu/defn retrieve-alerts :- [:sequential (ms/InstanceOf :model/Pulse)]"Fetch all Alerts."([]@@ -346,62 +337,24 @@([{:keys [archived? user-id]:or {archived? false}}](assert boolean? archived?)- (let [query (merge {:select-distinct [:p.* [[:lower :p.name] :lower-name]]- :from [[:pulse :p]]- :where [:and- [:not= :p.alert_condition nil]- [:= :p.archived archived?]- (when user-id- [:or- [:= :p.creator_id user-id]- [:= :pcr.user_id user-id]])]- :order-by [[:lower-name :asc]]}- (when user-id- {:left-join [[:pulse_channel :pchan] [:= :p.id :pchan.pulse_id]- [:pulse_channel_recipient :pcr] [:= :pchan.id :pcr.pulse_channel_id]]}))]- (for [alert (hydrate-notifications (query-as :model/Pulse query))- :let [alert (notification->alert alert)]- ;; if for whatever reason the Alert doesn't have a Card associated with it (e.g. the Card was deleted) don't- ;; return the Alert -- it's basically orphaned/invalid at this point. See #13575 -- we *should* be deleting- ;; Alerts if their associated PulseCard is deleted, but that's not currently the case.- :when (:card alert)]- alert))))+ (for [alert (hydrate-notifications (pulse.db/alerts archived? user-id))+ :let [alert (notification->alert alert)]+ ;; if for whatever reason the Alert doesn't have a Card associated with it (e.g. the Card was deleted) don't+ ;; return the Alert -- it's basically orphaned/invalid at this point. See #13575 -- we *should* be deleting+ ;; Alerts if their associated PulseCard is deleted, but that's not currently the case.+ :when (:card alert)]+ alert)))(mu/defn retrieve-pulses :- [:sequential (ms/InstanceOf :model/Pulse)]"Fetch all `Pulses`. When `user-id` is included, only fetches `Pulses` for which the provided user is the creatoror a recipient."[{:keys [archived? dashboard-id user-id]:or {archived? false}}]- (let [query {:select-distinct [:p.* [[:lower :p.name] :lower-name]]- :from [[:pulse :p]]- :left-join (concat- [[:report_dashboard :d] [:= :p.dashboard_id :d.id]]- (when user-id- [[:pulse_channel :pchan] [:= :p.id :pchan.pulse_id]- [:pulse_channel_recipient :pcr] [:= :pchan.id :pcr.pulse_channel_id]]))- :where [:and- [:= :p.alert_condition nil]- [:= :p.archived archived?]- ;; Only return dashboard subscriptions for non-archived dashboards- [:or- [:= :p.dashboard_id nil]- [:= :d.archived false]]- (when dashboard-id- [:= :p.dashboard_id dashboard-id])- ;; Only return dashboard subscriptions when `user-id` is passed, so that legacy- ;; pulses don't show up in the notification management page- (when user-id- [:and- [:not= :p.dashboard_id nil]- [:or- [:= :p.creator_id user-id]- [:= :pcr.user_id user-id]]])]- :order-by [[:lower-name :asc]]}]- (for [pulse (query-as :model/Pulse query)]- (-> pulse- (dissoc :lower-name)- hydrate-notification- notification->pulse))))+ (for [pulse (pulse.db/pulses archived? dashboard-id user-id)]+ (-> pulse+ (dissoc :lower-name)+ hydrate-notification+ notification->pulse)))(defn- tenant-scoped-caller?"True when the current user's recipient visibility is narrowed to their own tenant. Superusers and@@ -417,7 +370,7 @@nil and filters nothing (or, once the caller has a tenant, drops every recipient)."[recipient-ids](if (seq recipient-ids)- (t2/select-pk->fn :tenant_id :model/User :id [:in recipient-ids])+ (pulse.db/user-tenant-ids recipient-ids){}))(defn- recipient-visible-to-tenant-caller?@@ -507,17 +460,7 @@[:archived? {:optional true} boolean?]]](assert boolean? archived?)(map (comp notification->alert hydrate-notification)- (query-as :model/Pulse- {:select [:p.*]- :from [[:pulse :p]]- :join [[:pulse_card :pc] [:= :p.id :pc.pulse_id]- [:pulse_channel :pchan] [:= :pchan.pulse_id :p.id]- [:pulse_channel_recipient :pcr] [:= :pchan.id :pcr.pulse_channel_id]]- :where [:and- [:not= :p.alert_condition nil]- [:= :pc.card_id card-id]- [:= :pcr.user_id user-id]- [:= :p.archived archived?]]})))+ (pulse.db/alerts-for-card-and-user card-id user-id archived?)))(mu/defn retrieve-alerts-for-cards"Find all alerts for `card-ids`, used for admin users"@@ -529,14 +472,7 @@[:archived? {:optional true} boolean?]]](when (seq card-ids)(map (comp notification->alert hydrate-notification)- (query-as :model/Pulse- {:select [:p.*]- :from [[:pulse :p]]- :join [[:pulse_card :pc] [:= :p.id :pc.pulse_id]]- :where [:and- [:not= :p.alert_condition nil]- [:in :pc.card_id card-ids]- [:= :p.archived archived?]]}))))+ (pulse.db/alerts-for-cards card-ids archived?))))(mu/defn card->ref :- CardRef"Create a card reference from a card or id"@@ -559,7 +495,7 @@* All cards will be updated with a `position` according to their place in the collection of `card-ids`"[notification-or-id card-refs :- [:maybe [:sequential CardRef]]];; first off, just delete any cards associated with this pulse (we add them again below)- (t2/delete! :model/PulseCard :pulse_id (u/the-id notification-or-id))+ (pulse.db/delete-pulse-cards-for-pulse! (u/the-id notification-or-id));; now just insert all of the cards that were given to us(when (seq card-refs)(let [cards (map-indexed (fn [i {card-id :id :keys [include_csv include_xls format_rows pivot_results dashboard_card_id]}]@@ -572,7 +508,7 @@:pivot_results pivot_results:dashboard_card_id dashboard_card_id})card-refs)]- (t2/insert! :model/PulseCard cards))))+ (pulse.db/insert-pulse-cards! cards))))(mu/defn update-notification-channels!"Update the PulseChannels for a given `notification-or-id`. `channels` should be a definitive collection of *all* of@@ -584,7 +520,7 @@* All previously existing channels will be updated with their most recent information."[notification-or-id channels :- [:sequential :map]]- (let [existing-channels (t2/select :model/PulseChannel :pulse_id (u/the-id notification-or-id))+ (let [existing-channels (pulse.db/pulse-channels-for-pulse (u/the-id notification-or-id))channels (map-indexed(fn [idx channel](assoc channel@@ -612,14 +548,14 @@(binding [pulse-channel/*archive-parent-pulse-when-last-channel-is-deleted* false](when (seq to-delete)(assert (every? :id to-delete) "Cannot delete a PulseChannel without an :id")- (t2/delete! :model/PulseChannel :id [:in (map :id to-delete)])))))+ (pulse.db/delete-pulse-channels! (map :id to-delete))))))(mu/defn- create-notification-and-add-cards-and-channels!"Create a new Pulse/Alert with the properties specified in `notification`; add the `card-refs` to the Notification andadd the Notification to `channels`. Returns the `id` of the newly created Notification."[notification card-refs :- [:maybe [:sequential CardRef]] channels](t2/with-transaction [_conn]- (let [notification (first (t2/insert-returning-instances! :model/Pulse notification))]+ (let [notification (pulse.db/insert-pulse! notification)](update-notification-cards! notification card-refs)(update-notification-channels! notification channels)(u/the-id notification))))@@ -657,9 +593,7 @@(mu/defn- notification-or-id->existing-card-refs :- [:sequential CardRef][notification-or-id]- (t2/select [:model/PulseCard [:card_id :id] :include_csv :include_xls :dashboard_card_id]- :pulse_id (u/the-id notification-or-id)- {:order-by [[:position :asc]]}))+ (pulse.db/pulse-card-refs (u/the-id notification-or-id)))(mu/defn- card-refs-have-changed? :- :boolean[notification-or-id new-card-refs :- [:sequential CardRef]]@@ -685,10 +619,10 @@[:channels {:optional true} [:sequential :map]][:archived {:optional true} boolean?][:parameters {:optional true} [:maybe [:sequential :map]]]]]- (t2/update! :model/Pulse (u/the-id notification)- (u/select-keys-when notification- :present [:collection_id :collection_position :archived]- :non-nil [:name :alert_condition :alert_above_goal :alert_first_only :skip_if_empty :parameters]))+ (pulse.db/update-pulse! (u/the-id notification)+ (u/select-keys-when notification+ :present [:collection_id :collection_position :archived]+ :non-nil [:name :alert_condition :alert_above_goal :alert_first_only :skip_if_empty :parameters]));; update Cards if the 'refs' have changed(when (contains? notification :cards)(update-notification-cards-if-changed! notification (map card->ref (:cards notification))))diff --git a/src/metabase/pulse/models/pulse_card.clj b/src/metabase/pulse/models/pulse_card.cljindex 557deecafdd..03de8f4f97d 100644--- a/src/metabase/pulse/models/pulse_card.clj+++ b/src/metabase/pulse/models/pulse_card.clj@@ -1,5 +1,6 @@(ns metabase.pulse.models.pulse-card(:require+ [metabase.pulse.db :as pulse.db][metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]@@ -16,7 +17,7 @@"Return the next available `pulse_card.position` for the given `pulse`"[pulse-id]{:pre [(integer? pulse-id)]}- (-> (t2/select-one [:model/PulseCard [:%max.position :max]] :pulse_id pulse-id)+ (-> (pulse.db/max-pulse-card-position pulse-id):max(some-> inc)(or 0)))@@ -36,13 +37,13 @@"Creates new PulseCards, joining the given card, pulse, and dashboard card and setting appropriate defaults for othervalues if they're not provided."[new-pulse-cards :- [:sequential NewPulseCard]]- (t2/insert! :model/PulseCard- (for [{:keys [card_id pulse_id dashboard_card_id position include_csv include_xls format_rows pivot_results]} new-pulse-cards]- {:card_id card_id- :pulse_id pulse_id- :dashboard_card_id dashboard_card_id- :position (u/or-with some? position (next-position-for pulse_id))- :include_csv (boolean include_csv)- :include_xls (boolean include_xls)- :format_rows (boolean format_rows)- :pivot_results (boolean pivot_results)})))+ (pulse.db/insert-pulse-cards!+ (for [{:keys [card_id pulse_id dashboard_card_id position include_csv include_xls format_rows pivot_results]} new-pulse-cards]+ {:card_id card_id+ :pulse_id pulse_id+ :dashboard_card_id dashboard_card_id+ :position (u/or-with some? position (next-position-for pulse_id))+ :include_csv (boolean include_csv)+ :include_xls (boolean include_xls)+ :format_rows (boolean format_rows)+ :pivot_results (boolean pivot_results)})))diff --git a/src/metabase/pulse/models/pulse_channel.clj b/src/metabase/pulse/models/pulse_channel.cljindex cef2bf33634..ccc48a1e32e 100644--- a/src/metabase/pulse/models/pulse_channel.clj+++ b/src/metabase/pulse/models/pulse_channel.clj@@ -4,6 +4,7 @@[medley.core :as m][metabase.models.interface :as mi][metabase.notification.models :as notification.models]+ [metabase.pulse.db :as pulse.db][metabase.util :as u][metabase.util.i18n :refer [tru]][methodical.core :as methodical]@@ -130,12 +131,7 @@[_model _k pcs](when (seq pcs)(let [pcid->recipients (-> (group-by :pulse_channel_id- (t2/select [:model/User :id :email :first_name :last_name :pcr.pulse_channel_id]- {:left-join [[:pulse_channel_recipient :pcr] [:= :core_user.id :pcr.user_id]]- :where [:and- [:in :pcr.pulse_channel_id (map :id pcs)]- [:= :core_user.is_active true]]- :order-by [[:core_user.id :asc]]}))+ (pulse.db/active-recipients-for-channels (map :id pcs)))(update-vals #(map (fn [user] (dissoc user :pulse_channel_id)) %)))](for [pc pcs](assoc pc :recipients (concat@@ -157,9 +153,9 @@;; This function is called by [[metabase.pulse.models.pulse-channel/pre-delete]] when the `PulseChannel` is about to;; be deleted. Archives `Pulse` if the channel being deleted is its last channel."(when *archive-parent-pulse-when-last-channel-is-deleted*- (let [other-channels-count (t2/count :model/PulseChannel :pulse_id pulse-id, :id [:not= pulse-channel-id])]+ (let [other-channels-count (pulse.db/other-pulse-channel-count pulse-id pulse-channel-id)](when (zero? other-channels-count)- (t2/update! :model/Pulse pulse-id {:archived true}))))+ (pulse.db/update-pulse! pulse-id {:archived true}))));; it's best if this is done in after-delete, but toucan2 doesn't support that yet See toucan2#70S;; remove this pulse from its existing trigger(update-send-pulse-trigger-if-needed! pulse-id pulse-channel :remove-pc-ids #{(:id pulse-channel)}))@@ -188,7 +184,7 @@;; be sneaky and pass in a valid User ID but different email so they can send test Pulses out to arbitrary email;; addresses(when-let [user-ids (not-empty (into #{} (comp (filter some?) (map :id)) user-recipients))]- (let [user-id->email (t2/select-pk->fn :email :model/User, :id [:in user-ids])]+ (let [user-id->email (pulse.db/user-emails-by-id user-ids)](doseq [{:keys [id email]} user-recipients:let [correct-email (get user-id->email id)]](when-not correct-email@@ -243,17 +239,15 @@{:pre [(integer? id)(coll? user-ids)(every? integer? user-ids)]}- (let [recipients-old (set (t2/select-fn-set :user_id :model/PulseChannelRecipient, :pulse_channel_id id))+ (let [recipients-old (set (pulse.db/pulse-channel-recipient-user-ids id))recipients-new (set user-ids)recipients+ (set/difference recipients-new recipients-old)recipients- (set/difference recipients-old recipients-new)](when (seq recipients+)(let [vs (map #(assoc {:pulse_channel_id id} :user_id %) recipients+)]- (t2/insert! :model/PulseChannelRecipient vs)))+ (pulse.db/insert-pulse-channel-recipients! vs)))(when (seq recipients-)- (t2/delete! (t2/table-name :model/PulseChannelRecipient)- :pulse_channel_id id- :user_id [:in recipients-]))))+ (pulse.db/delete-pulse-channel-recipients-raw! id recipients-))))(defn update-pulse-channel!"Updates an existing `PulseChannel` along with all related data associated with the channel such as@@ -269,17 +263,17 @@(coll? recipients)(every? map? recipients)]}(let [recipients-by-type (group-by integer? (filter identity (map #(or (:id %) (:email %)) recipients)))]- (t2/update! :model/PulseChannel id- {:details (cond-> details- (supports-recipients? channel_type) (assoc :emails (get recipients-by-type false)))- :enabled enabled- :schedule_type schedule_type- :schedule_hour (when (not= schedule_type :hourly)- schedule_hour)- :schedule_day (when (contains? #{:weekly :monthly} schedule_type)- schedule_day)- :schedule_frame (when (= schedule_type :monthly)- schedule_frame)})+ (pulse.db/update-pulse-channel! id+ {:details (cond-> details+ (supports-recipients? channel_type) (assoc :emails (get recipients-by-type false)))+ :enabled enabled+ :schedule_type schedule_type+ :schedule_hour (when (not= schedule_type :hourly)+ schedule_hour)+ :schedule_day (when (contains? #{:weekly :monthly} schedule_type)+ schedule_day)+ :schedule_frame (when (= schedule_type :monthly)+ schedule_frame)})(when (supports-recipients? channel_type)(update-recipients! id (or (get recipients-by-type true) [])))))@@ -297,21 +291,20 @@(coll? recipients)(every? map? recipients)]}(let [recipients-by-type (group-by integer? (filter identity (map #(or (:id %) (:email %)) recipients)))- id (t2/insert-returning-pk!- :model/PulseChannel- :pulse_id pulse_id- :channel_type channel_type- :channel_id channel_id- :details (cond-> details- (supports-recipients? channel_type) (assoc :emails (get recipients-by-type false)))- :enabled enabled- :schedule_type schedule_type- :schedule_hour (when (not= schedule_type :hourly)- schedule_hour)- :schedule_day (when (contains? #{:weekly :monthly} schedule_type)- schedule_day)- :schedule_frame (when (= schedule_type :monthly)- schedule_frame))]+ id (pulse.db/insert-pulse-channel!+ {:pulse_id pulse_id+ :channel_type channel_type+ :channel_id channel_id+ :details (cond-> details+ (supports-recipients? channel_type) (assoc :emails (get recipients-by-type false)))+ :enabled enabled+ :schedule_type schedule_type+ :schedule_hour (when (not= schedule_type :hourly)+ schedule_hour)+ :schedule_day (when (contains? #{:weekly :monthly} schedule_type)+ schedule_day)+ :schedule_frame (when (= schedule_type :monthly)+ schedule_frame)})](when (and (supports-recipients? channel_type) (seq (get recipients-by-type true)))(update-recipients! id (get recipients-by-type true)));; return the id of our newly created channeldiff --git a/src/metabase/pulse/models/pulse_channel_recipient.clj b/src/metabase/pulse/models/pulse_channel_recipient.cljindex 0e85fcdeec8..17575bcfd32 100644--- a/src/metabase/pulse/models/pulse_channel_recipient.clj+++ b/src/metabase/pulse/models/pulse_channel_recipient.clj@@ -1,5 +1,6 @@(ns metabase.pulse.models.pulse-channel-recipient(:require+ [metabase.pulse.db :as pulse.db][methodical.core :as methodical][toucan2.core :as t2]))@@ -12,13 +13,11 @@;;; automatically deleted.(t2/define-before-delete :model/PulseChannelRecipient[{channel-id :pulse_channel_id, pulse-channel-recipient-id :id}]- (let [other-recipients-count (t2/count :model/PulseChannelRecipient- :pulse_channel_id channel-id- :id [:not= pulse-channel-recipient-id])+ (let [other-recipients-count (pulse.db/other-pulse-channel-recipient-count channel-id pulse-channel-recipient-id)last-recipient? (zero? other-recipients-count)](when last-recipient?;; make sure this channel doesn't have any email-address (non-User) recipients.- (let [details (t2/select-one-fn :details :model/PulseChannel :id channel-id)+ (let [details (pulse.db/pulse-channel-details channel-id)has-email-addresses? (seq (:emails details))](when-not has-email-addresses?- (t2/delete! :model/PulseChannel :id channel-id))))))+ (pulse.db/delete-pulse-channel! channel-id))))))diff --git a/src/metabase/pulse/send.clj b/src/metabase/pulse/send.cljindex c19230823ff..e569525bc86 100644--- a/src/metabase/pulse/send.clj+++ b/src/metabase/pulse/send.clj@@ -2,11 +2,11 @@"Code related to sending Pulses (Alerts or Dashboard Subscriptions)."(:require[metabase.models.interface :as mi]+ [metabase.pulse.db :as pulse.db][metabase.pulse.models.pulse :as models.pulse][metabase.task-history.core :as task-history][metabase.util.cron :as u.cron]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -48,7 +48,7 @@Only supports HTTP channels for now, returns a map with type key for slack and email"[{channel-type :channel_type :as pulse-channel}](if (= :http (keyword channel-type))- (t2/select-one :model/Channel :id (:channel_id pulse-channel))+ (pulse.db/channel (:channel_id pulse-channel)){:type (keyword "channel" (name channel-type))}))(defn- get-notification-handler@@ -149,7 +149,7 @@;; with-task-run is a no-op if already nested (e.g., from scheduler)(task-history/with-task-run (some-> (pulse->task-run-info pulse)(assoc :auto-complete (not async?)))- (let [dashboard (t2/select-one :model/Dashboard :id dashboard_id)+ (let [dashboard (pulse.db/dashboard dashboard_id)pulse (-> (mi/instance :model/Pulse pulse);; This is usually already done by this step, in the `send-pulses` task which uses `retrieve-pulse`;; to fetch the Pulse.diff --git a/src/metabase/pulse/task/email_remove_legacy_pulse.clj b/src/metabase/pulse/task/email_remove_legacy_pulse.cljindex d84b059ecd4..9071059b8f8 100644--- a/src/metabase/pulse/task/email_remove_legacy_pulse.clj+++ b/src/metabase/pulse/task/email_remove_legacy_pulse.clj@@ -6,14 +6,14 @@[metabase.channel.settings :as channel.settings][metabase.channel.template.core :as channel.template][metabase.channel.urls :as urls]+ [metabase.pulse.db :as pulse.db][metabase.task.core :as task]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)(defn- has-legacy-pulse? []- (pos? (t2/count :model/Pulse :dashboard_id nil :alert_condition nil :archived false)))+ (pos? (pulse.db/legacy-pulse-count)))(def ^:private template-name "warn_deprecate_pulse")@@ -21,9 +21,9 @@(when (and (channel.settings/email-configured?)(has-legacy-pulse?))(log/info "Sending email to admins about removal of legacy pulses")- (let [legacy-pulse (->> (t2/select :model/Pulse :dashboard_id nil :alert_condition nil :archived false)+ (let [legacy-pulse (->> (pulse.db/legacy-pulses)(map #(assoc % :url (urls/legacy-pulse-url (:id %)))))]- (doseq [admin (t2/select :model/User :is_superuser true)]+ (doseq [admin (pulse.db/superusers)](email/send-email-retrying!{:recipients [(:email admin)]:message-type :htmldiff --git a/src/metabase/pulse/task/send_pulses.clj b/src/metabase/pulse/task/send_pulses.cljindex d5ddf7fa879..95892700ebd 100644--- a/src/metabase/pulse/task/send_pulses.clj+++ b/src/metabase/pulse/task/send_pulses.clj@@ -12,6 +12,7 @@[clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers][metabase.driver :as driver]+ [metabase.pulse.db :as pulse.db][metabase.pulse.models.pulse :as models.pulse][metabase.pulse.send :as pulse.send][metabase.query-processor.timezone :as qp.timezone]@@ -20,8 +21,7 @@[metabase.tracing.core :as tracing][metabase.util.cron :as u.cron][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(java.util TimeZone)(org.quartz CronTrigger DisallowConcurrentExecution JobExecutionContext TriggerKey)))@@ -109,14 +109,7 @@[pulse-id](tracing/with-span :tasks "task.pulse.clear-orphan-channels" {:pulse/id pulse-id}(when-let [ids-to-delete (seq- (for [channel (t2/select [:model/PulseChannel :id :details :channel_id :channel_type]- {:where [:and- [:= :pulse_id pulse-id]- [:not [:exists ^:allow-subquery- {:select [1]- :from [:pulse_channel_recipient]- :where [:= :pulse_channel_recipient.pulse_channel_id- :pulse_channel.id]}]]]})+ (for [channel (pulse.db/pulse-channels-without-recipients pulse-id):when (case (:channel_type channel)(empty? (get-in channel [:details :emails]))@@ -126,7 +119,7 @@(nil? (:channel_id channel)))](:id channel)))](log/infof "Deleting %d PulseChannels with id: %s due to having no recipients" (count ids-to-delete) (str/join ", " ids-to-delete))- (t2/delete! :model/PulseChannel :id [:in ids-to-delete])+ (pulse.db/delete-pulse-channels! ids-to-delete)(set ids-to-delete))))(defn- send-pulse!*@@ -136,7 +129,7 @@[pulse-id channel-ids](let [cleared-channel-ids (clear-pulse-channels-no-recipients! pulse-id)to-send-channel-ids (set/difference channel-ids cleared-channel-ids)- to-send-enabled-channel-ids (t2/select-pks-set :model/PulseChannel :id [:in to-send-channel-ids] :enabled true)]+ to-send-enabled-channel-ids (pulse.db/enabled-pulse-channel-ids to-send-channel-ids)](if (seq to-send-enabled-channel-ids)(send-pulse! pulse-id to-send-enabled-channel-ids)(log/infof "Skip sending pulse %d because all channels have no recipients" pulse-id))))@@ -182,17 +175,7 @@(defn- active-dashsub-pcs[]- (t2/select :model/PulseChannel- {:select [:pc.*]- :from [[:pulse_channel :pc]]- :left-join [[:pulse :p] [:= :pc.pulse_id :p.id]- [:report_dashboard :d] [:= :p.dashboard_id :d.id]]- :where [:and- [:= :pc.enabled true]- ;; only do this for dashboard subscriptions, alert has been- ;; migrated to notifications- [:not= :p.dashboard_id nil]- [:= :d.archived false]]}))+ (pulse.db/active-dashboard-subscription-channels))(defn init-dashboard-subscription-triggers!"Update send pulse triggers for all active pulses.diff --git a/src/metabase/pulse/update_alerts.clj b/src/metabase/pulse/update_alerts.cljindex d6f90e7ee9b..fd251fdc289 100644--- a/src/metabase/pulse/update_alerts.clj+++ b/src/metabase/pulse/update_alerts.clj@@ -4,8 +4,8 @@[metabase.events.core :as events][metabase.lib.core :as lib][metabase.notification.models :as models.notification]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.pulse.db :as pulse.db]+ [metabase.util.malli :as mu]))(defn- card-archived? [old-card new-card](and (not (:archived old-card))@@ -58,7 +58,7 @@"Removes all of the alerts and notifies all of the email recipients of the alerts change."[topic actor card](when-let [card-notifications (seq (models.notification/notifications-for-card (:id card)))]- (t2/delete! :model/Notification :id [:in (map :id card-notifications)])+ (pulse.db/delete-notifications! (map :id card-notifications))(events/publish-event! topic {:card card:actor actor:notifications card-notifications})))diff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.cljnew file mode 100644index 00000000000..793104f3a0c--- /dev/null+++ b/src/metabase/queries/db.clj@@ -0,0 +1,450 @@+(ns metabase.queries.db+ "Application database queries for the queries module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions and hydration+ methods."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++;;; ------------------------------------------------ Cards ------------------------------------------------++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn cards+ "The Cards with `card-ids`."+ [card-ids]+ (t2/select :model/Card :id [:in card-ids]))++(defn card-query-info+ "The query, type, result metadata, and schema of the Card with `card-id`."+ [card-id]+ (t2/select-one [:model/Card :dataset_query :type :result_metadata :card_schema] :id card-id))++(defn card-dataset-query+ "The `:dataset_query` of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :dataset_query [:model/Card :dataset_query :card_schema] :id card-id))++(defn card-document-id+ "The `:document_id` of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :document_id :model/Card :id card-id))++(defn card-parameters+ "The `:parameters` of the Card with `card-id`."+ [card-id]+ (t2/select-one-fn :parameters [:model/Card :parameters] :id card-id))++(defn card-dimensions+ "The raw `:dimensions` row of the Card with `card-id`."+ [card-id]+ (t2/query-one {:select [:dimensions]+ :from [:report_card]+ :where [:= :id card-id]}))++(defn card-database-and-table-ids+ "The database and primary table IDs of the Card with `card-id`, as `:database-id` and `:table-id`."+ [card-id]+ (t2/select-one [:model/Card [:database_id :database-id] [:table_id :table-id]] :id card-id))++(defn card-queries+ "The IDs and queries of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :dataset_query :card_schema] :id [:in card-ids]))++(defn source-card-dependents+ "The IDs and source Card IDs of the Cards whose source Card is one of `source-card-ids`."+ [source-card-ids]+ (t2/select [:model/Card :id :source_card_id :card_schema] :source_card_id [:in source-card-ids]))++(defn metric-cards-for-source-cards+ "The unarchived metric Cards built on one of `source-card-ids`, ordered by name."+ [source-card-ids]+ (t2/select :model/Card+ :source_card_id [:in source-card-ids]+ :archived false+ :type :metric+ {:order-by [[:name :asc]]}))++(defn document-card-ids+ "The IDs of the Cards that belong to the Document with `document-id`."+ [document-id]+ (t2/select-pks-set :model/Card :document_id document-id))++(defn insert-card!+ "Insert `card` and return the new instance."+ [card]+ (t2/insert-returning-instance! :model/Card card))++(defn update-card!+ "Apply `changes` to the Card with `card-id`."+ [card-id changes]+ (t2/update! :model/Card card-id changes))++;;; ------------------------------------------- Card statistics -------------------------------------------++(defn dashcard-counts-by-card+ "Rows of `:card_id` and `:count` of DashboardCards for each of `card-ids`."+ [card-ids]+ (t2/query {:select [[:%count.* :count] :card_id]+ :from [:report_dashboardcard]+ :where [:in :card_id card-ids]+ :group-by [:card_id]}))++(defn parameter-card-counts-by-card+ "Rows of `:card_id` and `:count` of ParameterCards for each of `card-ids`."+ [card-ids]+ (t2/query {:select [[:%count.* :count] :card_id]+ :from [:parameter_card]+ :where [:in :card_id card-ids]+ :group-by [:card_id]}))++(defn average-running-times-by-card+ "Rows of `:card_id` and average `:running_time` of uncached executions for each of `card-ids`."+ [card-ids]+ (t2/query {:select [[:%avg.running_time :running_time] :card_id]+ :from [:query_execution]+ :where [:and+ [:not= :running_time nil]+ [:not= :cache_hit true]+ [:in :card_id card-ids]]+ :group-by [:card_id]}))++(defn last-query-starts-by-card+ "Rows of `:card_id` and latest `:started_at` of uncached executions for each of `card-ids`."+ [card-ids]+ (t2/query {:select [[:%max.started_at :started_at] :card_id]+ :from [:query_execution]+ :where [:and+ [:not= :running_time nil]+ [:not= :cache_hit true]+ [:in :card_id card-ids]]+ :group-by [:card_id]}))++(defn dashboards-for-cards+ "Rows of `:card_id` plus Dashboard columns for every Dashboard each of `card-ids` appears on, directly or as a series."+ [card-ids]+ (t2/query {:union-all [^:allow-subquery {:nest+ ^:allow-subquery {:select [[:dc.card_id :card_id]+ :d.name+ :d.collection_id+ :d.description+ :d.id+ :d.archived+ :d.enable_embedding]+ :from [[:report_dashboardcard :dc]]+ :join [[:report_dashboard :d] [:= :dc.dashboard_id :d.id]]+ :where [:in :dc.card_id card-ids]+ :order-by [[:d.id :asc]]}}+ ^:allow-subquery {:nest+ ^:allow-subquery {:select [[:dcs.card_id :card_id]+ :d.name+ :d.collection_id+ :d.description+ :d.id+ :d.archived+ :d.enable_embedding]+ :from [[:dashboardcard_series :dcs]]+ :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]+ [:report_dashboard :d] [:= :d.id :dc.dashboard_id]]+ :where [:in :dcs.card_id card-ids]+ :order-by [[:d.id :asc]]}}]}))++;;; ------------------------------------------- Related models --------------------------------------------++(defn databases+ "The Databases with `database-ids`."+ [database-ids]+ (t2/select :model/Database :id [:in database-ids]))++(defn database-name+ "The name of the Database with `database-id`."+ [database-id]+ (t2/select-one-fn :name :model/Database :id database-id))++(defn field-database-info-for-ids+ "The id, name, table name, and Database id of the Fields with `field-ids`."+ [field-ids]+ (t2/query {:select [[:field.id :field-id]+ [:field.name :field-name]+ [:table.name :table-name]+ [:table.db_id :field-db-id]]+ :from [[:metabase_field :field]]+ :left-join [[:metabase_table :table]+ [:= :field.table_id :table.id]]+ :where [:in :field.id field-ids]}))++(defn field-table-ids+ "The set of Table IDs of the Fields with `field-ids`."+ [field-ids]+ (t2/select-fn-set :table_id :model/Field :id [:in field-ids]))++(defn snippets+ "The NativeQuerySnippets with `snippet-ids`."+ [snippet-ids]+ (t2/select :model/NativeQuerySnippet :id [:in snippet-ids]))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn dashboards+ "The Dashboards with `dashboard-ids`."+ [dashboard-ids]+ (t2/select :model/Dashboard :id [:in dashboard-ids]))++(defn dashboard-collection-id+ "The `:collection_id` of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-one-fn :collection_id [:model/Dashboard :collection_id] :id dashboard-id))++(defn dashboard-parameters+ "The `:parameters` of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-one-fn :parameters [:model/Dashboard :parameters] :id dashboard-id))++(defn update-dashboard!+ "Apply `changes` to the Dashboard with `dashboard-id`."+ [dashboard-id changes]+ (t2/update! :model/Dashboard dashboard-id changes))++(defn dashcards-for-card+ "The DashboardCards showing the Card with `card-id`."+ [card-id]+ (t2/select :model/DashboardCard :card_id card-id))++(defn insert-dashcard!+ "Insert `dashcard`."+ [dashcard]+ (t2/insert! :model/DashboardCard dashcard))++(defn update-dashcard!+ "Apply `changes` to the DashboardCard with `dashcard-id`."+ [dashcard-id changes]+ (t2/update! :model/DashboardCard :id dashcard-id changes))++(defn delete-dashcards-for-card-on-dashboard!+ "Delete the DashboardCards showing the Card with `card-id` on the Dashboard with `dashboard-id`."+ [card-id dashboard-id]+ (t2/delete! :model/DashboardCard :card_id card-id :dashboard_id dashboard-id))++(defn delete-dashcards-for-card-off-dashboard!+ "Delete the DashboardCards showing the Card with `card-id` on any Dashboard other than `dashboard-id`."+ [card-id dashboard-id]+ (t2/delete! :model/DashboardCard :card_id card-id :dashboard_id [:not= dashboard-id]))++(defn dashcard-series-for-card-on-dashboard+ "The IDs of the DashboardCardSeries showing the Card with `card-id` on the Dashboard with `dashboard-id`."+ [card-id dashboard-id]+ (t2/query {:select [[:dcs.id]]+ :from [[:dashboardcard_series :dcs]]+ :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]]+ :where [:and+ [:= :dc.dashboard_id dashboard-id]+ [:= :dcs.card_id card-id]]}))++(defn dashcard-series-for-card-off-dashboard+ "The IDs of the DashboardCardSeries showing the Card with `card-id` on any Dashboard other than `dashboard-id`."+ [card-id dashboard-id]+ (t2/query {:select [[:dcs.id]]+ :from [[:dashboardcard_series :dcs]]+ :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]]+ :where [:and+ [:= :dcs.card_id card-id]+ [:not= :dc.dashboard_id dashboard-id]]}))++(defn delete-dashcard-series!+ "Delete the DashboardCardSeries with `series-ids`."+ [series-ids]+ (t2/delete! :model/DashboardCardSeries :id [:in series-ids]))++(defn implicit-action-ids-for-model+ "The IDs of the implicit Actions of the model Card with `model-id`."+ [model-id]+ (t2/select-pks-set :model/Action {:select [:action.id]+ :from [:action]+ :join [:implicit_action [:= :action.id :implicit_action.action_id]]+ :where [:= :action.model_id model-id]}))++(defn delete-actions!+ "Delete the Actions with `action-ids`."+ [action-ids]+ (t2/delete! :model/Action :id [:in action-ids]))++(defn archive-explicit-actions-for-model!+ "Archive the non-implicit Actions of the model Card with `model-id`."+ [model-id]+ (t2/update! :model/Action {:model_id model-id :type [:not= :implicit]} {:archived true}))++(defn delete-implicit-actions-for-model!+ "Delete the implicit Actions of the model Card with `model-id`."+ [model-id]+ (t2/delete! :model/Action :model_id model-id :type :implicit))++(defn delete-card-moderation-reviews!+ "Delete the ModerationReviews of the Card with `card-id`."+ [card-id]+ (t2/delete! :model/ModerationReview :moderated_item_type "card" :moderated_item_id card-id))++(defn delete-card-revisions!+ "Delete the Revisions of the Card with `card-id`."+ [card-id]+ (t2/delete! :model/Revision :model "Card" :model_id card-id))++(defn card-notification-ids+ "The IDs of the card Notifications attached to the Card with `card-id`."+ [card-id]+ (t2/select-pks-set :model/Notification+ :payload_type :notification/card+ :payload_id [:in ^:allow-subquery {:select [:id]+ :from [:notification_card]+ :where [:= :card_id card-id]}]))++(defn delete-notifications!+ "Delete the Notifications with `notification-ids`."+ [notification-ids]+ (t2/delete! :model/Notification :id [:in notification-ids]))++;;; --------------------------------------------- ParameterCard ---------------------------------------------++(defn parameter-cards-for-card+ "The ParameterCards drawing values from the Card with `card-id`."+ [card-id]+ (t2/select :model/ParameterCard :card_id card-id))++(defn parameter-card-card-ids+ "The set of Card IDs the parameters of the given parameterized object draw values from."+ [object-type object-id]+ (t2/select-fn-set :card_id :model/ParameterCard+ :parameterized_object_type object-type+ :parameterized_object_id object-id))++(defn parameter-card-exists?+ "Whether the given parameter of the given parameterized object has a ParameterCard."+ [object-type object-id parameter-id]+ (t2/exists? :model/ParameterCard+ :parameterized_object_type object-type+ :parameterized_object_id object-id+ :parameter_id parameter-id))++(defn set-parameter-card-card-id!+ "Point the ParameterCard of the given parameter of the given parameterized object at `card-id`."+ [object-type object-id parameter-id card-id]+ (t2/update! :model/ParameterCard+ {:parameterized_object_type object-type+ :parameterized_object_id object-id+ :parameter_id parameter-id}+ {:card_id card-id}))++(defn insert-parameter-card!+ "Insert `parameter-card`."+ [parameter-card]+ (t2/insert! :model/ParameterCard parameter-card))++(defn delete-parameter-cards-for-card!+ "Delete the ParameterCards drawing values from the Card with `card-id`."+ [card-id]+ (t2/delete! :model/ParameterCard :card_id card-id))++(defn delete-parameter-cards-for-object!+ "Delete every ParameterCard of the given parameterized object."+ [object-type object-id]+ (t2/delete! :model/ParameterCard+ :parameterized_object_type object-type+ :parameterized_object_id object-id))++(defn delete-parameter-cards-for-object-except!+ "Delete the ParameterCards of the given parameterized object whose parameter is not one of `parameter-ids`."+ [object-type object-id parameter-ids]+ (t2/delete! :model/ParameterCard+ :parameterized_object_type object-type+ :parameterized_object_id object-id+ :parameter_id [:not-in parameter-ids]))++;;; -------------------------------------------------- Query --------------------------------------------------++(defn average-execution-time+ "The recorded average execution time of the query with `query-hash`."+ [query-hash]+ (t2/select-one-fn :average_execution_time :model/Query :query_hash query-hash))++(defn- int-casting-type+ "MySQL doesn't accept `integer`, so we have to use `unsigned`; Postgres doesn't accept `unsigned` so we have to use+ `integer`. Yay SQL dialect differences :D"+ []+ (if (= (mdb/db-type) :mysql)+ :unsigned+ :integer))++(defn- rolling-average-expr+ [c0 c1]+ (h2x/cast (int-casting-type)+ (h2x/round (h2x/+ (h2x/* c0 :average_execution_time)+ c1)+ [:inline 0])))++(defn backfill-query-and-average-execution-time!+ "Set the query text and average execution time (`c0 * average_execution_time + c1`, rounded and cast to an integer)+ of the query with `query-hash` if its text was never stored."+ [query-hash query-json c0 c1]+ (t2/update! :model/Query+ {:query_hash query-hash, :query nil}+ {:query query-json+ :average_execution_time (rolling-average-expr c0 c1)}))++(defn update-average-execution-time!+ "Set the average execution time of the query with `query-hash` to `c0 * average_execution_time + c1`, rounded and+ cast to an integer."+ [query-hash c0 c1]+ (t2/update! :model/Query {:query_hash query-hash} {:average_execution_time (rolling-average-expr c0 c1)}))++(defn update-average-execution-times!+ "Set the average execution time of each Query identified by the `[query-hash c0 c1]` triples in `hash+coefficients`+ to `c0 * average_execution_time + c1`, rounded and cast to an integer."+ [hash+coefficients]+ (t2/query {:update (t2/table-name :model/Query)+ :set {:average_execution_time (into [:case]+ (mapcat (fn [[query-hash c0 c1]]+ [[:= :query_hash query-hash] (rolling-average-expr c0 c1)]))+ hash+coefficients)}+ :where [:in :query_hash (map first hash+coefficients)]}))++(defn insert-queries!+ "Insert the Query `rows`."+ [rows]+ (t2/insert! :model/Query rows))++(defn query-hash-statuses-reducible+ "Reducible rows of `:query_hash` and `:missing_query` for the Query rows with `query-hashes`."+ [query-hashes]+ (t2/reducible-query {:select [:query_hash [[:= :query nil] :missing_query]]+ :from [(t2/table-name :model/Query)]+ :where [:in :query_hash query-hashes]}))++;;; ---------------------------------------------- StoredResult ----------------------------------------------++(defn stored-result-ids-used-by-cards+ "The subset of `stored-result-ids` used by one of the Cards with `card-ids`."+ [card-ids stored-result-ids]+ (t2/select-fn-set :stored_result_id :model/StoredResultUse+ :card_id [:in card-ids]+ :stored_result_id [:in stored-result-ids]))++(defn insert-stored-result-use!+ "Record that the Card with `card-id` uses the StoredResult with `stored-result-id`."+ [stored-result-id card-id]+ (t2/insert! :model/StoredResultUse {:stored_result_id stored-result-id+ :card_id card-id}))++(defn stored-results-for-card+ "The StoredResults used by the Card with `card-id`."+ [card-id]+ (t2/select :model/StoredResult+ :id [:in ^:allow-subquery {:select [:stored_result_id]+ :from [:stored_result_use]+ :where [:= :card_id card-id]}]))diff --git a/src/metabase/queries/metadata.clj b/src/metabase/queries/metadata.cljindex 9b1229f1209..2c2db3c26ea 100644--- a/src/metabase/queries/metadata.clj+++ b/src/metabase/queries/metadata.clj@@ -11,6 +11,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi][metabase.permissions.core :as perms]+ [metabase.queries.db :as queries.db][metabase.queries.schema :as queries.schema][metabase.util :as u][metabase.util.malli :as mu]@@ -45,18 +46,18 @@(perms/prime-database-perms-cache {:db-ids (set ids)})(into [] (comp (filter mi/can-read?)(map #(assoc % :native_permissions (get-native-perms-info %))))- (t2/select :model/Database :id [:in ids]))))+ (queries.db/databases ids))))(defn- field-ids->table-ids[field-ids](if (seq field-ids)- (t2/select-fn-set :table_id :model/Field :id [:in field-ids])+ (queries.db/field-table-ids field-ids)#{}))(defn- collect-recursive-snippets([initial-snippet-ids](when (seq initial-snippet-ids)- (let [snippets (into [] (filter mi/can-read?) (t2/select :model/NativeQuerySnippet :id [:in initial-snippet-ids]))]+ (let [snippets (into [] (filter mi/can-read?) (queries.db/snippets initial-snippet-ids))](collect-recursive-snippets (set snippets) snippets (set initial-snippet-ids)))))([all-snippets snippets-to-recurse seen-ids](let [->nested-snippet-ids (fn [snippet]@@ -69,7 +70,7 @@snippet-id)))nested-snippet-ids (into #{} (mapcat ->nested-snippet-ids) snippets-to-recurse)nested-snippets (when (seq nested-snippet-ids)- (into [] (filter mi/can-read?) (t2/select :model/NativeQuerySnippet :id [:in nested-snippet-ids])))]+ (into [] (filter mi/can-read?) (queries.db/snippets nested-snippet-ids)))](if-not (seq nested-snippet-ids)all-snippets(recur (into all-snippets nested-snippets)@@ -191,7 +192,7 @@[:set ::lib.schema.id/card]]]](when (seq ids)(let [cards (into [] (filter mi/can-read?)- (t2/select :model/Card :id [:in ids]))]+ (queries.db/cards ids))](t2/hydrate cards :can_write))))(defn- dashcard->click-behaviors [dashcard]@@ -204,11 +205,9 @@(defn- batch-fetch-linked-dashboards[dashboard-ids](when (seq dashboard-ids)- (let [dashboards (->> (t2/select :model/Dashboard :id [:in dashboard-ids])+ (let [dashboards (->> (queries.db/dashboards dashboard-ids)(filter mi/can-read?))]- (t2/hydrate dashboards- :can_write- :param_fields))))+ (t2/hydrate dashboards :can_write :param_fields))))(defn- batch-fetch-dashboard-links[dashcards]diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex d0e314ff7b2..2fcd9f5ea4b 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -7,7 +7,6 @@[medley.core :as m][metabase.analytics-interface.core :as analytics][metabase.api.common :as api]- [metabase.app-db.core :as app-db][metabase.audit-app.core :as audit][metabase.cache.core :as cache][metabase.collections.core :as collections]@@ -35,6 +34,7 @@[metabase.premium-features.core :refer [defenterprise]][metabase.public-sharing.core :as public-sharing][metabase.pulse.core :as pulse]+ [metabase.queries.db :as queries.db][metabase.queries.models.card.metadata :as card.metadata][metabase.queries.models.parameter-card :as parameter-card][metabase.queries.models.query :as query]@@ -105,15 +105,13 @@(defmethod metrics/save-dimensions! :metadata/metric[metric dimensions dimension-mappings](when-let [metric-id (:id metric)]- (t2/update! :model/Card metric-id- {:dimensions dimensions- :dimension_mappings dimension-mappings})))+ (queries.db/update-card! metric-id+ {:dimensions dimensions+ :dimension_mappings dimension-mappings})))(defmethod metrics/dimensions-initialized? :metadata/metric[metric]- (some? (:dimensions (t2/query-one {:select [:dimensions]- :from [:report_card]- :where [:= :id (:id metric)]}))))+ (some? (:dimensions (queries.db/card-dimensions (:id metric)))))(t2/deftransforms :model/Card{:dataset_query lib-be/transform-query@@ -150,7 +148,7 @@[card](cond(contains? card :document_id) (:document_id card)- (:id card) (t2/select-one-fn :document_id :model/Card :id (:id card))+ (:id card) (queries.db/card-document-id (:id card)):else ::not-adjudicable))(defn- parent-document-permits?@@ -186,7 +184,7 @@(and (perms/can-read-via-parent-collection? (:collection_id instance))(parent-document-permits? instance :read)))([_ pk]- (mi/can-read? (t2/select-one :model/Card :id pk))))+ (mi/can-read? (queries.db/card pk))))(defmethod mi/can-write? :model/Card([instance]@@ -201,7 +199,7 @@(mi/current-user-has-full-permissions? (mi/perms-objects-set instance :write))(parent-document-permits? instance :write)))([_ pk]- (mi/can-write? (t2/select-one :model/Card :id pk))))+ (mi/can-write? (queries.db/card pk))))(defn model?"Returns true if `card` is a model."@@ -227,10 +225,7 @@(mi/instances-with-hydrated-datacards k(fn []- (->> (t2/query {:select [[:%count.* :count] :card_id]- :from [:report_dashboardcard]- :where [:in :card_id (map :id cards)]- :group-by [:card_id]})+ (->> (queries.db/dashcard-counts-by-card (map :id cards))(map (juxt :card_id :count))(into {}))):id@@ -242,33 +237,7 @@cards k(fn [](let [card-ids (map u/the-id cards)- all-dashboards (t2/query {:union-all [;; First get dashboards from direct card connections- ^:allow-subquery {:nest- ^:allow-subquery {:select [[:dc.card_id :card_id]- :d.name- :d.collection_id- :d.description- :d.id- :d.archived- :d.enable_embedding]- :from [[:report_dashboardcard :dc]]- :join [[:report_dashboard :d] [:= :dc.dashboard_id :d.id]]- :where [:in :dc.card_id [:inline card-ids]]- :order-by [[:d.id :asc]]}}- ;; Then get dashboards from series- ^:allow-subquery {:nest- ^:allow-subquery {:select [[:dcs.card_id :card_id]- :d.name- :d.collection_id- :d.description- :d.id- :d.archived- :d.enable_embedding]- :from [[:dashboardcard_series :dcs]]- :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]- [:report_dashboard :d] [:= :d.id :dc.dashboard_id]]- :where [:in :dcs.card_id [:inline card-ids]]- :order-by [[:d.id :asc]]}}]})]+ all-dashboards (queries.db/dashboards-for-cards card-ids)](update-vals(group-by :card_id all-dashboards)(fn [dashes]@@ -299,10 +268,7 @@[_model k cards](mi/instances-with-hydrated-datacards k- #(->> (t2/query {:select [[:%count.* :count] :card_id]- :from [:parameter_card]- :where [:in :card_id (map :id cards)]- :group-by [:card_id]})+ #(->> (queries.db/parameter-card-counts-by-card (map :id cards))(map (juxt :card_id :count))(into {})):id@@ -312,13 +278,7 @@[_model k cards](mi/instances-with-hydrated-datacards k- #(->> (t2/query {:select [[:%avg.running_time :running_time] :card_id]- :from [:query_execution]- :where [:and- [:not= :running_time nil]- [:not= :cache_hit true]- [:in :card_id (map :id cards)]]- :group-by [:card_id]})+ #(->> (queries.db/average-running-times-by-card (map :id cards))(map (juxt :card_id :running_time))(into {})):id))@@ -327,13 +287,7 @@[_model k cards](mi/instances-with-hydrated-datacards k- #(->> (t2/query {:select [[:%max.started_at :started_at] :card_id]- :from [:query_execution]- :where [:and- [:not= :running_time nil]- [:not= :cache_hit true]- [:in :card_id (map :id cards)]]- :group-by [:card_id]})+ #(->> (queries.db/last-query-starts-by-card (map :id cards))(map (juxt :card_id :started_at))(into {})):id))@@ -343,11 +297,7 @@(mi/instances-with-hydrated-datacards k#(group-by :source_card_id- (->> (t2/select :model/Card- :source_card_id [:in (map :id cards)],- :archived false,- :type :metric,- {:order-by [[:name :asc]]})+ (->> (queries.db/metric-cards-for-source-cards (map :id cards))(filter mi/can-read?))):id))@@ -439,18 +389,10 @@;; for updates if `query` isn't being updated we don't need to validate anything.(when query(when-let [field-ids (not-empty (params/card->template-tag-field-ids card))]- (doseq [{:keys [field-id field-name table-name field-db-id]} (app-db/query- {:select [[:field.id :field-id]- [:field.name :field-name]- [:table.name :table-name]- [:table.db_id :field-db-id]]- :from [[:metabase_field :field]]- :left-join [[:metabase_table :table]- [:= :field.table_id :table.id]]- :where [:in :field.id (set field-ids)]})]+ (doseq [{:keys [field-id field-name table-name field-db-id]} (queries.db/field-database-info-for-ids (set field-ids))](when-not (= field-db-id query-db-id)(throw (ex-info (letfn [(describe-database [db-id]- (format "%d %s" db-id (pr-str (t2/select-one-fn :name 'Database :id db-id))))]+ (format "%d %s" db-id (pr-str (queries.db/database-name db-id))))](tru "Invalid Field Filter: Field {0} belongs to Database {1}, but the query is against Database {2}"(format "%d %s.%s" field-id (pr-str table-name) (pr-str field-name))(describe-database field-db-id)@@ -527,7 +469,7 @@changes)(defn- check-dashboard-internal-card-insert [card]- (let [correct-collection-id (t2/select-one-fn :collection_id [:model/Dashboard :collection_id] (:dashboard_id card))+ (let [correct-collection-id (queries.db/dashboard-collection-id (:dashboard_id card))invalid? (or (and (contains? card :collection_id)(not= correct-collection-id (:collection_id card)))(not (contains? #{:question "question" nil} (:type card)))@@ -586,15 +528,16 @@- card.result_metadata changes and the parameter values source field can't be found anymore"[{:keys [id database_id]} changes](when (some #{:archived :result_metadata} (keys changes))- (let [parameter-cards (t2/select :model/ParameterCard :card_id id)+ (let [parameter-cards (queries.db/parameter-cards-for-card id)metadata-columns (when-let [result-metadata (:result_metadata changes)](lib/->card-metadata-columns(lib-be/application-database-metadata-provider database_id)result-metadata))](doseq [[[po-type po-id] param-cards](group-by (juxt :parameterized_object_type :parameterized_object_id) parameter-cards)]- (let [model (case po-type :card 'Card :dashboard 'Dashboard)- {:keys [parameters]} (t2/select-one [model :parameters] :id po-id)+ (let [parameters (case po-type+ :card (queries.db/card-parameters po-id)+ :dashboard (queries.db/dashboard-parameters po-id))affected-param-ids-set (cond;; update all parameters that use this card as source(:archived changes)@@ -623,7 +566,9 @@parameter))parameters)](when-not (= parameters new-parameters)- (t2/update! model po-id {:parameters new-parameters})))))))+ (case po-type+ :card (queries.db/update-card! po-id {:parameters new-parameters})+ :dashboard (queries.db/update-dashboard! po-id {:parameters new-parameters}))))))))(mu/defn model-supports-implicit-actions?"A model with implicit action supported iff they are a raw table,@@ -640,12 +585,8 @@(defn- disable-implicit-action-for-model!"Delete all implicit actions of a model if exists."[model-id]- (when-let [action-ids (t2/select-pks-set :model/Action {:select [:action.id]- :from [:action]- :join [:implicit_action- [:= :action.id :implicit_action.action_id]]- :where [:= :action.model_id model-id]})]- (t2/delete! :model/Action :id [:in action-ids])))+ (when-let [action-ids (queries.db/implicit-action-ids-for-model model-id)]+ (queries.db/delete-actions! action-ids)));;; TODO (Cam 7/21/25) -- icky to have some of the before-update stuff live in the before-update method below and then;;; some but not all of it live in this `pre-update` function... all of the before-update stuff should live in a single@@ -660,8 +601,7 @@old-card-info (when (or (contains? changes :type)(:dataset_query changes)(get-in changes [:dataset_query :native]))- (t2/select-one [:model/Card :dataset_query :type :result_metadata :card_schema]- :id (u/the-id id)))]+ (queries.db/card-query-info (u/the-id id)))];; if the template tag params for this Card have changed in any way we need to update the FieldValues for;; On-Demand DB Fields(when (some-> changes :dataset_query lib/native-only-query?)@@ -683,8 +623,8 @@;; Changing from a Model to a Question: archive associated actions(when (and (= (:type changes) :question)(= (:type old-card-info) :model))- (t2/update! :model/Action {:model_id id :type [:not= :implicit]} {:archived true})- (t2/delete! :model/Action :model_id id, :type :implicit))+ (queries.db/archive-explicit-actions-for-model! id)+ (queries.db/delete-implicit-actions-for-model! id));; Make sure any native query template tags match the DB in the query.(check-field-filter-fields-are-from-correct-database changes);; Make sure the Collection is in the default Collection namespace (e.g. as opposed to the Snippets Collection@@ -886,7 +826,7 @@(defn- apply-dashboard-question-updates [card changes](if-let [dashboard-id (:dashboard_id changes)]- (assoc card :collection_id (t2/select-one-fn :collection_id :model/Dashboard :id dashboard-id))+ (assoc card :collection_id (queries.db/dashboard-collection-id dashboard-id))card))(mu/defn- populate-result-metadata :- [:map@@ -943,18 +883,14 @@;; delete any ParameterCard that the parameters on this card linked to(parameter-card/delete-all-for-parameterized-object! "card" id);; delete any ParameterCard linked to this card- (t2/delete! :model/ParameterCard :card_id id)- (t2/delete! :model/ModerationReview :moderated_item_type "card", :moderated_item_id id)- (t2/delete! :model/Revision :model "Card", :model_id id)+ (queries.db/delete-parameter-cards-for-card! id)+ (queries.db/delete-card-moderation-reviews! id)+ (queries.db/delete-card-revisions! id);; delete any card-type notifications for this card — must materialize IDs first because;; Notification's before-delete deletes the NotificationCard, which would make a subquery;; return empty by the time the actual DELETE executes.- (when-let [notification-ids (seq (t2/select-pks-set :model/Notification- :payload_type :notification/card- :payload_id [:in ^:allow-subquery {:select [:id]- :from [:notification_card]- :where [:= :card_id id]}]))]- (t2/delete! :model/Notification :id [:in notification-ids])))+ (when-let [notification-ids (seq (queries.db/card-notification-ids id))]+ (queries.db/delete-notifications! notification-ids)))(defmethod mi/exclude-internal-content-hsql :model/Card[_model & {:keys [table-alias]}]@@ -963,7 +899,7 @@;;; ----------------------------------------------- Creating Cards ----------------------------------------------------(defn- autoplace-dashcard-for-card! [dashboard-id maybe-dashboard-tab-id card size]- (let [dashboard (t2/hydrate (t2/select-one :model/Dashboard dashboard-id) :dashcards [:tabs :tab-cards])+ (let [dashboard (t2/hydrate (queries.db/dashboard dashboard-id) :dashcards [:tabs :tab-cards]){:keys [dashcards tabs]} dashboardtabs (remove #(when maybe-dashboard-tab-id (not= maybe-dashboard-tab-id (:id %))) tabs)already-on-dashboard? (seq (filter #(= (:id card) (:card_id %)) dashcards))]@@ -977,10 +913,10 @@cards-on-first-tab size_x size_y autoplace/default-grid-width)(autoplace/get-position-for-new-dashcardcards-on-first-tab (:display card)))]- (t2/insert! :model/DashboardCard (assoc new-spot- :dashboard_tab_id (some-> first-tab :id)- :card_id (:id card)- :dashboard_id dashboard-id))+ (queries.db/insert-dashcard! (assoc new-spot+ :dashboard_tab_id (some-> first-tab :id)+ :card_id (:id card)+ :dashboard_id dashboard-id));; the handler for `:event/dashboard-update` will hydrate `:dashcards` iff it's missing - make sure it is, so;; we don't store a revision for the *unmodified* dashcards.(events/publish-event! :event/dashboard-update@@ -989,16 +925,10 @@(defn- autoremove-dashcard-for-card![card-id dashboard-id]- (t2/delete! :model/DashboardCard :card_id card-id :dashboard_id dashboard-id)- (when-let [dashcard-ids (seq (map :id (t2/query {:select [[:dcs.id]]- :from [[:dashboardcard_series :dcs]]- :join [[:report_dashboardcard :dc]- [:= :dc.id :dcs.dashboardcard_id]]- :where [:and- [:= :dc.dashboard_id dashboard-id]- [:= :dcs.card_id card-id]]})))]- (t2/delete! :model/DashboardCardSeries :id [:in (set dashcard-ids)]))- (events/publish-event! :event/dashboard-update {:object (t2/select-one :model/Dashboard dashboard-id)+ (queries.db/delete-dashcards-for-card-on-dashboard! card-id dashboard-id)+ (when-let [dashcard-ids (seq (map :id (queries.db/dashcard-series-for-card-on-dashboard card-id dashboard-id)))]+ (queries.db/delete-dashcard-series! (set dashcard-ids)))+ (events/publish-event! :event/dashboard-update {:object (queries.db/dashboard dashboard-id):user-id api/*current-user-id*}))(defn- autoplace-or-remove-dashcards-for-card!@@ -1052,14 +982,9 @@delete-old-dashcards?);; TODO: should we publish events here? might be expensive, and it might not be right to show "card X was;; removed from the dashboard" since you can't restore to the previous state...- (t2/delete! :model/DashboardCard :card_id card-id :dashboard_id [:not= new-dashboard-id])- (when-let [ids (seq (map :id (t2/query {:select [[:dcs.id]]- :from [[:dashboardcard_series :dcs]]- :join [[:report_dashboardcard :dc] [:= :dc.id :dcs.dashboardcard_id]]- :where [:and- [:= :dcs.card_id card-id]- [:not= :dc.dashboard_id new-dashboard-id]]})))]- (t2/delete! :model/DashboardCardSeries :id [:in ids])))))+ (queries.db/delete-dashcards-for-card-off-dashboard! card-id new-dashboard-id)+ (when-let [ids (seq (map :id (queries.db/dashcard-series-for-card-off-dashboard card-id new-dashboard-id)))]+ (queries.db/delete-dashcard-series! ids)))))(defn create-card!"Create a new Card. Metadata will be fetched off thread. If the metadata takes longer than [[metadata-sync-wait-ms]]@@ -1103,9 +1028,9 @@;; Adding a new card at `collection_position` could cause other cards in;; this collection to change position, check that and fix it if needed(api/maybe-reconcile-collection-position! position-info)- (u/prog1 (t2/insert-returning-instance! :model/Card (cond-> card-data- metadata- (assoc :result_metadata metadata)))+ (u/prog1 (queries.db/insert-card! (cond-> card-data+ metadata+ (assoc :result_metadata metadata)))(when (collections/remote-synced-collection? (:collection_id <>))(collections/check-non-remote-synced-dependencies <>))))](let [{:keys [dashboard_id]} card]@@ -1274,21 +1199,21 @@breakouts-before (card->breakouts card-before)breakouts-after (card->breakouts card-after)](when-some [identifier->action (breakouts->identifier->action breakouts-before breakouts-after)]- (let [dashcards (t2/select :model/DashboardCard :card_id (some :id [card-after card-before]))+ (let [dashcards (queries.db/dashcards-for-card (some :id [card-after card-before]))updates (updates-for-dashcards identifier->action dashcards)];; Beware. This can have negative impact on card update performance as queries are fired in sequence. I'm not;; aware of more reasonable way.(when (seq updates)(t2/with-transaction [_conn](doseq [[id update] updates]- (t2/update! :model/DashboardCard :id id update))))))))+ (queries.db/update-dashcard! id update))))))))(deftype SourceCardDependentsGraph []graph/Graph(children-of [_this key-seq](if (empty? key-seq){}- (let [deps (t2/select [:model/Card :id :source_card_id :card_schema] :source_card_id [:in key-seq])]+ (let [deps (queries.db/source-card-dependents key-seq)](u/group-by :source_card_id :id conj #{} deps)))))(defn- dependent-cards-to-update@@ -1297,7 +1222,7 @@(when (seq all-dep-ids)(into [](filter (fn [{:keys [dataset_query]}] (= (:database dataset_query) old-db-id)))- (t2/select [:model/Card :id :dataset_query :card_schema] :id [:in all-dep-ids])))))+ (queries.db/card-queries all-dep-ids)))))(defn- cascade-database-change-to-dependents!"When a card's `database_id` changes, update all cards that use it as a `:source-card` (transitively) so their@@ -1310,7 +1235,7 @@(when (and old-db-id new-db-id (not= old-db-id new-db-id))(let [cards-to-update (dependent-cards-to-update card-id old-db-id)](doseq [{dep-id :id, dep-query :dataset_query} cards-to-update]- (t2/update! :model/Card dep-id {:dataset_query (assoc dep-query :database new-db-id)}))))))+ (queries.db/update-card! dep-id {:dataset_query (assoc dep-query :database new-db-id)}))))))(defn update-card!"Update a Card. Metadata is fetched asynchronously. If it is ready before [[metadata-sync-wait-ms]] elapses it will be@@ -1333,7 +1258,7 @@(cache/invalidate-config! {:questions [(:id card-before-update)]:with-overrides? true});; ok, now save the Card- (t2/update! :model/Card (:id card-before-update) updated-fields))+ (queries.db/update-card! (:id card-before-update) updated-fields));; Update all transitively dependent cards if the database was changed (#74561)(cascade-database-change-to-dependents! card-before-update card-updates);; ok, now update dependent dashcard parameters@@ -1343,7 +1268,7 @@(log/errorf "Update of dependent card parameters failed!: %s" (ex-message e))))(collection/check-for-remote-sync-update card-before-update));; Fetch the updated Card from the DB- (let [card (t2/select-one :model/Card :id (:id card-before-update))]+ (let [card (queries.db/card (:id card-before-update))];;; TODO -- this should be triggered indirectly by `:event/card-update`(pulse/delete-alerts-if-needed! :old-card card-before-update, :new-card card, :actor actor);; skip publishing the event if it's just a change in its collection position@@ -1534,7 +1459,7 @@(card-deps false card))(defmethod serdes/descendants "Card" [_model-name id _opts]- (let [card (t2/select-one :model/Card :id id)+ (let [card (queries.db/card id)query (not-empty (:dataset_query card))source-cards (some-> query lib/all-source-card-ids)template-tags (some-> query lib/all-template-tags)diff --git a/src/metabase/queries/models/card/metadata.clj b/src/metabase/queries/models/card/metadata.cljindex 27089be9600..69b2973a907 100644--- a/src/metabase/queries/models/card/metadata.clj+++ b/src/metabase/queries/models/card/metadata.clj@@ -9,6 +9,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.models.interface :as mi]+ [metabase.queries.db :as queries.db][metabase.query-processor.metadata :as qp.metadata][metabase.query-processor.preprocess :as qp.preprocess][metabase.query-processor.schema :as qp.schema]@@ -17,8 +18,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(mr/def ::future[:fn {:error/message "A future"} future?])@@ -161,10 +161,10 @@ saved later when it is ready."(log/infof "Not updating metadata asynchronously for card %s because no metadata" (u/the-id card)):else- (let [current-query (t2/select-one-fn :dataset_query [:model/Card :dataset_query :card_schema] :id id)]+ (let [current-query (queries.db/card-dataset-query id)](if (= (:dataset_query card) current-query)(do- (t2/update! :model/Card id {:result_metadata metadata})+ (queries.db/update-card! id {:result_metadata metadata})(log/infof "Metadata updated asynchronously for card %s" id))(log/infof "Not updating metadata asynchronously for card %s because query has changed" id)))))(catch Throwable ediff --git a/src/metabase/queries/models/parameter_card.clj b/src/metabase/queries/models/parameter_card.cljindex ff054ee2e3f..c96806113d2 100644--- a/src/metabase/queries/models/parameter_card.clj+++ b/src/metabase/queries/models/parameter_card.clj@@ -1,9 +1,9 @@(ns metabase.queries.models.parameter-card(:require- [medley.core :as m][metabase.api.common :as api][metabase.models.interface :as mi][metabase.parameters.schema :as parameters.schema]+ [metabase.queries.db :as queries.db][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]@@ -52,11 +52,11 @@(delete-all-for-parameterized-object! parameterized-object-type parameterized-object-id []))([parameterized-object-type parameterized-object-id parameter-ids-still-in-use]- (let [conditions (concat [:parameterized_object_type parameterized-object-type- :parameterized_object_id parameterized-object-id]- (when (seq parameter-ids-still-in-use)- [:parameter_id [:not-in parameter-ids-still-in-use]]))]- (apply t2/delete! :model/ParameterCard conditions))))+ (if (seq parameter-ids-still-in-use)+ (queries.db/delete-parameter-cards-for-object-except! parameterized-object-type+ parameterized-object-id+ parameter-ids-still-in-use)+ (queries.db/delete-parameter-cards-for-object! parameterized-object-type parameterized-object-id))))(defn- upsert-from-parameters![parameterized-object-type parameterized-object-id parameters]@@ -67,9 +67,9 @@:parameter_id id}];; TODO: Maybe update! should return different values for no rows to update vs;; no changes to be made- (if (m/mapply t2/exists? :model/ParameterCard conditions)- (t2/update! :model/ParameterCard conditions {:card_id card-id})- (t2/insert! :model/ParameterCard (merge conditions {:card_id card-id}))))))+ (if (queries.db/parameter-card-exists? parameterized-object-type parameterized-object-id id)+ (queries.db/set-parameter-card-card-id! parameterized-object-type parameterized-object-id id card-id)+ (queries.db/insert-parameter-card! (merge conditions {:card_id card-id}))))))(defn values-source-card-ids"Returns the ids of the Cards `parameters` draw their values from."@@ -93,9 +93,7 @@parameters :- [:maybe [:sequential ::parameters.schema/parameter]]](when-not mi/*deserializing?*(when-let [wanted (not-empty (values-source-card-ids parameters))]- (let [existing (t2/select-fn-set :card_id :model/ParameterCard- :parameterized_object_type parameterized-object-type- :parameterized_object_id parameterized-object-id)]+ (let [existing (queries.db/parameter-card-card-ids parameterized-object-type parameterized-object-id)](doseq [card-id wanted:when (not (contains? existing card-id))](api/read-check :model/Card card-id))))))diff --git a/src/metabase/queries/models/query.clj b/src/metabase/queries/models/query.cljindex fedcd7231a8..989d02674e9 100644--- a/src/metabase/queries/models/query.clj+++ b/src/metabase/queries/models/query.clj@@ -1,14 +1,13 @@(ns metabase.queries.models.query"Functions related to the 'Query' model, which records stuff such as average query execution time."(:require- [metabase.app-db.core :as mdb][metabase.lib-be.schema :as lib-be.schema][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.schema :as lib.schema][metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi]- [metabase.util.honey-sql-2 :as h2x]+ [metabase.queries.db :as queries.db][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]@@ -36,16 +35,7 @@Returns `nil` if no information is available."^Integer [^bytes query-hash]{:pre [(instance? (Class/forName "[B") query-hash)]}- (t2/select-one-fn :average_execution_time :model/Query :query_hash query-hash))--(defn- int-casting-type- "Return appropriate type for use in SQL `CAST(x AS type)` statement.- MySQL doesn't accept `integer`, so we have to use `unsigned`; Postgres doesn't accept `unsigned`.- so we have to use `integer`. Yay SQL dialect differences :D"- []- (if (= (mdb/db-type) :mysql)- :unsigned- :integer))+ (queries.db/average-execution-time query-hash))(def ^:private smoothing-factor"The weight of the latest execution time in the exponential rolling average formula:@@ -61,21 +51,14 @@"Update the rolling average execution time for query with `query-hash`. Returns `true` if a record was updated,or `false` if no matching records were found."^Boolean [query ^bytes query-hash ^Integer execution-time-ms]- (let [avg-execution-time (h2x/cast (int-casting-type) (h2x/round (h2x/+ (h2x/* [:inline decay-factor] :average_execution_time)- [:inline (* smoothing-factor execution-time-ms)])- [:inline 0]))]+ (let [c1 (* smoothing-factor execution-time-ms)](or;; if it DOES NOT have a query (yet) set that. In 0.31.0 we added the query.query column, and it gets set for all;; new entries, so at some point in the future we can take this out, and save a DB call.- (pos? (t2/update! :model/Query- {:query_hash query-hash, :query nil}- {:query (json/encode query)- :average_execution_time avg-execution-time}))+ (pos? (queries.db/backfill-query-and-average-execution-time! query-hash (json/encode query) decay-factor c1));; if query is already set then just update average_execution_time. (We're doing this separate call to avoid;; updating query on every single UPDATE)- (pos? (t2/update! :model/Query- {:query_hash query-hash}- {:average_execution_time avg-execution-time})))))+ (pos? (queries.db/update-average-execution-time! query-hash decay-factor c1)))))(defn- rolling-average-coefficients"Collapse applying the rolling-average formula (see [[smoothing-factor]]) once per execution time into a single@@ -102,39 +85,24 @@(when hash-bytes(ByteBuffer/wrap ^bytes hash-bytes)))-(defn- rolling-average-update-expr- "HoneySQL expression that updates `:average_execution_time` as if the rolling-average formula were applied once per- execution time, in order."- [execution-times-ms]- (let [[c0 c1] (rolling-average-coefficients execution-times-ms)]- (h2x/cast (int-casting-type)- (h2x/round (h2x/+ (h2x/* [:inline c0] :average_execution_time)- [:inline c1])- [:inline 0]))))-(defn- update-rolling-average-execution-times!"Update the rolling average execution times for `groups` (each a sequence of entries sharing a query hash) with asingle atomic UPDATE."[groups](when (seq groups)- (let [hash+exprs (vec (for [group groups]- [(:query-hash (first group))- (rolling-average-update-expr (map :execution-time-ms group))]))]- (t2/query {:update (t2/table-name :model/Query)- :set {:average_execution_time (into [:case]- (mapcat (fn [[query-hash expr]]- [[:= :query_hash query-hash] expr]))- hash+exprs)}- :where [:in :query_hash (mapv first hash+exprs)]}))))+ (let [hash+coefficients (vec (for [group groups]+ (let [[c0 c1] (rolling-average-coefficients (map :execution-time-ms group))]+ [(:query-hash (first group)) c0 c1])))]+ (queries.db/update-average-execution-times! hash+coefficients))))(defn- insert-query-entries!"Insert new Query rows for `groups` (each a sequence of entries sharing a query hash) with a single INSERT."[groups]- (t2/insert! :model/Query (for [group groups]- {:query (:query (first group))- :query_hash (:query-hash (first group))- :average_execution_time (initial-average-execution-time- (map :execution-time-ms group))})))+ (queries.db/insert-queries! (for [group groups]+ {:query (:query (first group))+ :query_hash (:query-hash (first group))+ :average_execution_time (initial-average-execution-time+ (map :execution-time-ms group))})))(defn- query-hash->row-status"Fetch which of `query-hashes` already have Query rows. Returns a map of [[hash-key]] -> `:up-to-date` or@@ -150,9 +118,7 @@(if (contains? #{true 1} missing_query):needs-query-backfill:up-to-date)]))- (t2/reducible-query {:select [:query_hash [[:= :query nil] :missing_query]]- :from [(t2/table-name :model/Query)]- :where [:in :query_hash query-hashes]}))))+ (queries.db/query-hash-statuses-reducible query-hashes))))(defn save-queries-and-update-average-execution-times!"Update the recorded average execution times (or insert new records as needed) for `entries`, maps with `:query`,@@ -199,7 +165,7 @@(if-let [source-card-id (lib/primary-source-card-id query)](let [card (or (lib.metadata/card query source-card-id);; Card may belong to a different Database; fetch from the app DB- (t2/select-one [:model/Card [:database_id :database-id] [:table_id :table-id]] :id source-card-id))]+ (queries.db/card-database-and-table-ids source-card-id))](merge {:table-id nil, :database-id (:database query)} (select-keys card [:database-id :table-id])))(let [table-id (lib/primary-source-table-id query)]{:database-id database-iddiff --git a/src/metabase/queries/models/stored_result_use.clj b/src/metabase/queries/models/stored_result_use.cljindex 1da9d32baec..604266fd2c9 100644--- a/src/metabase/queries/models/stored_result_use.clj+++ b/src/metabase/queries/models/stored_result_use.clj@@ -7,6 +7,7 @@every snapshot a Card renders from. Lives in the queries module alongside `:model/StoredResult`."(:require[metabase.queries.cached-result :as cached-result]+ [metabase.queries.db :as queries.db][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]@@ -39,27 +40,19 @@(when (seq pairs)(let [distinct-pairs (distinct pairs)sr-ids (into #{} (map second) distinct-pairs)- doc-card-ids (t2/select-pks-set :model/Card :document_id document-id)+ doc-card-ids (queries.db/document-card-ids document-id)reachable (if (seq doc-card-ids)- (t2/select-fn-set :stored_result_id- :model/StoredResultUse- :card_id [:in doc-card-ids]- :stored_result_id [:in sr-ids])+ (queries.db/stored-result-ids-used-by-cards doc-card-ids sr-ids)#{})](doseq [[new-card-id sr-id] distinct-pairs:when (contains? reachable sr-id)]- (t2/insert! :model/StoredResultUse- {:stored_result_id sr-id- :card_id new-card-id})))))+ (queries.db/insert-stored-result-use! sr-id new-card-id)))))(mu/defn assert-can-view-card-snapshots!"Throw a 403 unless the current user may be served *every* `stored_result` Card `card-id` rendersfrom."[card-id :- ms/PositiveInt]- (let [snapshots (t2/select :model/StoredResult- :id [:in ^:allow-subquery {:select [:stored_result_id]- :from [:stored_result_use]- :where [:= :card_id card-id]}])]+ (let [snapshots (queries.db/stored-results-for-card card-id)](when (empty? snapshots)(throw (ex-info (tru "This card has no cached results.") {:status-code 404})))(doseq [snapshot snapshots]diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.cljindex 96825bc339f..95c7a5a119f 100644--- a/src/metabase/queries_rest/api/card.clj+++ b/src/metabase/queries_rest/api/card.clj@@ -20,6 +20,7 @@[metabase.parameters.schema :as parameters.schema][metabase.permissions.core :as perms][metabase.public-sharing.validation :as public-sharing.validation]+ [metabase.queries-rest.db :as queries-rest.db][metabase.queries.core :as queries][metabase.queries.schema :as queries.schema][metabase.query-permissions.core :as query-perms]@@ -46,8 +47,6 @@;;; ----------------------------------------------- Filtered Fetch Fns ------------------------------------------------(def ^:private order-by-name {:order-by [[:%lower.name :asc]]})-(defmulti ^:private cards-for-filter-option*{:arglists '([filter-option & args])}(fn [filter-option & _]@@ -56,17 +55,17 @@;; return all Cards. This is the default filter option.(defmethod cards-for-filter-option* :all[_]- (t2/select :model/Card, :archived false, order-by-name))+ (queries-rest.db/unarchived-cards));; return Cards created by the current user(defmethod cards-for-filter-option* :mine[_]- (t2/select :model/Card, :creator_id api/*current-user-id*, :archived false, order-by-name))+ (queries-rest.db/unarchived-cards-by-creator api/*current-user-id*));; return all Cards bookmarked by the current user.(defmethod cards-for-filter-option* :bookmarked[_]- (let [bookmarks (t2/select [:model/CardBookmark :card_id] :user_id api/*current-user-id*)]+ (let [bookmarks (queries-rest.db/card-bookmarks-for-user api/*current-user-id*)](->> (t2/hydrate bookmarks :card)(map :card)(remove :archived)@@ -75,30 +74,22 @@;; Return all Cards belonging to Database with `database-id`.(defmethod cards-for-filter-option* :database[_ database-id]- (t2/select :model/Card, :database_id database-id, :archived false, order-by-name))+ (queries-rest.db/unarchived-cards-for-database database-id));; Return all Cards belonging to `Table` with `table-id`.(defmethod cards-for-filter-option* :table[_ table-id]- (t2/select :model/Card, :table_id table-id, :archived false, order-by-name))+ (queries-rest.db/unarchived-cards-for-table table-id));; Cards that have been archived.(defmethod cards-for-filter-option* :archived[_]- (t2/select :model/Card, :archived true, order-by-name))+ (queries-rest.db/archived-cards));; Cards that are using a given model.(defmethod cards-for-filter-option* :using_model[_filter-option model-id]- (->> (t2/select :model/Card {:select [:c.*]- :from [[:report_card :m]]- :join [[:report_card :c] [:and- [:= :c.database_id :m.database_id]- [:or- [:like :c.dataset_query (format "%%card__%s%%" model-id)]- [:like :c.dataset_query (format "%%#%s%%" model-id)]]]]- :where [:and [:= :m.id model-id] [:not :c.archived]]- :order-by [[[:lower :c.name] :asc]]})+ (->> (queries-rest.db/cards-using-model model-id);; now check if model-id really occurs as a card ID(filter (fn [card](some-> card :dataset_query not-empty lib/all-source-card-ids (contains? model-id))))))@@ -106,8 +97,7 @@(mu/defn- cards-for-segment-or-metric[model-type :- [:enum :segment :metric]model-id :- pos-int?]- (->> (t2/select :model/Card (merge order-by-name- {:where [:like :dataset_query (str "%" (name model-type) "%" model-id "%")]}))+ (->> (queries-rest.db/cards-with-query-like (str "%" (name model-type) "%" model-id "%"));; now check if the segment/metric with model-id really occurs in a filter/aggregation expression(filter (fn [{query :dataset_query, :as _card}](when (seq query)@@ -134,7 +124,7 @@[](perms/check-has-application-permission :setting)(public-sharing.validation/check-public-sharing-enabled)- (t2/select [:model/Card :name :id :public_uuid :card_schema], :public_uuid [:not= nil], :archived false))+ (queries-rest.db/public-cards));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -146,20 +136,13 @@[](perms/check-has-application-permission :setting)(embedding.validation/check-embedding-enabled)- (t2/select [:model/Card :name :id :card_schema], :enable_embedding true, :archived false))+ (queries-rest.db/embeddable-cards));;; -------------------------------------------- Fetching a Card or Cards --------------------------------------------(def ^:private card-filter-options"a valid card filter option."(keys (methods cards-for-filter-option*)))-(defn- db-id-via-table- [model model-id]- (t2/select-one-fn :db_id :model/Table {:select [:t.db_id]- :from [[:metabase_table :t]]- :join [[model :m] [:= :t.id :m.table_id]]- :where [:= :m.id model-id]}))-;; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST API;;@@ -182,9 +165,9 @@(name f)))(case f:database (api/read-check :model/Database model-id)- :table (api/read-check :model/Database (t2/select-one-fn :db_id :model/Table, :id model-id))+ :table (api/read-check :model/Database (queries-rest.db/table-database-id model-id)):using_model (api/read-check :model/Card model-id)- :using_segment (api/read-check :model/Database (db-id-via-table :segment model-id))))+ :using_segment (api/read-check :model/Database (queries-rest.db/segment-database-id model-id))))(let [cards (filter mi/can-read? (cards-for-filter-option f model-id))last-edit-info (:card (revisions/fetch-last-edited-info {:card-ids (map :id cards)}))](into []@@ -203,21 +186,7 @@{:name "hydrate-card-details":attributes {:queries/id card-id}}(-> card- (t2/hydrate :based_on_upload- :creator- :can_write- :dashboard_count- [:dashboard :moderation_status]- :average_query_time- :last_query_start- :parameter_usage_count- :can_restore- :can_delete- :can_manage_db- [:collection :is_personal]- [:moderation_reviews :moderator_details]- :param_fields- :is_remote_synced)+ (t2/hydrate :based_on_upload :creator :can_write :dashboard_count [:dashboard :moderation_status] :average_query_time :last_query_start :parameter_usage_count :can_restore :can_delete :can_manage_db [:collection :is_personal] [:moderation_reviews :moderator_details] :param_fields :is_remote_synced)(update :creator select-keys [:id :first_name :last_name :email :common_name])(update :param_fields (fn [param-fields](perms/prime-table-perms-cache@@ -232,15 +201,14 @@(filterv #(viewable? (:table_id %)) fields))))))(update :dashboard #(some-> % (select-keys [:name :id :moderation_status])))(cond->- (queries/model? card) (t2/hydrate :persisted- ;; can_manage_db determines whether we should enable model persistence settings- :can_manage_db)))))+ ;; can_manage_db determines whether we should enable model persistence settings+ (queries/model? card) (t2/hydrate :persisted :can_manage_db)))))(defn- get-card"Get `Card` with ID."[id](let [with-last-edit-info #(first (revisions/with-last-edit-info [%] :card))- raw-card (t2/select-one :model/Card :id id)]+ raw-card (queries-rest.db/card id)](-> raw-cardapi/read-checkhydrate-card-details@@ -387,26 +355,16 @@[:last-cursor {:optional true} [:maybe ms/PositiveInt]][:page-size {:optional true} [:maybe ms/PositiveInt]][:exclude-ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]]]- (let [matching-cards (t2/select :model/Card- :archived false- :display [:in supported-series-display-type]- :id [:not= (:id card)]- (cond-> {:order-by [[:id :desc]]- :where [:and]}- last-cursor- (update :where conj [:< :id last-cursor])-- (seq exclude-ids)- (update :where conj [:not [:in :id exclude-ids]])-- query- (update :where conj [:like :%lower.name (h2x/like-substring query)])-- ;; add a little buffer to the page to account for cards that are not- ;; compatible + do not have permissions to read- ;; this is just a heuristic, but it should be good enough- page-size- (assoc :limit (+ 10 page-size))))+ (let [matching-cards (queries-rest.db/compatible-series-cards+ (:id card)+ supported-series-display-type+ last-cursor+ exclude-ids+ (when query (h2x/like-substring query))+ ;; add a little buffer to the page to account for cards that are not+ ;; compatible + do not have permissions to read+ ;; this is just a heuristic, but it should be good enough+ (when page-size (+ 10 page-size)))compatible-cards (->> matching-cards(filter mi/can-read?)(filter #(or@@ -469,7 +427,7 @@(fn [ids](every? pos-int? (api/parse-multi-values-param ids parse-long)))]]]]](let [exclude_ids (when exclude_ids (api/parse-multi-values-param exclude_ids parse-long))- card (-> (t2/select-one :model/Card :id id) api/check-404 api/read-check)+ card (-> (queries-rest.db/card id) api/check-404 api/read-check)card-display (:display card)](when-not (supported-series-display-type card-display)(throw (ex-info (tru "Card with type {0} is not compatible to have series" (name card-display))@@ -504,7 +462,7 @@(let [[_ collection-id :as specified-collection-id?] (find body :collection_id);; unlike collection_id, `dashboard_id=null` isn't different than not specifying it at all.dashboard-id (:dashboard_id body)- dashboard-id->collection-id #(t2/select-one-fn :collection_id [:model/Dashboard :collection_id] %)]+ dashboard-id->collection-id queries-rest.db/dashboard-collection-id](cond;; you specified both - they must match(and specified-collection-id? dashboard-id)@@ -684,14 +642,13 @@(let [query (:dataset_query card-updates)](check-if-card-can-be-saved query card-type)(check-parameter-permissions (:parameters card-updates)- (or query (t2/select-one-fn :dataset_query :model/Card :id id)))+ (or query (queries-rest.db/card-query id)))(when-some [query (:dataset_query card-updates)](try(lib/check-card-overwrite id query)(catch clojure.lang.ExceptionInfo e(throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 400))))))- (let [card-before-update (t2/hydrate (api/write-check :model/Card id)- [:moderation_reviews :moderator_details])+ (let [card-before-update (t2/hydrate (api/write-check :model/Card id) [:moderation_reviews :moderator_details])card-updates (maybe-populate-collection-idcard-before-update(api/updates-with-archived-directly card-before-update card-updates))@@ -794,7 +751,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](let [card (api/write-check :model/Card id)]- (t2/delete! :model/Card :id id)+ (queries-rest.db/delete-card! id)(events/publish-event! :event/card-delete {:object card :user-id api/*current-user-id*}))api/generic-204-no-content)@@ -808,8 +765,7 @@[new-collection-id-or-nil cards];; Sorting by `:collection_position` to ensure lower position cards are appended first(let [sorted-cards (sort-by :collection_position cards)- max-position-result (t2/select-one [:model/Card [:%max.collection_position :max_position]]- :collection_id new-collection-id-or-nil)+ max-position-result (queries-rest.db/max-collection-position new-collection-id-or-nil);; collection_position for the next card in the collectionstarting-position (inc (get max-position-result :max_position 0))];; This is using `map` but more like a `doseq` with multiple seqs. Wrapping this in a `doall` as we don't want it@@ -821,10 +777,9 @@(api/reconcile-position-for-collection! collection_id collection_position nil);; Now we can update the card with the new collection and a new calculated position;; that appended to the end- (t2/update! :model/Card- (u/the-id card)- {:collection_position idx- :collection_id new-collection-id-or-nil}))+ (queries-rest.db/update-card! (u/the-id card)+ {:collection_position idx+ :collection_id new-collection-id-or-nil}));; These are reversed because of the classic issue when removing an item from array. If we remove an;; item at index 1, everything above index 1 will get decremented. By reversing our processing order we;; can avoid changing the index of cards we haven't yet updated@@ -837,11 +792,7 @@(api/write-check :model/Collection new-collection-id-or-nil));; for each affected card...(when (seq card-ids)- (let [cards (t2/select [:model/Card :id :collection_id :collection_position :dataset_query :card_schema]- {:where [:and [:in :id (set card-ids)]- [:or [:not= :collection_id new-collection-id-or-nil]- (when new-collection-id-or-nil- [:= :collection_id nil])]]})] ; poisioned NULLs = ick+ (let [cards (queries-rest.db/cards-to-move-to-collection (set card-ids) new-collection-id-or-nil)] ; poisioned NULLs = ick;; ...check that we have write permissions for it...(doseq [card cards](api/write-check card))@@ -861,9 +812,7 @@(when-let [cards-without-position (seq (for [card cards:when (not (:collection_position card))](u/the-id card)))]- (t2/update! (t2/table-name :model/Card)- {:id [:in (set cards-without-position)]}- {:collection_id new-collection-id-or-nil}))+ (queries-rest.db/set-cards-collection-raw! (set cards-without-position) new-collection-id-or-nil))(doseq [card cards](collection/check-for-remote-sync-update card)))))@@ -913,7 +862,7 @@ids. 404s (rather than 403s) on an unpaired id so it doesn't confirm the snapshot exists."[card-id stored-result-id sort](api/check-exists? :model/StoredResultUse :card_id card-id :stored_result_id stored-result-id)- (let [sr (api/check-404 (t2/select-one :model/StoredResult :id stored-result-id))]+ (let [sr (api/check-404 (queries-rest.db/stored-result stored-result-id))](queries/assert-can-view-card-snapshots! card-id)(api/check-404 (queries/cached-dataset sr sort))))@@ -934,7 +883,7 @@[:sort {:optional true}[:maybe [:enum "value_asc" "value_desc" "label_asc" "label_desc"]]]]](let [resolved-card-id (eid-translation/->id-or-404 :card card-id)- card (api/check-404 (t2/select-one :model/Card resolved-card-id))]+ card (api/check-404 (queries-rest.db/card resolved-card-id))](if stored_result_id(do(api/read-check card)@@ -985,7 +934,7 @@[:pivot_results {:default false} ms/BooleanValue][:csv_include_bom {:default false} ms/BooleanValue]]](qp.card/process-query-for-card- (api/check-404 (t2/select-one :model/Card card-id)) export-format+ (api/check-404 (queries-rest.db/card card-id)) export-format:parameters parameters:constraints nil:context (api.dataset/export-format->context export-format)@@ -1015,15 +964,15 @@(api/check-superuser)(public-sharing.validation/check-public-sharing-enabled)(api/check-not-archived (api/read-check :model/Card card-id))- (let [{existing-public-uuid :public_uuid} (t2/select-one [:model/Card :public_uuid :card_schema] :id card-id)+ (let [{existing-public-uuid :public_uuid} (queries-rest.db/card-public-uuid-columns card-id)uuid (or existing-public-uuid(u/prog1 (str (random-uuid))(events/publish-event! :event/card-public-link-created{:object-id card-id:user-id api/*current-user-id*})- (t2/update! :model/Card card-id- {:public_uuid <>- :made_public_by_id api/*current-user-id*})))]+ (queries-rest.db/update-card! card-id+ {:public_uuid <>+ :made_public_by_id api/*current-user-id*})))]{:uuid uuid}));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API@@ -1040,9 +989,9 @@(perms/check-has-application-permission :setting)(public-sharing.validation/check-public-sharing-enabled)(api/check-exists? :model/Card :id card-id, :public_uuid [:not= nil])- (t2/update! :model/Card card-id- {:public_uuid nil- :made_public_by_id nil})+ (queries-rest.db/update-card! card-id+ {:public_uuid nil+ :made_public_by_id nil})(events/publish-event! :event/card-public-link-deleted{:object-id card-id:user-id api/*current-user-id*})@@ -1062,7 +1011,7 @@[:ignore_cache {:optional true} [:maybe :boolean]][:dashboard_id {:optional true} [:maybe ms/PositiveInt]][:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]]]- (let [card (api/check-404 (t2/select-one :model/Card card-id))]+ (let [card (api/check-404 (queries-rest.db/card card-id))](when dashboard_id(api/read-check :model/Dashboard dashboard_id))(qp.card/process-query-for-card card :apidiff --git a/src/metabase/queries_rest/api/cards.clj b/src/metabase/queries_rest/api/cards.cljindex da2ecac3ffc..6aae8b33151 100644--- a/src/metabase/queries_rest/api/cards.clj+++ b/src/metabase/queries_rest/api/cards.clj@@ -4,6 +4,7 @@[metabase.api.macros :as api.macros][metabase.models.interface :as mi][metabase.queries-rest.api.card :as api.card]+ [metabase.queries-rest.db :as queries-rest.db][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -27,7 +28,7 @@_query-params{:keys [card_ids]} :- [:map[:card_ids [:sequential ms/PositiveInt]]]]- (let [id->card (t2/select-fn->fn :id identity :model/Card :id [:in card_ids])]+ (let [id->card (queries-rest.db/cards-by-id card_ids)](as-> card_ids $(mapv id->card $)(t2/hydrate $ :in_dashboards)diff --git a/src/metabase/queries_rest/db.clj b/src/metabase/queries_rest/db.cljnew file mode 100644index 00000000000..d7ccfc1ae1b--- /dev/null+++ b/src/metabase/queries_rest/db.clj@@ -0,0 +1,162 @@+(ns metabase.queries-rest.db+ "Application database queries for the queries REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [toucan2.core :as t2]))++(def ^:private order-by-name {:order-by [[:%lower.name :asc]]})++(defn unarchived-cards+ "The unarchived Cards, in case-insensitive name order."+ []+ (t2/select :model/Card, :archived false, order-by-name))++(defn unarchived-cards-by-creator+ "The unarchived Cards created by the User with `creator-id`, in case-insensitive name order."+ [creator-id]+ (t2/select :model/Card, :creator_id creator-id, :archived false, order-by-name))++(defn unarchived-cards-for-database+ "The unarchived Cards of the Database with `database-id`, in case-insensitive name order."+ [database-id]+ (t2/select :model/Card, :database_id database-id, :archived false, order-by-name))++(defn unarchived-cards-for-table+ "The unarchived Cards of the Table with `table-id`, in case-insensitive name order."+ [table-id]+ (t2/select :model/Card, :table_id table-id, :archived false, order-by-name))++(defn archived-cards+ "The archived Cards, in case-insensitive name order."+ []+ (t2/select :model/Card, :archived true, order-by-name))++(defn cards-with-query-like+ "The Cards whose query matches the SQL LIKE `pattern`, in case-insensitive name order."+ [pattern]+ (t2/select :model/Card (merge order-by-name {:where [:like :dataset_query pattern]})))++(defn card-bookmarks-for-user+ "The Card ids bookmarked by the User with `user-id`."+ [user-id]+ (t2/select [:model/CardBookmark :card_id] :user_id user-id))++(defn cards-using-model+ "The unarchived Cards of the same Database as the model Card with `model-id` whose query mentions it, in+ case-insensitive name order."+ [model-id]+ (t2/select :model/Card {:select [:c.*]+ :from [[:report_card :m]]+ :join [[:report_card :c] [:and+ [:= :c.database_id :m.database_id]+ [:or+ [:like :c.dataset_query (format "%%card__%s%%" model-id)]+ [:like :c.dataset_query (format "%%#%s%%" model-id)]]]]+ :where [:and [:= :m.id model-id] [:not :c.archived]]+ :order-by [[[:lower :c.name] :asc]]}))++(defn public-cards+ "The name, id, public uuid, and schema of the unarchived Cards that are publicly shared."+ []+ (t2/select [:model/Card :name :id :public_uuid :card_schema], :public_uuid [:not= nil], :archived false))++(defn embeddable-cards+ "The name, id, and schema of the unarchived Cards with embedding enabled."+ []+ (t2/select [:model/Card :name :id :card_schema], :enable_embedding true, :archived false))++(defn segment-database-id+ "The Database id of the Table of the Segment with `segment-id`, or nil."+ [segment-id]+ (t2/select-one-fn :db_id :model/Table {:select [:t.db_id]+ :from [[:metabase_table :t]]+ :join [[:segment :m] [:= :t.id :m.table_id]]+ :where [:= :m.id segment-id]}))++(defn table-database-id+ "The Database id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id :model/Table, :id table-id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn cards-by-id+ "A map of Card id to Card for the Cards with `card-ids`."+ [card-ids]+ (t2/select-fn->fn :id identity :model/Card :id [:in card-ids]))++(defn card-query+ "The query of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :dataset_query :model/Card :id card-id))++(defn card-public-uuid-columns+ "The public uuid and schema of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :public_uuid :card_schema] :id card-id))++(defn compatible-series-cards+ "The unarchived Cards other than `excluded-card-id` displayed as one of `display-types`, newest first, whose id is+ less than `last-cursor` (when given), excluding `exclude-ids`, and whose lower-cased name matches the SQL LIKE+ `name-pattern` (when given). Up to `limit` results (when given)."+ [excluded-card-id display-types last-cursor exclude-ids name-pattern limit]+ (t2/select :model/Card+ :archived false+ :display [:in display-types]+ :id [:not= excluded-card-id]+ (cond-> {:order-by [[:id :desc]]}+ last-cursor+ (sql.helpers/where [:< :id last-cursor])++ (seq exclude-ids)+ (sql.helpers/where [:not [:in :id exclude-ids]])++ name-pattern+ (sql.helpers/where [:like :%lower.name name-pattern])++ limit+ (assoc :limit limit))))++(defn dashboard-collection-id+ "The Collection id of the Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one-fn :collection_id [:model/Dashboard :collection_id] dashboard-id))++(defn update-card!+ "Apply `changes` to the Card with `card-id`."+ [card-id changes]+ (t2/update! :model/Card card-id changes))++(defn delete-card!+ "Delete the Card with `card-id`."+ [card-id]+ (t2/delete! :model/Card :id card-id))++(defn max-collection-position+ "The `:max_position` of the Cards in the Collection with `collection-id` (nil for the root)."+ [collection-id]+ (t2/select-one [:model/Card [:%max.collection_position :max_position]] :collection_id collection-id))++(defn cards-to-move-to-collection+ "The id, Collection, position, query, and schema of the Cards among `card-ids` not already in+ `new-collection-id-or-nil`."+ [card-ids new-collection-id-or-nil]+ (t2/select [:model/Card :id :collection_id :collection_position :dataset_query :card_schema]+ {:where [:and [:in :id card-ids]+ [:or [:not= :collection_id new-collection-id-or-nil]+ (when new-collection-id-or-nil+ [:= :collection_id nil])]]}))++(defn set-cards-collection-raw!+ "Move the Cards with `card-ids` to the Collection with `collection-id` without running model hooks."+ [card-ids collection-id]+ (t2/update! (t2/table-name :model/Card) {:id [:in card-ids]} {:collection_id collection-id}))++(defn stored-result+ "The StoredResult with `id`, or nil."+ [id]+ (t2/select-one :model/StoredResult :id id))diff --git a/src/metabase/query_permissions/db.clj b/src/metabase/query_permissions/db.cljnew file mode 100644index 00000000000..775b8031f3a--- /dev/null+++ b/src/metabase/query_permissions/db.clj@@ -0,0 +1,25 @@+(ns metabase.query-permissions.db+ "Application database queries for the query permissions module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn card-collection-id+ "The `:collection_id` and `:card_schema` of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :collection_id :card_schema] :id card-id))++(defn card-not-in-database+ "The Card with `card-id` if it does not belong to the Database with `database-id`, or nil."+ [card-id database-id]+ (t2/select-one :model/Card :id card-id :database_id [:!= database-id]))++(defn field-table-ids+ "The set of Table ids of the Fields with `field-ids`."+ [field-ids]+ (t2/select-fn-set :table_id :model/Field :id [:in field-ids]))++(defn table-id->database-id+ "A map of Table id to Database id for the Tables with `table-ids`."+ [table-ids]+ (t2/select-pk->fn :db_id :model/Table :id [:in table-ids]))diff --git a/src/metabase/query_permissions/impl.clj b/src/metabase/query_permissions/impl.cljindex c5c9d513cf9..f4c784a48e6 100644--- a/src/metabase/query_permissions/impl.clj+++ b/src/metabase/query_permissions/impl.clj@@ -17,6 +17,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi][metabase.permissions.core :as perms]+ [metabase.query-permissions.db :as query-permissions.db][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.interface :as qp.i];; legacy usage -- don't do things like this going forward@@ -171,7 +172,7 @@(if (qp.store/initialized?)(when-let [{:keys [collection-id]} (lib.metadata/card (qp.store/metadata-provider) card-id)](t2/instance :model/Card {:collection_id collection-id}))- (t2/select-one [:model/Card :collection_id :card_schema] :id card-id))+ (query-permissions.db/card-collection-id card-id))(throw (Exception. (tru "Card {0} does not exist." card-id)))))(mu/defn- source-card-read-perms :- [:set perms/PathSchema]@@ -351,7 +352,7 @@;; used by the model upon which the action is defined. In this case, the underlying model whose;; permissions we need to check will not be exposed by the metadata provider, so we need a fallback.;; -- Noah- (t2/select-one :model/Card :id card-id :database_id [:!= database-id])+ (query-permissions.db/card-not-in-database card-id database-id)(throw (ex-info (tru "Card {0} does not exist." card-id){:type qp.error-type/invalid-query:card-id card-id}))))@@ -362,7 +363,7 @@(let [field-ids (keep :id result-metadata)table-ids (into (set (keep (some-fn :table-id :table_id) result-metadata))(when (seq field-ids)- (t2/select-fn-set :table_id :model/Field :id [:in field-ids])))]+ (query-permissions.db/field-table-ids field-ids)))](perms/prime-table-perms-cache {:db-ids #{database-id} :table-ids table-ids})(run! #(when-not (perms/user-has-permission-for-table?api/*current-user-id*@@ -459,9 +460,9 @@to."[field-ids :- [:maybe [:sequential ::lib.schema.id/field]]](when (seq field-ids)- (let [table-ids (t2/select-fn-set :table_id :model/Field :id [:in (set field-ids)])+ (let [table-ids (query-permissions.db/field-table-ids (set field-ids))table-id->database-id (when (seq table-ids)- (t2/select-pk->fn :db_id :model/Table :id [:in table-ids]))]+ (query-permissions.db/table-id->database-id table-ids))](perms/prime-table-perms-cache {:table-ids table-ids})(doseq [table-id table-ids:let [database-id (table-id->database-id table-id)]]diff --git a/src/metabase/query_processor/api.clj b/src/metabase/query_processor/api.cljindex 4f4ed7b3961..33ae379b635 100644--- a/src/metabase/query_processor/api.clj+++ b/src/metabase/query_processor/api.clj@@ -23,6 +23,7 @@[metabase.queries.core :as queries][metabase.query-processor :as qp][metabase.query-processor.compile :as qp.compile]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.middleware.constraints :as qp.constraints][metabase.query-processor.middleware.permissions :as qp.perms][metabase.query-processor.pivot :as qp.pivot]@@ -39,9 +40,7 @@;; defendpoint param schemas (ms/PositiveInt etc.); lib.schema has no API-param coercion schemas^{:clj-kondo/ignore [:discouraged-namespace]} [metabase.util.malli.schema :as ms][metabase.util.performance :refer [get-in select-keys]]- [steffan-westcott.clj-otel.api.trace.span :as span]- ;; endpoint side effects: table-read events and source-card lookups hit the app db directly- ^{:clj-kondo/ignore [:discouraged-namespace]} [toucan2.core :as t2]))+ [steffan-westcott.clj-otel.api.trace.span :as span]));;; -------------------------------------------- Running a Query Normally --------------------------------------------@@ -67,13 +66,13 @@(let [table-id (when (= (lib/normalized-query-type query) :mbql/query)(lib/primary-source-table-id query))](when (int? table-id)- (events/publish-event! :event/table-read {:object (t2/select-one :model/Table :id table-id)+ (events/publish-event! :event/table-read {:object (query-processor.db/table table-id):user-id api/*current-user-id*})));; add sensible constraints for results limits on our query(let [source-card-id (when (= (lib/normalized-query-type query) :mbql/query)(query->source-card-id query))source-card (when source-card-id- (t2/select-one [:model/Card :entity_id :result_metadata :type :card_schema] :id source-card-id))+ (query-processor.db/source-card-metadata source-card-id))info (cond-> {:executed-by api/*current-user-id*:context context:card-id source-card-id}diff --git a/src/metabase/query_processor/dashboard.clj b/src/metabase/query_processor/dashboard.cljindex b8f17cc0601..2542d1895cc 100644--- a/src/metabase/query_processor/dashboard.clj+++ b/src/metabase/query_processor/dashboard.clj@@ -14,6 +14,7 @@[metabase.permissions.core :as perms][metabase.permissions.metric :as permissions.metric][metabase.query-processor.card :as qp.card]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.middleware.constraints :as qp.constraints][metabase.query-processor.parameters.operators :as params.ops]@@ -23,10 +24,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.performance :refer [some not-empty get-in]]- [steffan-westcott.clj-otel.api.trace.span :as span]- ;; 404-checks dashcard/series membership in the app db; an existence check, not query metadata- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2]))+ [steffan-westcott.clj-otel.api.trace.span :as span]))(defn- check-card-and-dashcard-are-in-dashboard"Check that the Card with `card-id` is in Dashboard with `dashboard-id`, either in the already-loaded `dashcard` at the@@ -36,9 +34,7 @@(api/check-404(and (= (:dashboard_id dashcard) dashboard-id)(or (= (:card_id dashcard) card-id)- (t2/exists? :model/DashboardCardSeries- :card_id card-id- :dashboardcard_id dashcard-id))))))+ (query-processor.db/dashcard-series-exists? card-id dashcard-id))))))(defn- current-dimension-mapping?[provider query mapping]diff --git a/src/metabase/query_processor/db.clj b/src/metabase/query_processor/db.cljnew file mode 100644index 00000000000..8f869b80120--- /dev/null+++ b/src/metabase/query_processor/db.clj@@ -0,0 +1,73 @@+(ns metabase.query-processor.db+ "Application database queries for the query processor module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [java-time.api :as t]+ ^{:clj-kondo/ignore [:discouraged-namespace]}+ [toucan2.core :as t2]))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn source-card-metadata+ "The entity id, result metadata, and type of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :entity_id :result_metadata :type :card_schema] :id card-id))++(defn dashcard-series-exists?+ "Whether the Card with `card-id` is a series of the DashboardCard with `dashcard-id`."+ [card-id dashcard-id]+ (t2/exists? :model/DashboardCardSeries :card_id card-id :dashboardcard_id dashcard-id))++(defn cache-entry+ "`row-fn` applied to the results and updated-at of the QueryCache entry for `query-hash`, or nil."+ [row-fn query-hash]+ (t2/select-one-fn row-fn [:model/QueryCache :results :updated_at] :query_hash query-hash))++(defn claim-cache-refresh-lease!+ "Set `refresh_started_at` of the QueryCache entry for `query-hash` to `started-at` if its lease (defaulting to+ `lease-free-sentinel`) is older than `lease-cutoff`, returning the number of rows updated."+ [query-hash lease-free-sentinel lease-cutoff started-at]+ (t2/update! (t2/table-name :model/QueryCache)+ {:query_hash query-hash+ [:coalesce :refresh_started_at lease-free-sentinel] [:< lease-cutoff]}+ {:refresh_started_at started-at}))++(defn delete-cache-entry!+ "Delete the QueryCache entry for `query-hash`."+ [query-hash]+ (t2/delete! (t2/table-name :model/QueryCache) :query_hash query-hash))++(defn delete-cache-entries-updated-before!+ "Delete the QueryCache entries last updated at or before `updated-before`."+ [updated-before]+ (t2/delete! (t2/table-name :model/QueryCache) :updated_at [:<= updated-before]))++(defn insert-query-executions!+ "Insert the QueryExecution `rows`."+ [rows]+ (t2/insert! :model/QueryExecution rows))++(defn set-card-result-metadata!+ "Set the result metadata of the Card with `card-id` without touching `updated_at`."+ [card-id result-metadata]+ (t2/update! :model/Card card-id {:result_metadata result-metadata+ :updated_at :updated_at}))++(defn update-cards-last-used-at!+ "Move `last_used_at` of each Card in `card-id->timestamp` forward to its timestamp, without touching `updated_at`."+ [card-id->timestamp]+ (t2/query {:update [(t2/table-name :model/Card)]+ :where [:in :id (keys card-id->timestamp)]+ :set {:last_used_at (into [:case]+ (mapcat (fn [[id timestamp]]+ [[:= :id id] [:greatest [:coalesce :last_used_at (t/offset-date-time 0)] timestamp]])+ card-id->timestamp))+ :updated_at :updated_at}}))++(defn card-database-ids+ "The `:id`, `:database_id`, and `:card_schema` of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :database_id :card_schema] :id [:in card-ids]))diff --git a/src/metabase/query_processor/middleware/cache_backend/db.clj b/src/metabase/query_processor/middleware/cache_backend/db.cljindex 1123395a763..53b3a917dda 100644--- a/src/metabase/query_processor/middleware/cache_backend/db.clj+++ b/src/metabase/query_processor/middleware/cache_backend/db.clj@@ -3,13 +3,11 @@[java-time.api :as t][metabase.app-db.core :as app-db][metabase.premium-features.core :refer [defenterprise]]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.middleware.cache-backend.interface :as i][metabase.util.date-2 :as u.date][metabase.util.encryption :as encryption]- [metabase.util.log :as log]- ;; this backend's whole job is reading and writing app-db QueryCache rows- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.io ByteArrayInputStream)))@@ -45,11 +43,10 @@its result set is open, so materializing the row first and reading the blob afterwards throws \"object is alreadyclosed\"."[query-hash]- (t2/select-one-fn (fn [row]- {:results (results-as-bytes row)- :updated-at (:updated_at row)})- [:model/QueryCache :results :updated_at]- :query_hash query-hash))+ (query-processor.db/cache-entry (fn [row]+ {:results (results-as-bytes row)+ :updated-at (:updated_at row)})+ query-hash))(defn invalidated-at-ttl"Freshness boundary for a `:ttl` strategy: cache entries with `updated_at` older than this are stale. Returns nil when@@ -89,10 +86,7 @@blob was last written\", read that way by [[cache-fresh?]], [[purge-old-cache-entries!]], and the EE refreshscheduler; bumping it here would let a crashed refresh silently extend the row's freshness (#76856)."[query-hash lease-ms]- (pos? (t2/update! (t2/table-name :model/QueryCache)- {:query_hash query-hash- [:coalesce :refresh_started_at lease-free-sentinel] [:< (ms-ago lease-ms)]}- {:refresh_started_at (t/offset-date-time)})))+ (pos? (query-processor.db/claim-cache-refresh-lease! query-hash lease-free-sentinel (ms-ago lease-ms) (t/offset-date-time))))(defn delete-entry!"Delete the cache entry for `query-hash`, if one exists. Deleting the row also releases any held refresh lease, so@@ -101,7 +95,7 @@shouldn't fail a query that already ran successfully."[^bytes query-hash](try- (t2/delete! (t2/table-name :model/QueryCache) :query_hash query-hash)+ (query-processor.db/delete-cache-entry! query-hash)(catch Throwable e(log/errorf "Error deleting outdated cache entry: %s" (ex-message e))))nil)@@ -112,8 +106,7 @@{:pre [(number? max-age-seconds)]}(log/trace "Purging old cache entries.")(try- (t2/delete! (t2/table-name :model/QueryCache)- :updated_at [:<= (seconds-ago max-age-seconds)])+ (query-processor.db/delete-cache-entries-updated-before! (seconds-ago max-age-seconds))(catch Throwable e(log/errorf "Error purging old cache entries: %s" (ex-message e))))nil)diff --git a/src/metabase/query_processor/middleware/process_userland_query.clj b/src/metabase/query_processor/middleware/process_userland_query.cljindex f39e84af873..90234a617c2 100644--- a/src/metabase/query_processor/middleware/process_userland_query.clj+++ b/src/metabase/query_processor/middleware/process_userland_query.clj@@ -17,6 +17,7 @@[metabase.lib.computed :as lib.computed][metabase.lib.core :as lib][metabase.queries.models.query :as query]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.middleware.enterprise :as qp.middleware.enterprise][metabase.query-processor.schema :as qp.schema][metabase.query-processor.util :as qp.util]@@ -25,10 +26,7 @@[metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.performance :refer [every? empty? get-in not-empty]]- ;; records QueryExecution rows in the app db; a write the metadata provider can't do- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2]))+ [metabase.util.performance :refer [every? empty? get-in not-empty]]))(set! *warn-on-reflection* true)@@ -65,7 +63,7 @@(when (seq no-context)(log/warnf "Cannot save %d QueryExecution(s), missing :context" (count no-context)))(when (seq with-context)- (t2/insert! :model/QueryExecution (map #(dissoc % :json_query) with-context))))+ (query-processor.db/insert-query-executions! (map #(dissoc % :json_query) with-context))))(catch Throwable e(log/errorf "Error saving query execution info: %s" (ex-message e))))))diff --git a/src/metabase/query_processor/middleware/results_metadata.clj b/src/metabase/query_processor/middleware/results_metadata.cljindex bd354df618d..c79bb0efc7b 100644--- a/src/metabase/query_processor/middleware/results_metadata.clj+++ b/src/metabase/query_processor/middleware/results_metadata.clj@@ -12,6 +12,7 @@[metabase.lib.metadata :as lib.metadata][metabase.lib.schema :as lib.schema][metabase.lib.schema.metadata :as lib.schema.metadata]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.reducible :as qp.reducible][metabase.query-processor.schema :as qp.schema];; still passes state via the store's miscellaneous-value slot; general-cached-value migration pending@@ -20,10 +21,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [metabase.util.performance :refer [mapv select-keys get-in]]- ;; persists recomputed result_metadata back to the Card row; the metadata provider is read-only- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2]))+ [metabase.util.performance :refer [mapv select-keys get-in]]));;; +----------------------------------------------------------------------------------------------------------------+;;; | Middleware |@@ -88,8 +86,7 @@(qp.store/miscellaneous-value [::card-stored-metadata]))))(when-let [error (me/humanize (mr/explain [:sequential ::lib.schema.metadata/lib-or-legacy-column] actual-metadata))](throw (ex-info "Invalid result metadata!" {:error error, :metadata actual-metadata})))- (t2/update! :model/Card card-id {:result_metadata actual-metadata- :updated_at :updated_at})))+ (query-processor.db/set-card-result-metadata! card-id actual-metadata)));; if for some reason we weren't able to record results metadata for this query then just proceed as normal;; rather than failing the entire query(catch Throwable ediff --git a/src/metabase/query_processor/middleware/update_used_cards.clj b/src/metabase/query_processor/middleware/update_used_cards.cljindex 6509af7db3b..9ac8d2c90b4 100644--- a/src/metabase/query_processor/middleware/update_used_cards.clj+++ b/src/metabase/query_processor/middleware/update_used_cards.clj@@ -6,14 +6,12 @@[metabase.lib.metadata :as lib.metadata][metabase.lib.schema.common :as lib.schema.common][metabase.lib.schema.id :as lib.schema.id]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.schema :as qp.schema];; the legacy QP pipeline still conveys the metadata provider via the ambient store; no MBQL 5 path yet^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store][metabase.util.log :as log]- [metabase.util.malli :as mu]- ;; batch-updates Card.last_used_at in the app db; a write outside the metadata provider's scope- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -32,13 +30,7 @@;; :retry-transient? — the body is a single idempotent statement, safe to re-run on a;; multi-master deadlock (e.g. MariaDB Galera, where the cluster lock can't serialize writers).(cluster-lock/with-cluster-lock {:lock cluster-lock/card-statistics-lock :retry-transient? true}- (t2/query {:update [(t2/table-name :model/Card)]- :where [:in :id (keys card-id->timestamp)]- :set {:last_used_at (into [:case]- (mapcat (fn [[id timestamp]]- [[:= :id id] [:greatest [:coalesce :last_used_at (t/offset-date-time 0)] timestamp]])- card-id->timestamp))- :updated_at :updated_at}}))+ (query-processor.db/update-cards-last-used-at! card-id->timestamp))(catch Throwable e(log/errorf "Error updating used cards: %s" (ex-message e))))))diff --git a/src/metabase/query_processor/setup.clj b/src/metabase/query_processor/setup.cljindex 2dae9557a00..34011cbfb72 100644--- a/src/metabase/query_processor/setup.clj+++ b/src/metabase/query_processor/setup.clj@@ -14,6 +14,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.metadata :as lib.schema.metadata][metabase.lib.util :as lib.util]+ [metabase.query-processor.db :as query-processor.db][metabase.query-processor.error-type :as qp.error-type][metabase.query-processor.pipeline :as qp.pipeline][metabase.query-processor.schema :as qp.schema]@@ -22,10 +23,7 @@[metabase.settings.core :as setting][metabase.util.i18n :as i18n][metabase.util.log :as log]- [metabase.util.malli :as mu]- ;; pre-seeds bare-bones card metadata from the app db before any metadata provider exists- ^{:clj-kondo/ignore [:discouraged-namespace]}- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(java.util.concurrent ScheduledFuture ScheduledThreadPoolExecutor ThreadFactory TimeUnit)(org.apache.logging.log4j ThreadContext)))@@ -56,14 +54,13 @@(defn- bootstrap-metadatas [{metadata-type :lib/type, id-set :id, :as _metadata-spec}](when (and (seq id-set)(= metadata-type :metadata/card))- (t2/select-fn-vec- (fn [card]- {:lib/type :metadata/card- :id (:id card)- :name (format "Card #%d" (:id card))- :database-id (:database_id card)})- [:model/Card :id :database_id :card_schema]- :id [:in (set id-set)])))+ (into []+ (map (fn [card]+ {:lib/type :metadata/card+ :id (:id card)+ :name (format "Card #%d" (:id card))+ :database-id (:database_id card)}))+ (query-processor.db/card-database-ids (set id-set)))))(deftype ^:private BootstrapMetadataProvider []lib.metadata.protocols/MetadataProviderdiff --git a/src/metabase/remote_sync/core.clj b/src/metabase/remote_sync/core.cljindex ad532cabd8f..3ae0077364d 100644--- a/src/metabase/remote_sync/core.clj+++ b/src/metabase/remote_sync/core.clj@@ -1,7 +1,7 @@(ns metabase.remote-sync.core(:require[metabase.premium-features.core :refer [defenterprise]]- [toucan2.core :as t2]))+ [metabase.remote-sync.db :as remote-sync.db]))(defenterprise collection-editable?"Returns if remote-synced collections are editable. Takes a collection to check for eligibility.@@ -71,9 +71,7 @@;; For other models, check if they're in a remote-synced collection(let [collection-ids (into #{} (keep :collection_id) instances)remote-synced-coll-ids (when (seq collection-ids)- (t2/select-pks-set :model/Collection- :id [:in collection-ids]- :is_remote_synced true))]+ (remote-sync.db/remote-synced-collection-ids collection-ids))](into {}(map (fn [inst][(:id inst)diff --git a/src/metabase/remote_sync/db.clj b/src/metabase/remote_sync/db.cljnew file mode 100644index 00000000000..3fadd19c036--- /dev/null+++ b/src/metabase/remote_sync/db.clj@@ -0,0 +1,17 @@+(ns metabase.remote-sync.db+ "Application database queries for the remote sync module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (hydration definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn remote-synced-collection-ids+ "The ids among `collection-ids` of Collections that are remote synced, or nil."+ [collection-ids]+ (t2/select-pks-set :model/Collection :id [:in collection-ids] :is_remote_synced true))++(defn is-remote-synced-by-id+ "The `:id` and the containing Collection's `:is_remote_synced` of the `model` rows with `ids`."+ [model ids]+ (t2/select [model :id [:c.is_remote_synced :is_remote_synced]]+ {:where [:in (keyword (str (name (t2/table-name model)) ".id")) ids]+ :join [[:collection :c] [:= :collection_id :c.id]]}))diff --git a/src/metabase/remote_sync/init.clj b/src/metabase/remote_sync/init.cljindex e515ff672f3..7525f740fa1 100644--- a/src/metabase/remote_sync/init.clj+++ b/src/metabase/remote_sync/init.clj@@ -2,6 +2,7 @@(:require[metabase.api.common :as api][metabase.models.interface :as mi]+ [metabase.remote-sync.db :as remote-sync.db][metabase.remote-sync.events][methodical.core :as methodical][toucan2.core :as t2]))@@ -12,10 +13,6 @@(mi/instances-with-hydrated-data items k#(into {}(map (juxt :id (comp api/bit->boolean :is_remote_synced))- (t2/select [model :id [:c.is_remote_synced :is_remote_synced]]- {:where [:in (keyword (str (name (t2/table-name model)) ".id"))- (map :id items)]- :join [[:collection :c]- [:= :collection_id :c.id]]})))+ (remote-sync.db/is-remote-synced-by-id model (map :id items)))):id{:default false}))diff --git a/src/metabase/request/db.clj b/src/metabase/request/db.cljnew file mode 100644index 00000000000..fe279da38fa--- /dev/null+++ b/src/metabase/request/db.clj@@ -0,0 +1,26 @@+(ns metabase.request.db+ "Application database queries for the request module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.users.models.user :as user]+ [toucan2.core :as t2]))++(def ^:private current-user-columns+ ;; `:type` is needed so [[user/add-attributes]] can refuse to add attributes to non-personal (API-key/internal) users+ (into [:model/User :type] user/admin-or-self-visible-columns))++(defn current-user+ "The User with `user-id` with the columns the current user may see of themselves, or nil."+ [user-id]+ (t2/select-one current-user-columns :id user-id))++(defn current-user-for-id+ "The User with `user-id` as `{:metabase-user-id :is-superuser? :is-data-analyst? :user-locale :settings}`, or nil."+ [user-id]+ (t2/select-one [:model/User+ [:id :metabase-user-id]+ [:is_superuser :is-superuser?]+ [:is_data_analyst :is-data-analyst?]+ [:locale :user-locale]+ :settings]+ :id user-id))diff --git a/src/metabase/request/session.clj b/src/metabase/request/session.cljindex 61f1e6a3710..223ca261f5a 100644--- a/src/metabase/request/session.clj+++ b/src/metabase/request/session.clj@@ -2,20 +2,16 @@(:require[metabase.api.common :refer [*current-user* *current-user-id* *current-user-permissions-set* *is-group-manager?* *is-superuser?* *is-data-analyst?*]][metabase.permissions.core :as perms]+ [metabase.request.db :as request.db][metabase.request.schema :as request.schema][metabase.settings.core :as setting][metabase.users.models.user :as user][metabase.util.i18n :as i18n]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))--(def ^:private current-user-fields- ;; `:type` is needed so [[user/add-attributes]] can refuse to add attributes to non-personal (API-key/internal) users- (into [:model/User :type] user/admin-or-self-visible-columns))+ [metabase.util.malli :as mu]))(defn- find-user [user-id](when user-id- (some-> (t2/select-one current-user-fields, :id user-id)+ (some-> (request.db/current-user user-id)user/add-attributes)))(def ^:private ^:dynamic *user-local-values-user-id*@@ -64,13 +60,7 @@"Part of the impl for `with-current-user` -- don't use this directly."[current-user-id](when current-user-id- (t2/select-one [:model/User- [:id :metabase-user-id]- [:is_superuser :is-superuser?]- [:is_data_analyst :is-data-analyst?]- [:locale :user-locale]- :settings]- :id current-user-id)))+ (request.db/current-user-for-id current-user-id)))(defn do-as-admin"Execute `thunk` with admin perms."diff --git a/src/metabase/revisions/api.clj b/src/metabase/revisions/api.cljindex 537b30d634c..e68bfff4575 100644--- a/src/metabase/revisions/api.clj+++ b/src/metabase/revisions/api.clj@@ -10,10 +10,10 @@[metabase.parameters.params :as params][metabase.queries.core :as queries][metabase.query-permissions.core :as query-perms]+ [metabase.revisions.db :as revisions.db][metabase.revisions.models.revision :as revision][metabase.util.malli.schema :as ms][metabase.util.regex :as u.regex]- [toucan2.core :as t2][toucan2.model :as t2.model]))(def ^:private entity->model@@ -35,7 +35,7 @@(assert (keyword? model));; Ensure the model namespace is loaded before using it(t2.model/resolve-model model)- [model (t2/select-one model :id id)]))+ [model (revisions.db/entity model id)]));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -64,19 +64,14 @@(defn- stored-card-references[model id]- (let [parameter-cards (set (t2/select-fn-vec :card_id :model/ParameterCard- :parameterized_object_type (if (= model :model/Dashboard)- "dashboard"- "card")- :parameterized_object_id id))]+ (let [parameter-cards (set (revisions.db/parameter-card-ids (if (= model :model/Dashboard)+ "dashboard"+ "card")+ id))](if (= model :model/Dashboard)(into parameter-cards- (concat (t2/select-fn-vec :card_id :model/DashboardCard :dashboard_id id)- (t2/select-fn-vec :card_id :model/DashboardCardSeries- {:where [:in :dashboardcard_id- ^:allow-subquery {:select [:id]- :from [(t2/table-name :model/DashboardCard)]- :where [:= :dashboard_id id]}]})))+ (concat (revisions.db/dashboard-card-ids id)+ (revisions.db/dashboard-series-card-ids id)))parameter-cards)))(defn- revision-parameter-field-ids@@ -95,7 +90,7 @@mapping)card-ids (into #{} (keep :card_id) mappings)card-id->query (when (seq card-ids)- (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))]+ (revisions.db/card-queries card-ids))](into [] (keep (fn [{:keys [target card_id]}](resolve-target target (card-id->query card_id))))mappings))@@ -123,7 +118,7 @@[:revision_id ms/PositiveInt]]](let [[model instance] (model-and-instance entity id)_ (api/write-check instance)- revision (api/check-404 (t2/select-one :model/Revision :model (name model), :model_id id, :id revision-id))]+ revision (api/check-404 (revisions.db/revision (name model) id revision-id))];; if reverting a Card, make sure we have *data* permissions to run the query we're reverting to(when (= model :model/Card);; TODO -- we should be using something like `api/read-check` for this, but unfortunately the impl for Cardsdiff --git a/src/metabase/revisions/db.clj b/src/metabase/revisions/db.cljnew file mode 100644index 00000000000..3d2f7facbf9--- /dev/null+++ b/src/metabase/revisions/db.clj@@ -0,0 +1,172 @@+(ns metabase.revisions.db+ "Application database queries for the revisions module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn entity+ "The `model` row with `id`, or nil."+ [model id]+ (t2/select-one model :id id))++(defn raw-row+ "The `model` row with `id` read straight from its table, or nil."+ [model id]+ (t2/select-one (t2/table-name model) :id id))++(defn update-entity!+ "Apply `changes` to the `model` row with `id`."+ [model id changes]+ (t2/update! model id changes))++(defn parameter-card-ids+ "The Card ids of the ParameterCards of the `parameterized-object-type` with `parameterized-object-id`."+ [parameterized-object-type parameterized-object-id]+ (t2/select-fn-vec :card_id :model/ParameterCard+ :parameterized_object_type parameterized-object-type+ :parameterized_object_id parameterized-object-id))++(defn dashboard-card-ids+ "The Card ids of the DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-fn-vec :card_id :model/DashboardCard :dashboard_id dashboard-id))++(defn dashboard-series-card-ids+ "The Card ids of the DashboardCardSeries of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-fn-vec :card_id :model/DashboardCardSeries+ {:where [:in :dashboardcard_id+ ^:allow-subquery {:select [:id]+ :from [(t2/table-name :model/DashboardCard)]+ :where [:= :dashboard_id dashboard-id]}]}))++(defn card-queries+ "A map of Card id to query for the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn :dataset_query :model/Card :id [:in card-ids]))++(defn revision+ "The Revision with `revision-id` of the `model-name` row with `model-id`, or nil."+ [model-name model-id revision-id]+ (t2/select-one :model/Revision :model model-name, :model_id model-id, :id revision-id))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn dashcards+ "The DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id))++(defn dashboard-tabs+ "The DashboardTabs of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select :model/DashboardTab :dashboard_id dashboard-id))++(defn active-card-ids-for-dashboard+ "The ids among `card-ids` of unarchived Cards that belong to the Dashboard with `dashboard-id` or to no Dashboard."+ [card-ids dashboard-id]+ (t2/select-pks-set :model/Card+ {:where [:and+ [:in :id card-ids]+ [:= :archived false]+ [:or+ [:= :dashboard_id dashboard-id]+ [:= :dashboard_id nil]]]}))++(defn active-card-ids+ "The ids among `card-ids` of unarchived Cards."+ [card-ids]+ (t2/select-pks-set :model/Card {:where [:and [:in :id card-ids] [:= :archived false]]}))++(defn lock-revisions!+ "Lock the Revisions of the `model-name` row with `model-id` for update."+ [model-name model-id]+ (t2/query {:select [:id]+ :from [:revision]+ :where [:and+ [:= :model model-name]+ [:= :model_id model-id]]+ :for :update}))++(defn revision-ids-newest-first+ "The ids of the Revisions of the `model-name` row with `model-id`, newest first."+ [model-name model-id]+ (t2/select-fn-vec :id :model/Revision+ :model model-name+ :model_id model-id+ {:order-by [[:timestamp :desc]+ [:id :desc]]}))++(defn delete-revisions!+ "Delete the Revisions with `ids`."+ [ids]+ (t2/delete! :model/Revision :id [:in ids]))++(defn unmark-most-recent-revisions!+ "Clear `most_recent` on the Revisions of the `model-name` row with `model-id` other than `revision-id`."+ [model-name model-id revision-id]+ ;; updates the table directly: revisions are otherwise immutable+ (t2/update! (t2/table-name :model/Revision)+ {:model model-name :model_id model-id :most_recent true :id [:not= revision-id]}+ {:most_recent false}))++(defn revisions+ "The Revisions of the `model-name` row with `model-id`, newest first."+ [model-name model-id]+ (t2/select :model/Revision :model model-name :model_id model-id {:order-by [[:id :desc]]}))++(defn latest-revision+ "The newest Revision of the `model-name` row with `model-id`, or nil."+ [model-name model-id]+ (t2/select-one :model/Revision :model model-name, :model_id model-id, {:order-by [[:id :desc]]}))++(defn latest-revision-object+ "The serialized object of the newest Revision of the `model-name` row with `model-id`, or nil."+ [model-name model-id]+ (t2/select-one-fn :object :model/Revision :model model-name :model_id model-id {:order-by [[:id :desc]]}))++(defn revision-object+ "The serialized object of the Revision with `revision-id` of the `model-name` row with `model-id`, or nil."+ [model-name model-id revision-id]+ (t2/select-one-fn :object :model/Revision :model model-name :model_id model-id :id revision-id))++(defn insert-revision!+ "Insert the Revision `row`."+ [row]+ (t2/insert! :model/Revision row))++(defn insert-revision-returning!+ "Insert the Revision `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Revision row))++(defn latest-editors-reducible+ "A reducible of the model id, editing User, and timestamp of the most recent Revisions of the `db-model` rows with+ `ids`."+ [db-model ids]+ (t2/reducible-query+ {:select [:r.model_id :u.id :u.email :u.first_name :u.last_name :r.timestamp]+ :from [[:revision :r]]+ :left-join [[:core_user :u] [:= :u.id :r.user_id]]+ :where [:and+ [:= :r.most_recent true]+ [:= :r.model db-model]+ [:in :r.model_id ids]]}))++(defn latest-changes+ "The editing User, model, model id, and timestamp of the most recent Revisions of the Cards with `card-ids`+ and/or the Dashboards with `dashboard-ids`."+ [card-ids dashboard-ids]+ (t2/query {:select [:u.id :u.email :u.first_name :u.last_name+ :r.model :r.model_id :r.timestamp]+ :from [[:revision :r]]+ :left-join [[:core_user :u] [:= :u.id :r.user_id]]+ :where [:and [:= :r.most_recent true]+ (into [:or]+ (keep (fn [[model-name ids]]+ (when (seq ids)+ [:and [:= :model model-name] [:in :model_id ids]])))+ [["Card" card-ids] ["Dashboard" dashboard-ids]])]}))diff --git a/src/metabase/revisions/impl/card.clj b/src/metabase/revisions/impl/card.cljindex 79bbcbb837f..3a020e49c95 100644--- a/src/metabase/revisions/impl/card.clj+++ b/src/metabase/revisions/impl/card.clj@@ -1,6 +1,7 @@(ns metabase.revisions.impl.card(:require[metabase.queries.core :as queries]+ [metabase.revisions.db :as revisions.db][metabase.revisions.models.revision :as revision][toucan2.core :as t2]))@@ -41,8 +42,7 @@(not (:card_schema serialized-card)) (assoc :card_schema queries/starting-card-schema-version))restored (apply dissoc serialized-card excluded-columns-for-card-revision)](queries/check-new-parameter-source-card-permissions "card" id (:parameters restored))- (queries/maybe-unverify! (t2/hydrate (t2/select-one :model/Card :id id)- [:moderation_reviews :moderator_details])+ (queries/maybe-unverify! (t2/hydrate (revisions.db/card id) [:moderation_reviews :moderator_details])restored{:id user-id})((get-method revision/revert-to-revision! :default) model id user-id restored)))diff --git a/src/metabase/revisions/impl/dashboard.clj b/src/metabase/revisions/impl/dashboard.cljindex 2461de2afa4..71f6615be0e 100644--- a/src/metabase/revisions/impl/dashboard.clj+++ b/src/metabase/revisions/impl/dashboard.clj@@ -7,6 +7,7 @@[metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.dashboards.models.dashboard-tab :as dashboard-tab][metabase.queries.core :as queries]+ [metabase.revisions.db :as revisions.db][metabase.revisions.models.revision :as revision][metabase.util :as u][metabase.util.i18n :refer [deferred-tru deferred-trun]]@@ -47,7 +48,7 @@(defn- revert-dashcards[dashboard-id serialized-cards]- (let [current-cards (->> (t2/hydrate (t2/select :model/DashboardCard :dashboard_id dashboard-id) :series)+ (let [current-cards (->> (t2/hydrate (revisions.db/dashcards dashboard-id) :series)(mapv (fn [dashcard](-> (apply dissoc (t2.realize/realize dashcard)excluded-columns-for-dashcard-revision)@@ -68,15 +69,7 @@[dashboard-id dashcards](let [card-ids (set (keep :card_id dashcards))active-card-ids (when-let [card-ids (seq card-ids)]- (t2/select-pks-set :model/Card- {:where [:and- [:in :id card-ids]- ;; skip when archived- [:= :archived false]- ;; belong to this dashboard, or are not Dashboard Questions- [:or- [:= :dashboard_id dashboard-id]- [:= :dashboard_id nil]]]}))+ (revisions.db/active-card-ids-for-dashboard card-ids dashboard-id))inactive-card-ids (set/difference card-ids active-card-ids)](remove #(contains? inactive-card-ids (:card_id %)) dashcards)))@@ -86,10 +79,7 @@[parameters](let [card-ids (set (keep #(get-in % [:values_source_config :card_id]) parameters))active-card-ids (when (seq card-ids)- (t2/select-pks-set :model/Card- {:where [:and- [:in :id card-ids]- [:= :archived false]]}))+ (revisions.db/active-card-ids card-ids))invalid-card-ids (set/difference card-ids active-card-ids)](if (empty? invalid-card-ids)parameters@@ -110,8 +100,8 @@(apply dissoc serialized-dashboard :cards :tabs excluded-columns-for-dashboard-revision));; Now update the tabs and cards as needed(let [serialized-dashcards (:cards serialized-dashboard)- current-tabs (t2/select-fn-vec #(dissoc (t2.realize/realize %) :created_at :updated_at :entity_id :dashboard_id)- :model/DashboardTab :dashboard_id dashboard-id)+ current-tabs (mapv #(dissoc (t2.realize/realize %) :created_at :updated_at :entity_id :dashboard_id)+ (revisions.db/dashboard-tabs dashboard-id)){:keys [old->new-tab-id]} (dashboard-tab/do-update-tabs! dashboard-id current-tabs (:tabs serialized-dashboard))_ (dashboard/archive-or-unarchive-internal-dashboard-questions! dashboard-id serialized-dashcards)serialized-dashcards (cond->> serialized-dashcardsdiff --git a/src/metabase/revisions/models/revision.clj b/src/metabase/revisions/models/revision.cljindex 1fb16f24b9b..664029c4d14 100644--- a/src/metabase/revisions/models/revision.clj+++ b/src/metabase/revisions/models/revision.clj@@ -4,6 +4,7 @@[metabase.config.core :as config][metabase.models.interface :as mi][metabase.queries.core :as queries]+ [metabase.revisions.db :as revisions.db][metabase.revisions.models.revision.diff :refer [diff-strings*]][metabase.util :as u][metabase.util.i18n :refer [deferred-tru tru]]@@ -37,12 +38,12 @@(defmethod revert-to-revision! :default[model id _user-id serialized-instance]- (let [valid-columns (keys (t2/select-one (t2/table-name model) :id id))+ (let [valid-columns (keys (revisions.db/raw-row model id));; Only include fields that we know are on the model in the current version of Metabase! Otherwise we'll get;; an error if a field in an earlier version has since been dropped, but is still present in the revision.;; This is best effort — other kinds of schema changes could still break the ability to revert successfully.revert-instance (select-keys serialized-instance valid-columns)]- (t2/update! model id revert-instance)))+ (revisions.db/update-entity! model id revert-instance)))(defmulti diff-map"Return a map describing the difference between `object-1` and `object-2`."@@ -92,12 +93,7 @@(t2/define-before-insert :model/Revision[{:keys [model model_id] :as revision}];; obtain a lock on the existing revisions for this entity to prevent concurrent inserts of new revisions- (t2/query {:select [:id]- :from [:revision]- :where [:and- [:= :model model]- [:= :model_id model_id]]- :for :update})+ (revisions.db/lock-revisions! model model_id)(assoc revision:timestamp (or (:timestamp revision) :%now):metabase_version config/mb-version-string@@ -127,23 +123,15 @@(defn- delete-old-revisions!"Delete old revisions of `model` with `id` when there are more than `max-revisions` in the DB."[model id]- (when-let [old-revisions (seq (drop max-revisions (t2/select-fn-vec :id :model/Revision- :model (name model)- :model_id id- {:order-by [[:timestamp :desc]- [:id :desc]]})))]- (t2/delete! :model/Revision :id [:in old-revisions])))+ (when-let [old-revisions (seq (drop max-revisions (revisions.db/revision-ids-newest-first (name model) id)))]+ (revisions.db/delete-revisions! old-revisions)))(t2/define-after-insert :model/Revision[revision](u/prog1 revision(let [{:keys [id model model_id]} revision]- ;; Note 1: Update the last `most_recent revision` to false (not including the current revision)- ;; Note 2: We don't allow updating revision but this is a special case, so we by pass the check by- ;; updating directly with the table name- (t2/update! (t2/table-name :model/Revision)- {:model model :model_id model_id :most_recent true :id [:not= id]}- {:most_recent false})+ ;; Update the last `most_recent revision` to false (not including the current revision)+ (revisions.db/unmark-most-recent-revisions! model model_id id)(delete-old-revisions! model model_id))));;; # Functions@@ -188,7 +176,7 @@[model :- [:fn toucan-model?]id :- pos-int?](let [model-name (name model)]- (t2/select :model/Revision :model model-name :model_id id {:order-by [[:id :desc]]})))+ (revisions.db/revisions model-name id)))(mu/defn revisions+details"Fetch `revisions` for `model` with `id` that the current user may see, and add details. Diffs and descriptions@@ -217,7 +205,7 @@[:message {:optional true} [:maybe :string]]]](let [entity-name (name entity)serialized-object (serialize-instance entity id (dissoc object :message))- last-object (t2/select-one-fn :object :model/Revision :model entity-name :model_id id {:order-by [[:id :desc]]})+ last-object (revisions.db/latest-revision-object entity-name id);; For Card entities, ensure :card_schema is excluded from comparison;; Old revisions might have :card_schema added by after-select, but this field;; shouldn't trigger new revisions as it's a technical/internal field@@ -231,14 +219,13 @@;; so to be safe, we'll just compare them as string(when-not (= (json/encode serialized-object)(json/encode last-object-for-comparison))- (t2/insert! :model/Revision- :model entity-name- :model_id id- :user_id user-id- :object serialized-object- :is_creation is-creation?- :is_reversion false- :message message)+ (revisions.db/insert-revision! {:model entity-name+ :model_id id+ :user_id user-id+ :object serialized-object+ :is_creation is-creation?+ :is_reversion false+ :message message})object)))(mu/defn revert!@@ -250,22 +237,20 @@[:entity [:fn toucan-model?]]]](let [{:keys [id user-id revision-id entity]} infomodel-name (name entity)- serialized-instance (t2/select-one-fn :object :model/Revision :model model-name :model_id id :id revision-id)]+ serialized-instance (revisions.db/revision-object model-name id revision-id)](t2/with-transaction [_conn](let [already-in-target-state? (= serialized-instance- (t2/select-one-fn :object :model/Revision- :model model-name :model_id id {:order-by [[:id :desc]]}))]+ (revisions.db/latest-revision-object model-name id))];; Do the reversion of the object(revert-to-revision! entity id user-id serialized-instance);; Push a new revision to record this change- (let [last-revision (t2/select-one :model/Revision :model model-name, :model_id id, {:order-by [[:id :desc]]})]+ (let [last-revision (revisions.db/latest-revision model-name id)](if already-in-target-state?last-revision- (let [new-revision (first (t2/insert-returning-instances! :model/Revision- :model model-name- :model_id id- :user_id user-id- :object serialized-instance- :is_creation false- :is_reversion true))]+ (let [new-revision (revisions.db/insert-revision-returning! {:model model-name+ :model_id id+ :user_id user-id+ :object serialized-instance+ :is_creation false+ :is_reversion true})](add-revision-details entity new-revision last-revision))))))))diff --git a/src/metabase/revisions/models/revision/diff.clj b/src/metabase/revisions/models/revision/diff.cljindex 08272c27964..ff4b6c6b598 100644--- a/src/metabase/revisions/models/revision/diff.clj+++ b/src/metabase/revisions/models/revision/diff.clj@@ -2,14 +2,14 @@(:require[clojure.data :as data][metabase.models.interface :as mi]+ [metabase.revisions.db :as revisions.db][metabase.util.i18n :refer [deferred-tru]]- [metabase.util.match :as match]- [toucan2.core :as t2]))+ [metabase.util.match :as match]))(defn- readable-name[model id](when id- (when-let [instance (t2/select-one model :id id)]+ (when-let [instance (revisions.db/entity model id)](when (mi/can-read? instance)(:name instance)))))diff --git a/src/metabase/revisions/models/revision/last_edit.clj b/src/metabase/revisions/models/revision/last_edit.cljindex e17492473c4..cf4d00bc175 100644--- a/src/metabase/revisions/models/revision/last_edit.clj+++ b/src/metabase/revisions/models/revision/last_edit.clj@@ -11,10 +11,10 @@[clojure.set :as set][java-time.api :as t][medley.core :as m]+ [metabase.revisions.db :as revisions.db][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [steffan-westcott.clj-otel.api.trace.span :as span]- [toucan2.core :as t2]))+ [steffan-westcott.clj-otel.api.trace.span :as span]))(def ^:private model->db-model {:card "Card" :dashboard "Dashboard"})@@ -51,14 +51,7 @@(:model_id card-updated-info)(select-keys card-updated-info [:id :email :first_name :last_name :timestamp]))){}- (t2/reducible-query- {:select [:r.model_id :u.id :u.email :u.first_name :u.last_name :r.timestamp]- :from [[:revision :r]]- :left-join [[:core_user :u] [:= :u.id :r.user_id]]- :where [:and- [:= :r.most_recent true]- [:= :r.model (model->db-model model)]- [:in :r.model_id ids]]}))]+ (revisions.db/latest-editors-reducible (model->db-model model) ids))](map (fn [item](m/assoc-some item :last-edit-info (-> item :id id->updated-info)))items))))))@@ -87,17 +80,7 @@:dashboard {dashboard_id {:id :email :first_name :last_name :timestamp}}}"[{:keys [card-ids dashboard-ids]}](when (seq (concat card-ids dashboard-ids))- (let [latest-changes (t2/query {:select [:u.id :u.email :u.first_name :u.last_name- :r.model :r.model_id :r.timestamp]- :from [[:revision :r]]- :left-join [[:core_user :u] [:= :u.id :r.user_id]]- :where [:and [:= :r.most_recent true]- (into [:or]- (keep (fn [[model-name ids]]- (when (seq ids)- [:and [:= :model model-name] [:in :model_id ids]])))- [["Card" card-ids]- ["Dashboard" dashboard-ids]])]})]+ (let [latest-changes (revisions.db/latest-changes card-ids dashboard-ids)](->> latest-changes(group-by :model)(m/map-vals (fn [model-changes]diff --git a/src/metabase/run_tracking/db.clj b/src/metabase/run_tracking/db.cljnew file mode 100644index 00000000000..9a9d8105a1d--- /dev/null+++ b/src/metabase/run_tracking/db.clj@@ -0,0 +1,29 @@+(ns metabase.run-tracking.db+ "Application database queries for the run tracking module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn heartbeat!+ "Set `heartbeat-column` to now on the `model` rows in `ids` matching the Honey SQL predicate `active`."+ [model active heartbeat-column ids]+ (t2/query {:update (t2/table-name model)+ :set {heartbeat-column :%now}+ :where [:and active [:in :id ids]]}))++(defn active-ids+ "The ids among `ids` of the `model` rows matching the Honey SQL predicate `active`."+ [model active ids]+ (t2/select-fn-set :id model {:where [:and [:in :id ids] active]}))++(defn lock-active-stale-rows+ "The `model` rows matching the Honey SQL predicates `active` and `stale`, locked for update."+ [model active stale]+ (t2/select model {:where [:and active stale] :for :update}))++(defn set-terminal!+ "Apply the `terminal` column values to the `model` rows in `ids` matching the Honey SQL predicate `active`."+ [model active ids terminal]+ (t2/query {:update (t2/table-name model)+ :set terminal+ :where [:and active [:in :id ids]]}))diff --git a/src/metabase/run_tracking/ops.clj b/src/metabase/run_tracking/ops.cljindex 7a285b602c1..012a8866ba6 100644--- a/src/metabase/run_tracking/ops.clj+++ b/src/metabase/run_tracking/ops.clj@@ -3,6 +3,7 @@(:require[metabase.analytics-interface.core :as analytics][metabase.app-db.core :as mdb]+ [metabase.run-tracking.db :as run-tracking.db][metabase.util.honey-sql-2 :as h2x][toucan2.core :as t2])(:import@@ -34,9 +35,7 @@`active` is a HoneySQL predicate, e.g. `[:= :is_active true]`."[model active heartbeat-column ids](when (seq ids)- (t2/query {:update (t2/table-name model)- :set {heartbeat-column :%now}- :where [:and active [:in :id ids]]})))+ (run-tracking.db/heartbeat! model active heartbeat-column ids)))(defn heartbeat-and-reconcile!"Per-node tick for the runs this process owns: call `(heartbeat! ids)`, then `(on-gone id)` for@@ -47,7 +46,7 @@[{:keys [model active ids heartbeat! on-gone]}](when-let [ids (seq ids)](heartbeat! ids)- (let [active-ids (t2/select-fn-set :id model {:where [:and [:in :id ids] active]})]+ (let [active-ids (run-tracking.db/active-ids model active ids)](doseq [id ids:when (not (contains? active-ids id))](on-gone id)))))@@ -59,10 +58,8 @@`active` is a HoneySQL predicate, e.g. `[:= :is_active true]`."[{:keys [model active stale terminal]}](t2/with-transaction [_conn]- (when-let [rows (not-empty (t2/select model {:where [:and active stale] :for :update}))]- (t2/query {:update (t2/table-name model)- :set terminal- :where [:and active [:in :id (mapv :id rows)]]})+ (when-let [rows (not-empty (run-tracking.db/lock-active-stale-rows model active stale))]+ (run-tracking.db/set-terminal! model active (mapv :id rows) terminal)rows)))(defn reap-orphaned!diff --git a/src/metabase/sample_data/db.clj b/src/metabase/sample_data/db.cljnew file mode 100644index 00000000000..db039163d91--- /dev/null+++ b/src/metabase/sample_data/db.clj@@ -0,0 +1,59 @@+(ns metabase.sample-data.db+ "Application database queries for the sample data module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn sample-database-exists?+ "Whether a sample Database exists."+ []+ (t2/exists? :model/Database :is_sample true))++(defn sample-database+ "The sample Database, or nil."+ []+ (t2/select-one :model/Database :is_sample true))++(defn sample-database-id+ "The id of the sample Database, or nil."+ []+ (t2/select-one-pk :model/Database :is_sample true))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn set-sample-database-details!+ "Set the `details` of the sample Database, returning the ids of the updated rows."+ [details]+ (t2/update-returning-pks! :model/Database :is_sample true {:details details}))++(defn insert-sample-database!+ "Insert the sample Database and return the inserted instance."+ [database-name details engine]+ (t2/insert-returning-instance! :model/Database+ :name database-name+ :details details+ :engine engine+ :is_sample true))++(defn update-database!+ "Apply `changes` to the Database with `database-id`."+ [database-id changes]+ (t2/update! :model/Database database-id changes))++(defn set-database-tables-schema!+ "Set the `schema` of every Table of the Database with `database-id`."+ [database-id schema]+ (t2/update! :model/Table :db_id database-id {:schema schema}))++(defn set-database-table-permissions-schema-name!+ "Set the `schema_name` of the table-level DataPermissions rows of the Database with `database-id`, via a raw table+ update because the model's before-update rejects all updates."+ [database-id schema-name]+ (t2/query {:update (t2/table-name :model/DataPermissions)+ :set {:schema_name schema-name}+ :where [:and+ [:= :db_id database-id]+ [:not= :table_id nil]]}))diff --git a/src/metabase/sample_data/impl.clj b/src/metabase/sample_data/impl.cljindex 4246e5daa6a..e581d514441 100644--- a/src/metabase/sample_data/impl.clj+++ b/src/metabase/sample_data/impl.clj@@ -5,6 +5,7 @@[clojure.string :as str][metabase.driver.util :as driver.u][metabase.plugins.core :as plugins]+ [metabase.sample-data.db :as sample-data.db][metabase.sync.core :as sync][metabase.util.files :as u.files][metabase.util.i18n :refer [trs]]@@ -97,13 +98,9 @@(log/info "Loading sample database")(let [engine (sample-database-engine)details (try-to-extract-sample-database! engine)- db (if (t2/exists? :model/Database :is_sample true)- (t2/select-one :model/Database (first (t2/update-returning-pks! :model/Database :is_sample true {:details details})))- (first (t2/insert-returning-instances! :model/Database- :name sample-database-name- :details details- :engine engine- :is_sample true)))]+ db (if (sample-data.db/sample-database-exists?)+ (sample-data.db/database (first (sample-data.db/set-sample-database-details! details)))+ (sample-data.db/insert-sample-database! sample-database-name details engine))](log/debug "Syncing Sample Database...")(sync/sync-database! db))(log/debug "Finished adding Sample Database.")@@ -113,7 +110,7 @@(defn sample-database-id"ID of the Sample Database if it exists, otherwise nil."[]- (t2/select-one-pk :model/Database :is_sample true))+ (sample-data.db/sample-database-id))(defn- table-schema-for-engine"The schema value the sync process assigns to the sample database's tables for a given engine: H2 puts@@ -152,20 +149,15 @@(let [details (try-to-extract-sample-database! engine)settings (settings-sans-unsupported-features engine old-sample-db)](t2/with-transaction [_conn]- (t2/update! :model/Database (:id old-sample-db)- (cond-> {:engine engine, :details details}- settings (assoc :settings settings)))- (t2/update! :model/Table :db_id (:id old-sample-db) {:schema (table-schema-for-engine engine)})+ (sample-data.db/update-database! (:id old-sample-db)+ (cond-> {:engine engine, :details details}+ settings (assoc :settings settings)))+ (sample-data.db/set-database-tables-schema! (:id old-sample-db) (table-schema-for-engine engine));; Table-level permission rows denormalize the table's schema; keep them matching or schema-scoped- ;; permission checks (e.g. schema visibility in the data picker) stop counting them. Raw table update:- ;; the model's before-update rejects all updates, and delete+reinsert would churn ids for a rename that- ;; doesn't change any permission value.- (t2/query {:update (t2/table-name :model/DataPermissions)- :set {:schema_name (table-schema-for-engine engine)}- :where [:and- [:= :db_id (:id old-sample-db)]- [:not= :table_id nil]]}))- (sync/sync-database! (t2/select-one :model/Database :id (:id old-sample-db)))))+ ;; permission checks (e.g. schema visibility in the data picker) stop counting them. Delete+reinsert would churn+ ;; ids for a rename that doesn't change any permission value.+ (sample-data.db/set-database-table-permissions-schema-name! (:id old-sample-db) (table-schema-for-engine engine)))+ (sync/sync-database! (sample-data.db/database (:id old-sample-db)))))(defn update-sample-database-if-needed!"Reconcile the existing sample database with the bundled one. When the bundled engine changed@@ -173,7 +165,7 @@[[migrate-sample-database-engine-in-place!]]); otherwise we just refresh its connection details in casethe JAR has moved."([]- (update-sample-database-if-needed! (t2/select-one :model/Database :is_sample true)))+ (update-sample-database-if-needed! (sample-data.db/sample-database)))([sample-db](when sample-db@@ -182,4 +174,4 @@(migrate-sample-database-engine-in-place! engine sample-db)(let [intended (try-to-extract-sample-database! engine)](when (not= (:details sample-db) intended)- (t2/update! :model/Database (:id sample-db) {:details intended}))))))))+ (sample-data.db/update-database! (:id sample-db) {:details intended}))))))))diff --git a/src/metabase/sample_data/settings.clj b/src/metabase/sample_data/settings.cljindex c843dffa816..958946b96eb 100644--- a/src/metabase/sample_data/settings.clj+++ b/src/metabase/sample_data/settings.clj@@ -1,12 +1,12 @@(ns metabase.sample-data.settings(:require- [metabase.settings.core :refer [defsetting]]- [toucan2.core :as t2]))+ [metabase.sample-data.db :as sample-data.db]+ [metabase.settings.core :refer [defsetting]]))(defsetting has-sample-database?"Whether this instance has a Sample Database database":type :boolean:visibility :authenticated:setter :none- :getter (fn [] (t2/exists? :model/Database, :is_sample true))+ :getter (fn [] (sample-data.db/sample-database-exists?)):doc false)diff --git a/src/metabase/search/api.clj b/src/metabase/search/api.cljindex 33ef5bf90e1..23013e9ed44 100644--- a/src/metabase/search/api.clj+++ b/src/metabase/search/api.clj@@ -12,6 +12,7 @@[metabase.request.core :as request][metabase.search.config :as search.config][metabase.search.core :as search]+ [metabase.search.db :as search.db][metabase.search.engine :as search.engine][metabase.search.ingestion :as ingestion][metabase.search.settings :as search.settings]@@ -21,8 +22,7 @@[metabase.util.i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [ring.util.response :as response]- [toucan2.core :as t2]))+ [ring.util.response :as response]))(set! *warn-on-reflection* true)@@ -378,7 +378,7 @@expected-result-type expected-result-id))](if (and for-user-id (not= for-user-id api/*current-user-id*));; Build the context and run every permission/visibility check from the target user's perspective.- (do (api/check-404 (t2/exists? :model/User :id for-user-id))+ (do (api/check-404 (search.db/user-exists? for-user-id))(request/with-current-user for-user-id (diagnose)))(diagnose))))diff --git a/src/metabase/search/appdb/core.clj b/src/metabase/search/appdb/core.cljindex da36a5fe47d..7a3301e6ffc 100644--- a/src/metabase/search/appdb/core.clj+++ b/src/metabase/search/appdb/core.clj@@ -11,6 +11,7 @@[metabase.search.appdb.scoring :as search.scoring][metabase.search.appdb.specialization.postgres :as specialization.postgres][metabase.search.config :as search.config]+ [metabase.search.db :as search.db][metabase.search.engine :as search.engine][metabase.search.filter :as search.filter][metabase.search.hierarchy :as search.hierarchy]@@ -25,8 +26,7 @@[metabase.util.i18n :as i18n][metabase.util.json :as json][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2])+ [methodical.core :as methodical])(:import(java.time OffsetDateTime)(java.util Queue)))@@ -157,7 +157,7 @@:forced-init? init-now?:index-state-before index-state:index-state-after @@#'search.index/*indexes*- :index-metadata (t2/select :model/SearchIndexMetadata :engine :appdb)}))))+ :index-metadata (search.db/index-metadata-for-engine :appdb)}))))(tracing/with-span :search "search.appdb.query" {:search/query-length (count search-string)}(try@@ -173,7 +173,7 @@scorers (search.scoring/scorers search-ctx)query (->> (base-filtered-query search-ctx search-string [:legacy_input])(search.scoring/with-scores search-ctx scorers))]- (->> (t2/query query)+ (->> (search.db/rows query)(map (partial rehydrate weights (keys scorers)))))(catch Exception e;; Rule out the error coming from stale index metadata.@@ -197,7 +197,7 @@:search_index.model:search_index.source_type)))(search.filter/with-filters search-ctx)- t2/query+ search.db/rows(into #{} (map :model)))))(defn- restrict-to-row [model id qry]@@ -209,7 +209,7 @@(-> qry(assoc :select [[[:inline 1] :one]] :limit 1)(dissoc :order-by)- t2/query+ search.db/rowsseqboolean))@@ -231,7 +231,7 @@(let [active (search.index/active-table)](if (nil? active){:type :missing-from-index :details {:reason :no-active-index}}- (let [index-row (t2/select-one active :model model :model_id (str id))]+ (let [index-row (search.db/index-row active model (str id))](cond(nil? index-row){:type :missing-from-index :details {:active-table active}}@@ -284,7 +284,7 @@(if in-place?(when-let [table (search.index/active-table)];; keep the current table, just delete its contents- (t2/delete! table))+ (search.db/delete-all-rows! table))(search.index/maybe-create-pending!))(u/prog1 (populate-index! (if in-place? :search/updating :search/reindexing))(search.index/activate-table!))diff --git a/src/metabase/search/appdb/index.clj b/src/metabase/search/appdb/index.cljindex d9e742fac3d..b6b08abc551 100644--- a/src/metabase/search/appdb/index.clj+++ b/src/metabase/search/appdb/index.clj@@ -10,6 +10,7 @@[metabase.search.appdb.specialization.h2 :as h2][metabase.search.appdb.specialization.postgres :as postgres][metabase.search.config :as search.config]+ [metabase.search.db :as search.db][metabase.search.engine :as search.engine][metabase.search.ingestion :as search.ingestion][metabase.search.models.search-index-metadata :as search-index-metadata]@@ -108,31 +109,16 @@briefly stale relative to what has been dropped)."[table](when table- (t2/exists? :information_schema.tables :table_name (table-name table))))+ (search.db/table-exists? (table-name table))))(defn- drop-table! [table](boolean(when table- (t2/query (sql.helpers/drop-table :if-exists (keyword (table-name table)))))))+ (search.db/execute! (sql.helpers/drop-table :if-exists (keyword (table-name table)))))))(defn- orphan-indexes [](map (comp keyword u/lower-case-en :table_name)- (t2/query {:select [:ist.table_name]- :from [[:information_schema.tables :ist]]- :where [:and- [:= :ist.table_schema :%current_schema]- [:or- [:like [:lower :ist.table_name] "search\\_index\\_\\_%"]- ;; legacy table names- [:in [:lower :ist.table_name]- ["search_index" "search_index_next" "search_index_retired"]]]- ;; Exclude temp tables — they are managed by with-temp-index-table- [:not-like [:lower :ist.table_name] "%\\_temp"]- [:not [:exists ^:allow-subquery {:select [1]- :from [[(t2/table-name :model/SearchIndexMetadata) :sim]]- :where [:and- [:= :sim.engine "appdb"]- [:= [:lower :sim.index_name] [:lower :ist.table_name]]]}]]]})))+ (search.db/orphan-index-table-names)))(defn- delete-obsolete-tables! [];; Delete metadata around indexes that are no longer needed.@@ -141,7 +127,7 @@(let [dropped (volatile! [])](doseq [table (orphan-indexes)](try- (t2/query (sql.helpers/drop-table table))+ (search.db/execute! (sql.helpers/drop-table table))(vswap! dropped conj table);; Deletion could fail if it races with other instances(catch Exception e@@ -194,10 +180,10 @@(t2/with-transaction [_ (mdb/app-db)](-> (sql.helpers/create-table table-name)(sql.helpers/with-columns (specialization/table-schema base-schema))- t2/query)+ search.db/execute!)(let [table-name (name table-name)](doseq [stmt (specialization/post-create-statements table-name table-name)]- (t2/query stmt)))))+ (search.db/execute! stmt)))))(defn maybe-create-pending!"Create a search index table if one doesn't exist. Record and return the name of the table, regardless."@@ -222,7 +208,7 @@(log/errorf "Error creating pending index table, cleaning up metadata: %s" (ex-message e))(try(t2/with-connection [safe-conn (mdb/app-db)]- (t2/delete! :conn safe-conn :model/SearchIndexMetadata :index_name (name table-name)))+ (search.db/delete-index-metadata-by-name-on-conn! safe-conn (name table-name)))(catch Exception del-e(log/warnf "Error clearing out search metadata after failure: %s" (ex-message del-e))))(sync-tracking-atoms!))))@@ -389,7 +375,7 @@(when updated(u/prog1 (->> entries (map :model) frequencies)(when reindexing?- (t2/query ["commit"]))+ (search.db/commit!))(log/trace "indexed documents for " <>)))))](if reindexing?;; New connection used for performing the updates which commit periodically without impacting any outer transactions.@@ -424,7 +410,7 @@(when table-name;; The table can disappear after we read its name, especially during tests.{search-model (try (isolate-write!- #(t2/delete! table-name :model search-model :model_id [:in (set ids)]))+ #(search.db/delete-index-rows! table-name search-model (set ids)))(catch Exception e (if (table-not-found-exception? e) 0 (throw e))))})))(apply merge-with +)(into {}))))@@ -432,13 +418,7 @@(defn when-index-created"Return creation time of the active index, or nil if there is none."[]- (t2/select-one-fn :created_at- :model/SearchIndexMetadata- :engine :appdb- :version (search.spec/index-version-hash)- :lang_code (i18n/site-locale-string)- :status :active- {:order-by [[:created_at :desc]]}))+ (search.db/active-index-created-at (search.spec/index-version-hash) (i18n/site-locale-string)))(defn search-query"Query fragment for all models corresponding to a query parameter `:search-term`."@@ -452,7 +432,7 @@"Use the index table to search for records."[search-term & [search-ctx]](map (juxt :model :name)- (t2/query (search-query search-term search-ctx [:model :name]))))+ (search.db/rows (search-query search-term search-ctx [:model :name]))))(defn reset-index!"Ensure we have a blank slate; in case the table schema or stored data format has changed."@@ -497,13 +477,13 @@(binding [*mocking-tables* true*indexes* (atom {:active table-name#})](try- (t2/insert! :model/SearchIndexMetadata {:engine :appdb- :version version#- :lang_code (i18n/site-locale-string)- :status :pending- :index_name (name table-name#)})+ (search.db/insert-index-metadata! {:engine :appdb+ :version version#+ :lang_code (i18n/site-locale-string)+ :status :pending+ :index_name (name table-name#)})(create-table! table-name#)~@body(finally(#'drop-table! table-name#)- (t2/delete! :model/SearchIndexMetadata :version version#)))))))+ (search.db/delete-index-metadata-by-version! version#)))))))diff --git a/src/metabase/search/appdb/scoring.clj b/src/metabase/search/appdb/scoring.cljindex 712d6529c51..cf64abaf7b1 100644--- a/src/metabase/search/appdb/scoring.clj+++ b/src/metabase/search/appdb/scoring.clj@@ -7,9 +7,9 @@[metabase.search.appdb.index :as search.index][metabase.search.appdb.specialization.api :as specialization][metabase.search.config :as search.config]+ [metabase.search.db :as search.db][metabase.search.scoring :as search.scoring]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(defn all-scores"Score stats for each scorer"@@ -18,9 +18,9 @@(defn- view-count-percentiles*[p-value]- (into {} (for [{:keys [model vcp]} (t2/query (specialization/view-count-percentile-query- (search.index/active-table)- p-value))]+ (into {} (for [{:keys [model vcp]} (search.db/rows (specialization/view-count-percentile-query+ (search.index/active-table)+ p-value))][(keyword model) vcp])))(def ^{:private truediff --git a/src/metabase/search/appdb/specialization/h2.clj b/src/metabase/search/appdb/specialization/h2.cljindex 204bd3d4044..f560ac18430 100644--- a/src/metabase/search/appdb/specialization/h2.clj+++ b/src/metabase/search/appdb/specialization/h2.clj@@ -4,9 +4,9 @@[clojure.string :as str][honey.sql.helpers :as sql.helpers][metabase.search.appdb.specialization.api :as specialization]+ [metabase.search.db :as search.db][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x]- [toucan2.core :as t2]))+ [metabase.util.honey-sql-2 :as h2x]))(defmethod specialization/table-schema :h2 [base-schema](into [[:id :bigint :auto-increment :primary-key]@@ -28,8 +28,8 @@(when (seq entries)(doseq [[model model-entries] (group-by :model entries)](let [ids (map (comp str :model_id) model-entries)]- (t2/delete! table :model model :model_id [:in ids])))- (t2/insert! table entries))))+ (search.db/delete-index-rows! table model ids)))+ (search.db/insert-rows! table entries))))(defn- wildcard-tokens [search-term](->> (str/split search-term #"\s+")@@ -65,4 +65,4 @@(defmethod specialization/index-size-estimate :h2[table-name]- (t2/count table-name))+ (search.db/index-entry-count table-name))diff --git a/src/metabase/search/appdb/specialization/postgres.clj b/src/metabase/search/appdb/specialization/postgres.cljindex fee83b8344c..71abfdc83ac 100644--- a/src/metabase/search/appdb/specialization/postgres.clj+++ b/src/metabase/search/appdb/specialization/postgres.clj@@ -2,9 +2,9 @@(:require[clojure.string :as str][metabase.search.appdb.specialization.api :as specialization]+ [metabase.search.db :as search.db][metabase.search.util :as search.util]- [metabase.util.honey-sql-2 :as h2x]- [toucan2.core :as t2]))+ [metabase.util.honey-sql-2 :as h2x]))(defmethod specialization/table-schema :postgres [base-schema](into [[:id :bigint [:primary-key] ^:allow-raw-sql [:raw "GENERATED BY DEFAULT AS IDENTITY"]]@@ -26,7 +26,7 @@(defmethod specialization/batch-upsert! :postgres [table entries](when (seq entries)- (t2/query+ (search.db/execute!;; The cost of dynamically calculating these keys should be small compared to the IO cost, so unoptimized. Note;; that the entries are not guaranteed to be homogeneous - some may be missing nullable columns. So we need to;; get the keys from *all* the entries.@@ -103,15 +103,13 @@(defmethod specialization/analyze-table! :postgres[table-name]- (t2/query (str "ANALYZE " (name table-name))))+ (search.db/execute! (str "ANALYZE " (name table-name))))(defmethod specialization/index-size-estimate :postgres[table-name];; Use the planner's row estimate (pg_class.reltuples) instead of a full count(*). reltuples/relpages are;; only populated by ANALYZE/VACUUM, so right after a rebuild the estimate may be stale — return nil in;; that window and let the caller skip the metric rather than doing a full table scan.- (let [{:keys [reltuples relpages]} (t2/query-one {:select [:reltuples :relpages]- :from [:pg_class]- :where [:= :oid [:to_regclass (name table-name)]]})]+ (let [{:keys [reltuples relpages]} (search.db/pg-class-estimate (name table-name))](when (and relpages (pos? relpages) reltuples (nat-int? (long reltuples)))(long reltuples))))diff --git a/src/metabase/search/db.clj b/src/metabase/search/db.cljnew file mode 100644index 00000000000..cb0c9ae6289--- /dev/null+++ b/src/metabase/search/db.clj@@ -0,0 +1,220 @@+(ns metabase.search.db+ "Application database queries for the search module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (connection and transaction handling still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn rows+ "The rows returned by the Honey SQL or raw SQL `query`."+ [query]+ (t2/query query))++(defn execute!+ "Run the Honey SQL or raw SQL `statement`."+ [statement]+ (t2/query statement))++(defn commit!+ "Commit the current transaction."+ []+ (t2/query ["commit"]))++(defn user-exists?+ "Whether a User with `user-id` exists."+ [user-id]+ (t2/exists? :model/User :id user-id))++(defn entity-exists?+ "Whether a `model` row with `id` exists."+ [model id]+ (t2/exists? model :id id))++(defn any-card+ "Some Card, or nil."+ []+ (t2/select-one :model/Card))++(defn index-metadata-for-engine+ "The SearchIndexMetadata rows of `engine`."+ [engine]+ (t2/select :model/SearchIndexMetadata :engine engine))++(defn index-row+ "The row of the search index `table` for `model` and `model-id`, or nil."+ [table model model-id]+ (t2/select-one table :model model :model_id model-id))++(defn delete-all-rows!+ "Delete every row of the search index `table`."+ [table]+ (t2/delete! table))++(defn delete-index-rows!+ "Delete the rows of the search index `table` for `model` and `model-ids`."+ [table model model-ids]+ (t2/delete! table :model model :model_id [:in model-ids]))++(defn insert-rows!+ "Insert `entries` into the search index `table`."+ [table entries]+ (t2/insert! table entries))++(defn index-entry-count+ "The number of entries in the search index table `index-table`."+ [index-table]+ (t2/count index-table))++(defn table-exists?+ "Whether a table named `table-name` exists in the app DB."+ [table-name]+ (t2/exists? :information_schema.tables :table_name table-name))++(defn orphan-index-table-names+ "The `:table_name`s of search index tables in the current schema with no SearchIndexMetadata."+ []+ (t2/query {:select [:ist.table_name]+ :from [[:information_schema.tables :ist]]+ :where [:and+ [:= :ist.table_schema :%current_schema]+ [:or+ [:like [:lower :ist.table_name] "search\\_index\\_\\_%"]+ ;; legacy table names+ [:in [:lower :ist.table_name]+ ["search_index" "search_index_next" "search_index_retired"]]]+ ;; Exclude temp tables — they are managed by with-temp-index-table+ [:not-like [:lower :ist.table_name] "%\\_temp"]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[(t2/table-name :model/SearchIndexMetadata) :sim]]+ :where [:and+ [:= :sim.engine "appdb"]+ [:= [:lower :sim.index_name] [:lower :ist.table_name]]]}]]]}))++(defn pg-class-estimate+ "The planner's `:reltuples` and `:relpages` estimate for `table-name` (Postgres only), or nil."+ [table-name]+ (t2/query-one {:select [:reltuples :relpages]+ :from [:pg_class]+ :where [:= :oid [:to_regclass table-name]]}))++(defn pg-text-search-configs+ "The `:cfgname`s of the Postgres text search configurations."+ []+ (t2/query {:select [:cfgname]+ :from [:pg_ts_config]}))++(defn active-index-created-at+ "When the active `appdb` search index for `version` and `lang-code` was created, or nil."+ [version lang-code]+ (t2/select-one-fn :created_at+ :model/SearchIndexMetadata+ :engine :appdb+ :version version+ :lang_code lang-code+ :status :active+ {:order-by [[:created_at :desc]]}))++(defn insert-index-metadata!+ "Insert the SearchIndexMetadata `row`."+ [row]+ (t2/insert! :model/SearchIndexMetadata row))++(defn delete-index-metadata-by-version!+ "Delete the SearchIndexMetadata rows of `version`."+ [version]+ (t2/delete! :model/SearchIndexMetadata :version version))++(defn delete-index-metadata-by-name-on-conn!+ "Delete the SearchIndexMetadata rows named `index-name`, on `conn`."+ [conn index-name]+ (t2/delete! :conn conn :model/SearchIndexMetadata :index_name index-name))++(defn delete-index-metadata!+ "Delete the SearchIndexMetadata row of `engine`, `version`, `lang-code`, and `index-name`."+ [engine version lang-code index-name]+ (t2/delete! :model/SearchIndexMetadata :engine engine :version version :lang_code lang-code :index_name index-name))++(defn index-metadata+ "The name, status, and creation time of the active and pending SearchIndexMetadata rows of `engine`, `version`, and+ `lang-code`."+ [engine version lang-code]+ (t2/select [:model/SearchIndexMetadata :index_name :status :created_at]+ :engine engine+ :version version+ :lang_code lang-code+ :status [:in [:active :pending]]))++(defn delete-expired-pending-index-metadata!+ "Delete the pending SearchIndexMetadata rows of `lang-code` created before `created-before`."+ [lang-code created-before]+ (t2/delete! :model/SearchIndexMetadata+ {:where [:and+ [:= :lang_code lang-code]+ [:= :status "pending"]+ [:< :created_at created-before]]}))++(defn pending-index-metadata-exists?+ "Whether a pending SearchIndexMetadata row of `engine`, `version`, and `lang-code` exists."+ [engine version lang-code]+ (t2/exists? :model/SearchIndexMetadata :engine engine :version version :lang_code lang-code :status :pending))++(defn delete-retired-index-metadata!+ "Delete the retired SearchIndexMetadata rows of `engine`, `version`, and `lang-code`."+ [engine version lang-code]+ (t2/delete! :model/SearchIndexMetadata :engine engine :version version :lang_code lang-code :status :retired))++(defn retire-active-index-metadata!+ "Retire the active SearchIndexMetadata rows of `engine`, `version`, and `lang-code`."+ [engine version lang-code]+ (t2/update! :model/SearchIndexMetadata {:engine engine :version version :lang_code lang-code :status :active} {:status :retired}))++(defn activate-pending-index-metadata!+ "Activate the pending SearchIndexMetadata rows of `engine`, `version`, and `lang-code`."+ [engine version lang-code]+ (t2/update! :model/SearchIndexMetadata {:engine engine :version version :lang_code lang-code :status :pending} {:status :active}))++(defn active-index-name+ "The name of the active SearchIndexMetadata row of `engine`, `version`, and `lang-code`, or nil."+ [engine version lang-code]+ (t2/select-one-fn :index_name :model/SearchIndexMetadata :engine engine :version version :lang_code lang-code :status :active))++(defn recent-index-versions+ "The `:version`s of the `limit` most recently updated SearchIndexMetadata versions."+ [limit]+ (t2/query {:select [:version]+ :from [(t2/table-name :model/SearchIndexMetadata)]+ :group-by [:version]+ ;; use pk as a tie-breaker+ :order-by [[[:max :updated_at] :desc]+ [[:max :id] :desc]]+ :limit limit}))++(defn delete-obsolete-index-metadata!+ "Delete the SearchIndexMetadata rows whose version is not in `recent-versions`, or not in `keep-versions` and last+ updated before `updated-before`."+ [recent-versions keep-versions updated-before]+ (t2/query-one {:delete-from [(t2/table-name :model/SearchIndexMetadata)]+ :where [:or+ [:not-in :version recent-versions]+ [:and+ [:not-in :version keep-versions]+ [:< :updated_at updated-before]]]}))++(defn personal-collection-root-id+ "The id of the root personal Collection of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one-pk :model/Collection :personal_owner_id [:= user-id] :location "/"))++(defn non-destination-database-ids+ "The ids of the Databases that are not routing destinations, or nil."+ []+ (t2/select-pks-set :model/Database :router_database_id nil))++(defn user-common-names+ "A map of User id to common name for the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn :common_name [:model/User :id :first_name :last_name :email] :id [:in user-ids]))++(defn card-result-metadata+ "A map of Card id to result metadata for the Cards with `card-ids`."+ [card-ids]+ (t2/select-pk->fn :result_metadata [:model/Card :id :card_schema :result_metadata] :id [:in card-ids]))diff --git a/src/metabase/search/filter.clj b/src/metabase/search/filter.cljindex f36f0645d1f..9c3a7eb66cb 100644--- a/src/metabase/search/filter.clj+++ b/src/metabase/search/filter.clj@@ -6,12 +6,12 @@[metabase.premium-features.core :as premium-features][metabase.query-processor.parameters.dates :as qp.parameters.dates][metabase.search.config :as search.config]+ [metabase.search.db :as search.db][metabase.search.permissions :as search.permissions][metabase.search.spec :as search.spec][metabase.util.date-2 :as u.date][metabase.util.honey-sql-2 :as h2x]- [metabase.util.i18n :refer [tru]]- [toucan2.core :as t2])+ [metabase.util.i18n :refer [tru]])(:import(java.time LocalDate)))@@ -132,9 +132,7 @@"only-mine"[:or[:= :collection.personal_owner_id current-user-id]- [:like :collection.location (format "/%d/%%" (t2/select-one-pk :model/Collection- :personal_owner_id [:= current-user-id]- :location "/"))]]+ [:like :collection.location (format "/%d/%%" (search.db/personal-collection-root-id current-user-id))]]"exclude-others"(let [with-filter #(personal-collections-where-clausediff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.cljindex 46f4b4da93b..455149a23dd 100644--- a/src/metabase/search/impl.clj+++ b/src/metabase/search/impl.clj@@ -7,6 +7,7 @@[metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features][metabase.search.config :as search.config :refer [SearchableModel SearchContext]]+ [metabase.search.db :as search.db][metabase.search.engine :as search.engine][metabase.search.filter :as search.filter][metabase.search.in-place.filter :as search.in-place.filter]@@ -124,7 +125,7 @@[search-ctx](when (and (not (:is-superuser? search-ctx))(some #{"table" "indexed-entity"} (:models search-ctx)))- (perms/prime-table-perms-cache {:db-ids (t2/select-pks-set :model/Database :router_database_id nil)})))+ (perms/prime-table-perms-cache {:db-ids (search.db/non-destination-database-ids)})))(defn- hydrate-user-metadata"Hydrate common-name for last_edited_by and created_by for each result."@@ -132,7 +133,7 @@(let [user-ids (set (flatten (for [result results](remove nil? ((juxt :last_editor_id :creator_id) result)))))user-id->common-name (if (pos? (count user-ids))- (t2/select-pk->fn :common_name [:model/User :id :first_name :last_name :email] :id [:in user-ids])+ (search.db/user-common-names user-ids){})](mapv (fn [{:keys [creator_id last_editor_id] :as result}](assoc result@@ -147,11 +148,9 @@(cond-> result(= (:model result) "dataset")(assoc :collection_effective_ancestors- (->> (t2/hydrate- (if (nil? (:collection_id result))- collection/root-collection- {:location (:collection_location result)})- :effective_ancestors)+ (->> (t2/hydrate (if (nil? (:collection_id result))+ collection/root-collection+ {:location (:collection_location result)}) :effective_ancestors):effective_ancestors;; two pieces for backwards compatibility:;; - remove the root collection@@ -462,7 +461,7 @@search-results)card-metadata (if (empty? card-ids){}- (t2/select-pk->fn :result_metadata [:model/Card :id :card_schema :result_metadata] :id [:in card-ids]))]+ (search.db/card-result-metadata card-ids))](map (fn [{:keys [model id] :as item}](if (contains? #{"card" "metric" "dataset"} model)(assoc item :result_metadata (card-metadata id))diff --git a/src/metabase/search/ingestion.clj b/src/metabase/search/ingestion.cljindex c2910acc309..308e7e42f44 100644--- a/src/metabase/search/ingestion.clj+++ b/src/metabase/search/ingestion.clj@@ -7,6 +7,7 @@[metabase.app-db.core :as mdb][metabase.collections.curation :as collections.curation][metabase.lib-be.core :as lib-be]+ [metabase.search.db :as search.db][metabase.search.engine :as search.engine][metabase.search.spec :as search.spec][metabase.tracing.core :as tracing]@@ -223,12 +224,12 @@(let [spec (search.spec/spec search-model)indexed? (-> (spec-index-query-where search-model [:= :this.id id])(assoc :select [[[:inline 1] :one]] :limit 1)- t2/query+ search.db/rowsseqboolean)](condindexed? :indexable- (t2/exists? (:model spec) :id id) :excluded+ (search.db/entity-exists? (:model spec) id) :excluded:else :not-found))))(def ^:private max-document-error-logs 10)@@ -275,7 +276,7 @@(->> (for [model search.spec/search-models](-> (spec-index-query-where model nil)(assoc :select [[:%count.* :count]])- t2/query+ search.db/rowsfirst:count))(filter some?)diff --git a/src/metabase/search/models/search_index_metadata.clj b/src/metabase/search/models/search_index_metadata.cljindex 5bc3c1de078..9d9993291ed 100644--- a/src/metabase/search/models/search_index_metadata.clj+++ b/src/metabase/search/models/search_index_metadata.clj@@ -2,6 +2,7 @@(:require[java-time.api :as t][metabase.models.interface :as mi]+ [metabase.search.db :as search.db][metabase.util :as u][metabase.util.i18n :as i18n][metabase.util.log :as log]@@ -26,11 +27,7 @@"The current 'pending' and 'active' indexes for the given coordinates, where they exist."[engine version](let [pending-cut-off (t/minus (t/offset-date-time) pending-table-cut-off)]- (->> (t2/select [:model/SearchIndexMetadata :index_name :status :created_at]- :engine engine- :version version- :lang_code (i18n/site-locale-string)- :status [:in [:active :pending]])+ (->> (search.db/index-metadata engine version (i18n/site-locale-string))(filter (fn [{:keys [status created_at]}](or (not= status :pending)(t/before? pending-cut-off created_at))))@@ -40,23 +37,15 @@"Create a 'pending' entry, unless one already exists. Return whether it was created."[engine version index-name];; Clear out any expired records- (t2/delete! :model/SearchIndexMetadata- {:where [:and- [:= :lang_code (i18n/site-locale-string)]- [:= :status "pending"]- [:< :created_at (t/minus (t/offset-date-time) pending-table-cut-off)]]})+ (search.db/delete-expired-pending-index-metadata! (i18n/site-locale-string) (t/minus (t/offset-date-time) pending-table-cut-off))(boolean- (when-not (t2/exists? :model/SearchIndexMetadata- :engine engine- :version version- :lang_code (i18n/site-locale-string)- :status :pending)+ (when-not (search.db/pending-index-metadata-exists? engine version (i18n/site-locale-string))(try- (t2/insert! :model/SearchIndexMetadata {:engine engine- :version version- :lang_code (i18n/site-locale-string)- :status :pending- :index_name (name index-name)})+ (search.db/insert-index-metadata! {:engine engine+ :version version+ :lang_code (i18n/site-locale-string)+ :status :pending+ :index_name (name index-name)})(log/infof "Inserted new pending table %s" index-name)true(catch Exception _@@ -66,34 +55,25 @@(defn delete-index!"Delete the given pending index, as long as its still pending."[engine version index-name]- (t2/delete! :model/SearchIndexMetadata :engine engine :version version :lang_code (i18n/site-locale-string) :index_name (name index-name)))+ (search.db/delete-index-metadata! engine version (i18n/site-locale-string) (name index-name)))(defn active-pending!"If there is 'pending' index, make it 'active'. Return the name of the active index, regardless."[engine version](t2/with-transaction [_conn]- (when (t2/exists? :model/SearchIndexMetadata :engine engine :version version :lang_code (i18n/site-locale-string) :status :pending)- (t2/delete! :model/SearchIndexMetadata :engine engine :version version :lang_code (i18n/site-locale-string) :status :retired)- (t2/update! :model/SearchIndexMetadata {:engine engine :version version :lang_code (i18n/site-locale-string) :status :active} {:status :retired})- (t2/update! :model/SearchIndexMetadata {:engine engine :version version :lang_code (i18n/site-locale-string) :status :pending} {:status :active}))- (t2/select-one-fn :index_name :model/SearchIndexMetadata :engine engine :version version :lang_code (i18n/site-locale-string) :status :active)))+ (when (search.db/pending-index-metadata-exists? engine version (i18n/site-locale-string))+ (search.db/delete-retired-index-metadata! engine version (i18n/site-locale-string))+ (search.db/retire-active-index-metadata! engine version (i18n/site-locale-string))+ (search.db/activate-pending-index-metadata! engine version (i18n/site-locale-string)))+ (search.db/active-index-name engine version (i18n/site-locale-string))))(defn delete-obsolete!"Remove metadata corresponding to obsolete Metabase versions.It is up to the relevant engine to delete the actual indexes themselves."[our-version];; If there are no recent versions, then there is nothing to delete.- (when-let [most-recent (seq (map :version (t2/query {:select [:version]- :from [(t2/table-name :model/SearchIndexMetadata)]- :group-by [:version]- ;; use pk as a tie-breaker- :order-by [[[:max :updated_at] :desc]- [[:max :id] :desc]]- :limit 3})))]- (t2/query-one {:delete-from [(t2/table-name :model/SearchIndexMetadata)]- :where [:or- [:not-in :version most-recent]- ;; Drop those older than 1 day, unless we are using them, or they are the most recent.- [:and- [:not-in :version (filter some? [our-version (first most-recent)])]- [:< :updated_at (t/minus (t/zoned-date-time) pending-table-cut-off)]]]})))+ (when-let [most-recent (seq (map :version (search.db/recent-index-versions 3)))]+ ;; Drop those older than 1 day, unless we are using them, or they are the most recent.+ (search.db/delete-obsolete-index-metadata! most-recent+ (filter some? [our-version (first most-recent)])+ (t/minus (t/zoned-date-time) pending-table-cut-off))))diff --git a/src/metabase/search/spec.clj b/src/metabase/search/spec.cljindex cf6aadad63d..351decf3fef 100644--- a/src/metabase/search/spec.clj+++ b/src/metabase/search/spec.clj@@ -9,6 +9,7 @@[malli.error :as me][metabase.config.core :as config][metabase.search.config :as search.config]+ [metabase.search.db :as search.db][metabase.util :as u][metabase.util.json :as json][metabase.util.malli.registry :as mr]@@ -477,7 +478,7 @@(doseq [d (keys (model-hooks))](derive d :hook/search-index))- (search-models-to-update (t2/select-one :model/Card))+ (search-models-to-update (search.db/any-card))(methods spec)(model-hooks)diff --git a/src/metabase/search/util.clj b/src/metabase/search/util.cljindex 03f32578ef6..baf64cf1bf2 100644--- a/src/metabase/search/util.clj+++ b/src/metabase/search/util.clj@@ -2,12 +2,12 @@(:require[clojure.string :as str][metabase.app-db.core :as mdb]+ [metabase.search.db :as search.db][metabase.search.ingestion :as search.ingestion][metabase.search.settings :as search.settings][metabase.util :as u][metabase.util.i18n :as i18n]- [metabase.util.string :as u.str]- [toucan2.core :as t2]))+ [metabase.util.string :as u.str]))(defn impossible-condition?"An (incomplete) check where queries will definitely return nothing, to help avoid spurious index update queries."@@ -78,8 +78,7 @@:es :spanish:sv :swedish:tr :turkish}- available-languages (->> (t2/query {:select [:cfgname]- :from [:pg_ts_config]})+ available-languages (->> (search.db/pg-text-search-configs)(map :cfgname)(map keyword)set)]diff --git a/src/metabase/secrets/db.clj b/src/metabase/secrets/db.cljnew file mode 100644index 00000000000..422c85bdd0b--- /dev/null+++ b/src/metabase/secrets/db.clj@@ -0,0 +1,25 @@+(ns metabase.secrets.db+ "Application database queries for the secrets module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn latest-secret+ "The highest-version Secret with `id`, or nil."+ [id]+ (t2/select-one :model/Secret :id id {:order-by [[:version :desc]]}))++(defn insert-secret!+ "Insert the Secret `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Secret row))++(defn secret-version+ "The Secret with `id` and `version`, or nil."+ [id version]+ (t2/select-one :model/Secret :id id :version version))++(defn delete-secret!+ "Delete every version of the Secret with `id`."+ [id]+ (t2/delete! :model/Secret :id id))diff --git a/src/metabase/secrets/models/secret.clj b/src/metabase/secrets/models/secret.cljindex c134550e6de..480256eee97 100644--- a/src/metabase/secrets/models/secret.clj+++ b/src/metabase/secrets/models/secret.clj@@ -10,6 +10,7 @@[metabase.driver.util :as driver.u][metabase.models.interface :as mi][metabase.premium-features.core :as premium-features]+ [metabase.secrets.db :as secrets.db][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.log :as log]@@ -46,7 +47,7 @@"Returns the latest Secret instance for the given `id` (meaning the one with the highest `version`)."{:added "0.42.0"}[id]- (t2/select-one :model/Secret :id id {:order-by [[:version :desc]]}))+ (secrets.db/latest-secret id))(defn upsert-secret-value!"Inserts a new secret value, or updates an existing one, for the given parameters.@@ -55,18 +56,18 @@{:added "0.42.0"}[existing-id nm kind src value](let [insert-new (fn [id v]- (let [inserted (first (t2/insert-returning-instances! :model/Secret (cond-> {:version v- :name nm- :kind kind- :source src- :value value- :creator_id api/*current-user-id*}- id- (assoc :id id))))]+ (let [inserted (secrets.db/insert-secret! (cond-> {:version v+ :name nm+ :kind kind+ :source src+ :value value+ :creator_id api/*current-user-id*}+ id+ (assoc :id id)))];; Toucan doesn't support composite primary keys, so adding a new record with incremented;; version for an existing ID won't return a result from t2/insert!, hence we may need to;; manually select it here- (t2/select-one :model/Secret :id (or id (u/the-id inserted)) :version v)))+ (secrets.db/secret-version (or id (u/the-id inserted)) v)))latest-version (when existing-id (latest-for-id existing-id))](if latest-version(insert-new (u/the-id latest-version) (inc (:version latest-version)))@@ -292,7 +293,7 @@#{}possible-secret-prop-names)](log/infof "Deleting secret ID %s from app DB because the owning database (%s) is being deleted" secret-id id)- (t2/delete! :model/Secret :id secret-id))))+ (secrets.db/delete-secret! secret-id))))(defn- hydrate-redacted-secret[db-details conn-prop-nm _conn-prop]@@ -386,7 +387,7 @@(:value secret))](assoc cleared-details id-kw id))(do- (t2/delete! :model/Secret :id secret-id)+ (secrets.db/delete-secret! secret-id)(dissoc cleared-details id-kw)));; Don't throw out a secret even if the client didn't send it back(m/assoc-some cleared-details id-kw secret-id)))))]diff --git a/src/metabase/segments/api.clj b/src/metabase/segments/api.cljindex bb458e601fd..c3d0f0f3f38 100644--- a/src/metabase/segments/api.clj+++ b/src/metabase/segments/api.clj@@ -8,6 +8,7 @@[metabase.lib.core :as lib][metabase.models.interface :as mi][metabase.permissions.core :as perms]+ [metabase.segments.db :as segments.db][metabase.segments.schema :as segments.schema][metabase.util :as u][metabase.util.i18n :refer [tru]]@@ -47,17 +48,12 @@(let [table-id (definition-table-id definition)](api/create-check :model/Segment (assoc body :table_id table-id))(let [segment (api/check-500- (first (t2/insert-returning-instances! :model/Segment- :table_id table-id- :creator_id api/*current-user-id*- :name name- :description description- :definition definition)))]+ (segments.db/insert-segment! table-id api/*current-user-id* name description definition))](events/publish-event! :event/segment-create {:object segment :user-id api/*current-user-id*})(t2/hydrate segment :creator))))(mu/defn- hydrated-segment [id :- ms/PositiveInt]- (-> (api/read-check (t2/select-one :model/Segment :id id))+ (-> (api/read-check (segments.db/segment id))(t2/hydrate :creator)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -77,12 +73,10 @@(api.macros/defendpoint :get "/""Fetch *all* `Segments`."[]- (let [segments (t2/select :model/Segment- :archived false- {:order-by [[:%lower.name :asc]]})+ (let [segments (segments.db/unarchived-segments)table-ids (into #{} (keep :table_id) segments)](perms/prime-table-perms-cache {:db-ids (when (seq table-ids)- (t2/select-fn-set :db_id :model/Table :id [:in table-ids]))+ (segments.db/table-database-ids table-ids)):table-ids table-ids})(-> (filterv mi/can-read? segments)(t2/hydrate :creator :definition_description))))@@ -106,7 +100,7 @@(when (not= new-table-id (:table_id existing))(api/create-check :model/Segment {:table_id new-table-id}))))(when changes- (t2/update! :model/Segment id changes))+ (segments.db/update-segment! id changes))(u/prog1 (hydrated-segment id)(events/publish-event! :event/segment-update{:object <> :user-id api/*current-user-id* :revision-message revision_message}))))@@ -157,4 +151,4 @@"Return related entities."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (-> (t2/select-one :model/Segment :id id) api/read-check xrays/related))+ (-> (segments.db/segment id) api/read-check xrays/related))diff --git a/src/metabase/segments/db.clj b/src/metabase/segments/db.cljnew file mode 100644index 00000000000..86bc2f07d31--- /dev/null+++ b/src/metabase/segments/db.clj@@ -0,0 +1,55 @@+(ns metabase.segments.db+ "Application database queries for the segments module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn insert-segment!+ "Insert a Segment and return the inserted instance."+ [table-id creator-id segment-name description definition]+ (t2/insert-returning-instance! :model/Segment+ :table_id table-id+ :creator_id creator-id+ :name segment-name+ :description description+ :definition definition))++(defn segment+ "The Segment with `id`, or nil."+ [id]+ (t2/select-one :model/Segment :id id))++(defn unarchived-segments+ "The unarchived Segments, in case-insensitive name order."+ []+ (t2/select :model/Segment :archived false {:order-by [[:%lower.name :asc]]}))++(defn table-database-ids+ "The set of Database ids of the Tables with `table-ids`."+ [table-ids]+ (t2/select-fn-set :db_id :model/Table :id [:in table-ids]))++(defn update-segment!+ "Apply `changes` to the Segment with `id`."+ [id changes]+ (t2/update! :model/Segment id changes))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn table-database-id+ "The Database id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id :model/Table :id table-id))++(defn table-perms-columns+ "The Database id, schema, and id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one [:model/Table :db_id :schema :id] :id table-id))++(defn collections+ "The Collections with `collection-ids`."+ [collection-ids]+ (t2/select :model/Collection :id [:in collection-ids]))diff --git a/src/metabase/segments/models/segment.clj b/src/metabase/segments/models/segment.cljindex 29ac062c55b..1df0a5b9faf 100644--- a/src/metabase/segments/models/segment.clj+++ b/src/metabase/segments/models/segment.clj@@ -13,6 +13,7 @@[metabase.permissions.core :as perms][metabase.remote-sync.core :as remote-sync][metabase.search.core :as search]+ [metabase.segments.db :as segments.db][metabase.segments.schema :as segments.schema][metabase.util :as u][metabase.util.i18n :refer [tru]]@@ -81,8 +82,8 @@([instance](let [table (:table (t2/hydrate instance :table))](mi/can-read? table)))- ([model pk]- (mi/can-read? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-read? (segments.db/segment pk))));; Segments can be created by;; a) superusers@@ -91,7 +92,7 @@(defmethod mi/can-write? :model/Segment([instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (segments.db/table (:table_id instance)))](and (or (mi/superuser?)(and api/*is-data-analyst?*(perms/user-has-permission-for-table?@@ -101,8 +102,8 @@(:db_id table)(u/the-id table))))(remote-sync/table-editable? table))))- ([model pk]- (mi/can-write? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-write? (segments.db/segment pk))));; Segments can be created by;; a) superusers@@ -111,7 +112,7 @@(defmethod mi/can-create? :model/Segment[_model instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (segments.db/table (:table_id instance)))](and (or (mi/superuser?)(and api/*is-data-analyst?*(perms/user-has-permission-for-table?@@ -136,7 +137,7 @@collection-synced-map (if (seq collection-ids)(into {}(map (juxt :id :is_remote_synced))- (t2/select :model/Collection :id [:in collection-ids]))+ (segments.db/collections collection-ids)){});; Associate collection info with each segment's tablesegments-with-collection (for [segment segments-with-tables@@ -157,7 +158,7 @@[{:keys [definition], table-id :table_id}](when (some? definition)(let [database-id (when table-id- (t2/select-one-fn :db_id :model/Table :id table-id))]+ (segments.db/table-database-id table-id))](normalize-segment-definition definition table-id database-id))))(t2/define-before-insert :model/Segment@@ -184,7 +185,7 @@(defmethod mi/perms-objects-set :model/Segment[segment read-or-write](let [table (or (:table segment)- (t2/select-one ['Table :db_id :schema :id] :id (u/the-id (:table_id segment))))]+ (segments.db/table-perms-columns (u/the-id (:table_id segment))))](mi/perms-objects-set table read-or-write)))(defn- maybe-migrated-segment-definitiondiff --git a/src/metabase/server/db.clj b/src/metabase/server/db.cljnew file mode 100644index 00000000000..0011f9155e7--- /dev/null+++ b/src/metabase/server/db.clj@@ -0,0 +1,145 @@+(ns metabase.server.db+ "Application database queries for the server module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]+ [toucan2.pipeline :as t2.pipeline]))++;; These session/API-key/OAuth-token lookup queries run on every single authenticated API request, so it's worth it+;; to optimize a bit and only compile each one to SQL once (keyed by its boolean/enum arguments) rather than every+;; time.++(defn- oldest-allowed-expr+ "A database-specific expression for `NOW() - interval`."+ [db-type amount unit]+ (let [now (h2x/current-datetime-honeysql-form db-type)]+ (case db-type+ :postgres [:- now [::h2x/postgres-interval amount unit]]+ :h2 [:dateadd (h2x/literal (name unit))+ [:inline (- amount)]+ now]+ :mysql [:- now [::h2x/mysql-interval amount unit]])))++(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds])} session-with-id-query+ (mdb/memoize-for-application-db+ (fn [db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds]+ (first+ (t2.pipeline/compile*+ (cond-> {:select [[:session.user_id :metabase-user-id]+ [:user.is_superuser :is-superuser?]+ [:user.is_data_analyst :is-data-analyst?]+ [:user.locale :user-locale]+ [:auth_identity.provider :auth-provider]]+ :from [[:core_session :session]]+ :left-join [[:core_user :user] [:= :session.user_id :user.id]+ [:tenant] [:= :tenant.id :user.tenant_id]+ [:auth_identity] [:= :auth_identity.id :session.auth_identity_id]]+ :where (into [:and+ (if enable-tenants?+ [:or [:= :tenant.id nil] :tenant.is_active]+ [:= :tenant.id nil])+ [:= :user.is_active true]+ [:= :session.key_hashed ^:allow-raw-sql [:raw "?"]]+ [:> :session.created_at (oldest-allowed-expr db-type max-age-minutes :minute)]+ [:or [:= :session.expires_at nil]+ [:> :session.expires_at (h2x/current-datetime-honeysql-form db-type)]]+ [:= :session.anti_csrf_token (case session-type+ :normal nil+ :full-app-embed ^:allow-raw-sql [:raw "?"])]]+ (when session-timeout-seconds+ [[:> [:coalesce :session.last_active_at :session.created_at]+ (oldest-allowed-expr db-type session-timeout-seconds :second)]]))+ :limit [:inline 1]}+ enable-advanced-permissions?+ (->+ (sql.helpers/select+ [:pgm.is_group_manager :is-group-manager?])+ (sql.helpers/left-join+ [:permissions_group_membership :pgm] [:and+ [:= :pgm.user_id :user.id]+ [:is :pgm.is_group_manager true]]))))))))++(def ^:private ^{:arglists '([enable-advanced-permissions?])} user-data-for-api-key-prefix-query+ (mdb/memoize-for-application-db+ (fn [enable-advanced-permissions?]+ (first+ (t2.pipeline/compile*+ (cond-> {:select [[:api_key.user_id :metabase-user-id]+ [:api_key.key :api-key]+ [:user.is_superuser :is-superuser?]+ [:user.is_data_analyst :is-data-analyst?]+ [:user.locale :user-locale]]+ :from :api_key+ :left-join [[:core_user :user] [:= :api_key.user_id :user.id]]+ :where [:and+ [:= :user.is_active true]+ [:= :api_key.key_prefix ^:allow-raw-sql [:raw "?"]]]+ :limit [:inline 1]}+ enable-advanced-permissions?+ (->+ (sql.helpers/select+ [:pgm.is_group_manager :is-group-manager?])+ (sql.helpers/left-join+ [:permissions_group_membership :pgm] [:and+ [:= :pgm.user_id :user.id]+ [:is :pgm.is_group_manager true]]))))))))++(def ^:private ^{:arglists '([enable-advanced-permissions?])} user-data-for-id-query+ (mdb/memoize-for-application-db+ (fn [enable-advanced-permissions?]+ (first+ (t2.pipeline/compile*+ (cond-> {:select [[:user.id :metabase-user-id]+ [:user.is_superuser :is-superuser?]+ [:user.is_data_analyst :is-data-analyst?]+ [:user.locale :user-locale]]+ :from [[:core_user :user]]+ :where [:and+ [:= :user.is_active true]+ [:= :user.id ^:allow-raw-sql [:raw "?"]]]+ :limit [:inline 1]}+ enable-advanced-permissions?+ (->+ (sql.helpers/select+ [:pgm.is_group_manager :is-group-manager?])+ (sql.helpers/left-join+ [:permissions_group_membership :pgm] [:and+ [:= :pgm.user_id :user.id]+ [:is :pgm.is_group_manager true]]))))))))++(defn session-user-info+ "The user id, superuser/data-analyst/group-manager flags, locale, and auth provider for the active, unexpired+ Session whose `key_hashed` is `session-key-hash`, or nil if there is none. `anti-csrf-token`, when present,+ additionally requires the Session's `anti_csrf_token` to match it (a full-app-embed session); `max-age-minutes`+ and `session-timeout-seconds` (which may be nil) bound how old or idle the Session may be."+ [session-key-hash anti-csrf-token max-age-minutes enable-advanced-permissions? enable-tenants? session-timeout-seconds]+ (let [sql (session-with-id-query (mdb/db-type)+ max-age-minutes+ (if (seq anti-csrf-token) :full-app-embed :normal)+ enable-advanced-permissions?+ enable-tenants?+ session-timeout-seconds)+ params (concat [session-key-hash] (when (seq anti-csrf-token) [anti-csrf-token]))]+ (t2/query-one (cons sql params))))++(defn api-key-user-info+ "The user id, api key, superuser/data-analyst/group-manager flags, and locale for the active User whose ApiKey+ starts with `key-prefix`, or nil if there is none."+ [key-prefix enable-advanced-permissions?]+ (t2/query-one (cons (user-data-for-api-key-prefix-query enable-advanced-permissions?) [key-prefix])))++(defn oauth-user-info+ "The user id, superuser/data-analyst/group-manager flags, and locale for the active User with `user-id`, or nil if+ there is none."+ [user-id enable-advanced-permissions?]+ (t2/query-one (cons (user-data-for-id-query enable-advanced-permissions?) [user-id])))++(defn touch-session!+ "Set `last_active_at` of the Session with `key-hashed` to now."+ [key-hashed]+ (t2/query-one {:update (t2/table-name :model/Session)+ :set {:last_active_at :%now}+ :where [:= :key_hashed key-hashed]}))diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.cljindex 3fa103f4d6a..5e3712da456 100644--- a/src/metabase/server/middleware/session.clj+++ b/src/metabase/server/middleware/session.clj@@ -15,7 +15,6 @@an ApiKey in our database, you'll be authenticated as that ApiKey's associated User."(:require[clojure.string :as str]- [honey.sql.helpers :as sql.helpers][java-time.api :as t][malli.error :as me][medley.core :as m]@@ -23,7 +22,6 @@[metabase.api-keys.core :as api-key][metabase.api-keys.schema :as api-keys.schema][metabase.api.macros.scope :as scope]- [metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.initialization-status.core :as init-status][metabase.mcp.core :as mcp]@@ -31,20 +29,18 @@[metabase.premium-features.core :as premium-features][metabase.request.core :as request][metabase.request.schema :as request.schema]+ [metabase.server.db :as server.db][metabase.session.core :as session][metabase.settings.core :as setting][metabase.tracing.core :as tracing][metabase.util :as u][metabase.util.encryption :as encryption]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :as i18n][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.password :as u.password]- [metabase.util.string :as string]- [toucan2.core :as t2]- [toucan2.pipeline :as t2.pipeline]))+ [metabase.util.string :as string]))(set! *warn-on-reflection* true)@@ -100,110 +96,6 @@;;; | wrap-current-user-info |;;; +----------------------------------------------------------------------------------------------------------------+-;; Because this query runs on every single API request it's worth it to optimize it a bit and only compile it to SQL-;; once rather than every time-(defn- oldest-allowed-expr- "Build a database-specific expression for `NOW() - interval`."- [db-type amount unit]- (let [now (h2x/current-datetime-honeysql-form db-type)]- (case db-type- :postgres [:- now [::h2x/postgres-interval amount unit]]- :h2 [:dateadd (h2x/literal (name unit))- [:inline (- amount)]- now]- :mysql [:- now [::h2x/mysql-interval amount unit]])))--(def ^:private ^{:arglists '([db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds])} session-with-id-query- (mdb/memoize-for-application-db- (fn [db-type max-age-minutes session-type enable-advanced-permissions? enable-tenants? session-timeout-seconds]- (first- (t2.pipeline/compile*- (cond-> {:select [[:session.user_id :metabase-user-id]- [:user.is_superuser :is-superuser?]- [:user.is_data_analyst :is-data-analyst?]- [:user.locale :user-locale]- [:auth_identity.provider :auth-provider]]- :from [[:core_session :session]]- :left-join [[:core_user :user] [:= :session.user_id :user.id]- [:tenant] [:= :tenant.id :user.tenant_id]- [:auth_identity] [:= :auth_identity.id :session.auth_identity_id]]- :where (into [:and- (if enable-tenants?- [:or [:= :tenant.id nil] :tenant.is_active]- [:= :tenant.id nil])- [:= :user.is_active true]- [:= :session.key_hashed ^:allow-raw-sql [:raw "?"]]- [:> :session.created_at (oldest-allowed-expr db-type max-age-minutes :minute)]- [:or [:= :session.expires_at nil]- [:> :session.expires_at (h2x/current-datetime-honeysql-form db-type)]]- [:= :session.anti_csrf_token (case session-type- :normal nil- :full-app-embed ^:allow-raw-sql [:raw "?"])]]- (when session-timeout-seconds- [[:> [:coalesce :session.last_active_at :session.created_at]- (oldest-allowed-expr db-type session-timeout-seconds :second)]]))- :limit [:inline 1]}- enable-advanced-permissions?- (->- (sql.helpers/select- [:pgm.is_group_manager :is-group-manager?])- (sql.helpers/left-join- [:permissions_group_membership :pgm] [:and- [:= :pgm.user_id :user.id]- [:is :pgm.is_group_manager true]]))))))))--;; See above: because this query runs on every single API request (with an API Key) it's worth it to optimize it a bit-;; and only compile it to SQL once rather than every time-(def ^:private ^{:arglists '([enable-advanced-permissions?])} user-data-for-api-key-prefix-query- (mdb/memoize-for-application-db- (fn [enable-advanced-permissions?]- (first- (t2.pipeline/compile*- (cond-> {:select [[:api_key.user_id :metabase-user-id]- [:api_key.key :api-key]- [:user.is_superuser :is-superuser?]- [:user.is_data_analyst :is-data-analyst?]- [:user.locale :user-locale]]- :from :api_key- :left-join [[:core_user :user] [:= :api_key.user_id :user.id]]- :where [:and- [:= :user.is_active true]- [:= :api_key.key_prefix ^:allow-raw-sql [:raw "?"]]]- :limit [:inline 1]}- enable-advanced-permissions?- (->- (sql.helpers/select- [:pgm.is_group_manager :is-group-manager?])- (sql.helpers/left-join- [:permissions_group_membership :pgm] [:and- [:= :pgm.user_id :user.id]- [:is :pgm.is_group_manager true]]))))))))--;; Like the session/api-key queries above, this runs on every OAuth-bearer-authenticated API request, so-;; compile it to SQL once. Keyed on the resolved user id from the OAuth access token.-(def ^:private ^{:arglists '([enable-advanced-permissions?])} user-data-for-id-query- (mdb/memoize-for-application-db- (fn [enable-advanced-permissions?]- (first- (t2.pipeline/compile*- (cond-> {:select [[:user.id :metabase-user-id]- [:user.is_superuser :is-superuser?]- [:user.is_data_analyst :is-data-analyst?]- [:user.locale :user-locale]]- :from [[:core_user :user]]- :where [:and- [:= :user.is_active true]- [:= :user.id ^:allow-raw-sql [:raw "?"]]]- :limit [:inline 1]}- enable-advanced-permissions?- (->- (sql.helpers/select- [:pgm.is_group_manager :is-group-manager?])- (sql.helpers/left-join- [:permissions_group_membership :pgm] [:and- [:= :pgm.user_id :user.id]- [:is :pgm.is_group_manager true]]))))))))-(defn- valid-session-key?"Validates that the given session-key looks like a session key (a UUID string). Session keys are only ever comparedagainst `core_session.key_hashed`; this check short-circuits obviously-invalid values before we hash them."@@ -214,20 +106,15 @@"Return User ID and superuser status for Session with `session-key` if it is valid and not expired."[session-key anti-csrf-token](when (and session-key (valid-session-key? session-key) (init-status/complete?))- (let [timeout (request/enabled-session-timeout-seconds)- sql (session-with-id-query (mdb/db-type)+ (some-> (server.db/session-user-info (session/hash-session-key session-key)+ anti-csrf-token(config/config-int :max-session-age)- (if (seq anti-csrf-token) :full-app-embed :normal)(premium-features/enable-advanced-permissions?)(and (premium-features/enable-tenants?)(setting/get :use-tenants))- timeout)- params (concat [(session/hash-session-key session-key)]- (when (seq anti-csrf-token)- [anti-csrf-token]))]- (some-> (t2/query-one (cons sql params))- ;; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false- (update :is-group-manager? boolean)))))+ (request/enabled-session-timeout-seconds))+ ;; is-group-manager? could return `nil, convert it to boolean so it's guaranteed to be only true/false+ (update :is-group-manager? boolean))))(def ^:private api-key-that-should-never-match (str (random-uuid)))(def ^:private hash-that-should-never-match (u.password/hash-bcrypt "password"))@@ -266,9 +153,8 @@(log/error "Ignoring invalid API Key")(log/errorf "Ignoring invalid API Key: %s" error))nil)- (let [user-info (-> (t2/query-one (cons (user-data-for-api-key-prefix-query- (premium-features/enable-advanced-permissions?))- [(api-key/prefix api-key)]))+ (let [user-info (-> (server.db/api-key-user-info (api-key/prefix api-key)+ (premium-features/enable-advanced-permissions?))(m/update-existing :is-group-manager? boolean))](when (matching-api-key? user-info api-key)(-> user-info@@ -305,8 +191,7 @@(when (init-status/complete?)(when-let [token (oauth-server/extract-bearer-token request)](when-let [{:keys [user-id scopes]} (oauth-server/resolve-access-token token)]- (some-> (t2/query-one (cons (user-data-for-id-query (premium-features/enable-advanced-permissions?))- [user-id]))+ (some-> (server.db/oauth-user-info user-id (premium-features/enable-advanced-permissions?))(m/update-existing :is-group-manager? boolean)(assoc :token-scopes (oauth-token->token-scopes scopes)))))))@@ -330,7 +215,7 @@(contains? mcp-ui-request-surface [(:request-method request) (:uri request)]))(when-let [{:keys [uid sid] :as claims}(mcp/resolve-ui-credential (get-in request [:headers "x-metabase-mcp-ui-auth"]))]- (some-> (t2/query-one (cons (user-data-for-id-query (premium-features/enable-advanced-permissions?)) [uid]))+ (some-> (server.db/oauth-user-info uid (premium-features/enable-advanced-permissions?))(m/update-existing :is-group-manager? boolean);; Endpoint scope middleware treats this as session-like auth, but the;; route allowlist above is the actual authorization boundary.@@ -415,9 +300,7 @@(let [hashed (session/hash-session-key session-key)](when (session/record-session-activity-update! hashed)(try- (t2/query-one {:update (t2/table-name :model/Session)- :set {:last_active_at :%now}- :where [:= :key_hashed hashed]})+ (server.db/touch-session! hashed)(catch Exception e(log/warnf "Failed to update session last_active_at: %s" (ex-message e))))))))diff --git a/src/metabase/session/api.clj b/src/metabase/session/api.cljindex 962620819f9..b97c893ab6e 100644--- a/src/metabase/session/api.clj+++ b/src/metabase/session/api.clj@@ -13,6 +13,7 @@[metabase.premium-features.core :refer [defenterprise]][metabase.request.core :as request][metabase.session.challenge :as session.challenge]+ [metabase.session.db :as session.db][metabase.session.models.session :as session][metabase.session.schema :as session.schema][metabase.settings.core :as setting]@@ -24,8 +25,7 @@[metabase.util.malli :as mu][metabase.util.malli.schema :as ms][metabase.util.password :as u.password]- [throttle.core :as throttle]- [toucan2.core :as t2]))+ [throttle.core :as throttle]))(set! *warn-on-reflection* true)@@ -220,7 +220,7 @@[_route-params _query-params _body {:keys [metabase-session-key], :as _request}](api/check-404 (not-empty metabase-session-key))(let [session-key-hashed (session/hash-session-key metabase-session-key)- rows-deleted (t2/delete! :model/Session :key_hashed session-key-hashed)]+ rows-deleted (session.db/delete-session-by-key-hashed! session-key-hashed)];; clear the cookie even when no row matched (e.g. a session hashed under a previous secret), or the browser;; would keep resending the dead cookie(request/clear-session-cookie@@ -251,17 +251,15 @@"Refresh the reset token on an existing support-access-grant AuthIdentity, preserving the grantbinding. Returns the new plaintext token, or nil if the grant has expired."[user-id]- (when-let [auth-identity (t2/select-one :model/AuthIdentity- :user_id user-id- :provider "support-access-grant")]+ (when-let [auth-identity (session.db/auth-identity-for-provider user-id "support-access-grant")](let [grant-ends-at (get-in auth-identity [:credentials :grant_ends_at])](when (and grant-ends-at (t/before? (t/instant) (t/instant grant-ends-at)))(let [token (auth-identity/generate-reset-token user-id)]- (t2/update! :model/AuthIdentity (:id auth-identity)- {:credentials {:token_hash (u.password/hash-bcrypt token)- :expires_at (t/plus (t/instant) (t/hours 48))- :grant_ends_at grant-ends-at- :consumed_at nil}})+ (session.db/set-auth-identity-credentials! (:id auth-identity)+ {:token_hash (u.password/hash-bcrypt token)+ :expires_at (t/plus (t/instant) (t/hours 48))+ :grant_ends_at grant-ends-at+ :consumed_at nil})token)))))(defn- forgot-password-impl@@ -270,9 +268,7 @@(when-let [{user-id :idsso-source :sso_sourceis-active? :is_active :as user}- (t2/select-one [:model/User :id :sso_source :is_active]- :%lower.email- (u/lower-case-en email))]+ (session.db/user-by-email email)](cond;; SSO users should use their SSO provider, not password reset.(sso-password-reset-disabled? sso-source)@@ -281,7 +277,7 @@;; Support-access users get a refreshed token bound to the grant.;; If the grant has expired, refresh-support-access-token! returns nil and we silently;; do nothing (same as a nonexistent account).- (t2/exists? :model/AuthIdentity :user_id user-id :provider "support-access-grant")+ (session.db/auth-identity-exists? user-id "support-access-grant")(when-let [reset-token (refresh-support-access-token! user-id)](let [password-reset-url (str (system/site-url) "/auth/reset_password/" reset-token)](messages/send-password-reset-email! email nil password-reset-url is-active?)))@@ -488,9 +484,9 @@(fn [](when-not (verify-second-factor! user-id code jti)(events/publish-event! :event/mfa-verification-failed- {:object (t2/select-one :model/User :id user-id)})+ {:object (session.db/user user-id)})(throw (ex-info (tru "Invalid authentication code.") {:status-code 401})))))- (let [user (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id)]+ (let [user (session.db/user-login-status user-id)];; the account can be deactivated (or deleted) between the password step and here; a;; challenge token must not outlive the account. Same 401 as a bad token — no oracle.(when-not (:is_active user)diff --git a/src/metabase/session/db.clj b/src/metabase/session/db.cljnew file mode 100644index 00000000000..3d0abb3df0b--- /dev/null+++ b/src/metabase/session/db.clj@@ -0,0 +1,72 @@+(ns metabase.session.db+ "Application database queries for the session module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.app-db.core :as mdb]+ [metabase.tracing.core :as tracing]+ [metabase.util :as u]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn delete-session-by-key-hashed!+ "Delete the Session with `key-hashed`, returning the number of rows deleted."+ [key-hashed]+ (t2/delete! :model/Session :key_hashed key-hashed))++(defn delete-sessions-for-user!+ "Delete every Session of the User with `user-id`."+ [user-id]+ (t2/delete! :model/Session :user_id user-id))++(defn delete-expired-sessions!+ "Delete Sessions older than `max-age-minutes`, past their own `expires_at`, or (when `idle-timeout-seconds` is+ given) idle longer than `idle-timeout-seconds`. Returns the number of rows deleted."+ [max-age-minutes idle-timeout-seconds]+ (let [db-type (mdb/db-type)+ now (h2x/current-datetime-honeysql-form db-type)+ oldest-allowed (h2x/add-interval-honeysql-form db-type now (- max-age-minutes) :minute)+ timeout-oldest (when idle-timeout-seconds+ (h2x/add-interval-honeysql-form db-type now (- idle-timeout-seconds) :second))+ hsql {:delete-from [(t2/table-name :model/Session)]+ :where (cond-> [:or+ [:< :created_at oldest-allowed]+ [:and [:not= :expires_at nil] [:< :expires_at now]]]+ timeout-oldest+ (conj [:< [:coalesce :last_active_at :created_at] timeout-oldest]))}]+ (tracing/with-span :tasks "task.session-cleanup.delete" {:db/statement (tracing/best-effort-sanitize-sql hsql)}+ (t2/query-one hsql))))++(defn auth-identity-for-provider+ "The AuthIdentity of the User with `user-id` at `provider`, or nil."+ [user-id provider]+ (t2/select-one :model/AuthIdentity :user_id user-id :provider provider))++(defn auth-identity-exists?+ "Whether the User with `user-id` has an AuthIdentity at `provider`."+ [user-id provider]+ (t2/exists? :model/AuthIdentity :user_id user-id :provider provider))++(defn set-auth-identity-credentials!+ "Set the `credentials` of the AuthIdentity with `auth-identity-id`."+ [auth-identity-id credentials]+ (t2/update! :model/AuthIdentity auth-identity-id {:credentials credentials}))++(defn auth-identity-provider+ "The `:provider` of the AuthIdentity with `auth-identity-id`, or nil."+ [auth-identity-id]+ (t2/select-one [:model/AuthIdentity :provider] :id auth-identity-id))++(defn user-by-email+ "The id, SSO source, and active flag of the User whose email matches `email` case-insensitively, or nil."+ [email]+ (t2/select-one [:model/User :id :sso_source :is_active] :%lower.email (u/lower-case-en email)))++(defn user+ "The User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User :id user-id))++(defn user-login-status+ "The id, active flag, last login, and tenant id of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :id :is_active :last_login :tenant_id] :id user-id))diff --git a/src/metabase/session/events/revoke_on_deactivation.clj b/src/metabase/session/events/revoke_on_deactivation.cljindex 35f6a23d601..e46b9bb02d0 100644--- a/src/metabase/session/events/revoke_on_deactivation.clj+++ b/src/metabase/session/events/revoke_on_deactivation.clj@@ -3,12 +3,12 @@pre-deactivation session cookie. (SEC-863)"(:require[metabase.events.core :as events]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [metabase.session.db :as session.db]+ [methodical.core :as methodical]))(events/derive! ::event :metabase/event)(events/derive! :event/user-credentials-revoked ::event)(methodical/defmethod events/publish-event! ::event[_topic {:keys [user-id] :as _event}]- (t2/delete! :model/Session :user_id user-id))+ (session.db/delete-sessions-for-user! user-id))diff --git a/src/metabase/session/models/session.clj b/src/metabase/session/models/session.cljindex 9ec8b698229..c619bc83a12 100644--- a/src/metabase/session/models/session.clj+++ b/src/metabase/session/models/session.clj@@ -8,6 +8,7 @@[environ.core :as env][metabase.events.core :as events][metabase.request.core :as request]+ [metabase.session.db :as session.db][metabase.session.settings :as session.settings][metabase.util :as u][metabase.util.encryption :as encryption]@@ -85,7 +86,7 @@(throw (ex-info "Session key should not be stored plaintext in the session table." {})));; Check auth identity provider if provided(when-let [auth-identity-id (:auth_identity_id session)]- (when-let [auth-identity (t2/select-one [:model/AuthIdentity :provider] :id auth-identity-id)]+ (when-let [auth-identity (session.db/auth-identity-provider auth-identity-id)](when (and (= "password" (:provider auth-identity))(not (session.settings/enable-password-login)))(throw (ex-info (str (tru "Password login is disabled for this instance."))@@ -101,7 +102,7 @@(t2/define-after-insert :model/Session[session]- (when-let [user (t2/select-one :model/User (:user_id session))]+ (when-let [user (session.db/user (:user_id session))](let [event {:user-id (u/the-id user)}](events/publish-event! :event/user-login event)(when (nil? (:last_login user))diff --git a/src/metabase/session/task/session_cleanup.clj b/src/metabase/session/task/session_cleanup.cljindex c0c2c244857..ec55cc89c8f 100644--- a/src/metabase/session/task/session_cleanup.clj+++ b/src/metabase/session/task/session_cleanup.clj@@ -3,14 +3,11 @@[clojurewerkz.quartzite.jobs :as jobs][clojurewerkz.quartzite.schedule.cron :as cron][clojurewerkz.quartzite.triggers :as triggers]- [metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.request.core :as request][metabase.session.core :as session]- [metabase.task.core :as task]- [metabase.tracing.core :as tracing]- [metabase.util.honey-sql-2 :as h2x]- [toucan2.core :as t2]))+ [metabase.session.db :as session.db]+ [metabase.task.core :as task]))(set! *warn-on-reflection* true)@@ -19,27 +16,8 @@(absolute lifetime), sessions past their own `expires_at`, and sessions that have been idle longer than thesession-timeout setting (if configured)."[]- (let [db-type (mdb/db-type)- now (h2x/current-datetime-honeysql-form db-type)- oldest-allowed (h2x/add-interval-honeysql-form db-type- now- (- (config/config-int :max-session-age))- :minute)- timeout-seconds (request/enabled-session-timeout-seconds)- timeout-oldest (when timeout-seconds- (h2x/add-interval-honeysql-form db-type- now- (- timeout-seconds)- :second))- where-clause (cond-> [:or- [:< :created_at oldest-allowed]- [:and [:not= :expires_at nil] [:< :expires_at now]]]- timeout-oldest- (conj [:< [:coalesce :last_active_at :created_at] timeout-oldest]))- hsql {:delete-from [(t2/table-name :model/Session)]- :where where-clause}]- (tracing/with-span :tasks "task.session-cleanup.delete" {:db/statement (tracing/best-effort-sanitize-sql hsql)}- (t2/query-one hsql))))+ (session.db/delete-expired-sessions! (config/config-int :max-session-age)+ (request/enabled-session-timeout-seconds)))(def ^:private session-cleanup-job-key (jobs/key "metabase.task.session-cleanup.job"))(def ^:private session-cleanup-trigger-key (triggers/key "metabase.task.session-cleanup.trigger"))diff --git a/src/metabase/settings/db.clj b/src/metabase/settings/db.cljnew file mode 100644index 00000000000..1aab48c9714--- /dev/null+++ b/src/metabase/settings/db.clj@@ -0,0 +1,47 @@+(ns metabase.settings.db+ "Application database queries for the settings module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions."+ (:require+ [toucan2.core :as t2]))++(defn setting-value+ "The stored value of the Setting with `setting-key`, or nil."+ [setting-key]+ (t2/select-one-fn :value :model/Setting :key setting-key))++(defn setting-values-by-key+ "A map of key to stored value for every Setting."+ []+ (t2/select-fn->fn :key :value :model/Setting))++(defn insert-setting!+ "Insert a Setting row for `setting-key` holding `value` and return it."+ [setting-key value]+ (first (t2/insert-returning-instances! :model/Setting :key setting-key :value value)))++(defn update-setting-value!+ "Set the value of the Setting with `setting-key` to `value`."+ [setting-key value]+ (t2/update! :model/Setting :key setting-key {:value value}))++(defn delete-setting!+ "Delete the Setting with `setting-key`, via a raw table delete that bypasses model hooks."+ [setting-key]+ (t2/delete! (t2/table-name :model/Setting) :key setting-key))++(defn update-raw-setting-row!+ "Set the raw `value` and `value-with-aad` of the Setting row with `setting-key`, returning the number of rows+ updated."+ [setting-key value value-with-aad]+ (t2/update! :setting {:key setting-key} {:value value, :value_with_aad value-with-aad}))++(defn insert-raw-setting-row!+ "Insert a raw Setting row for `setting-key` holding `value` and `value-with-aad`."+ [setting-key value value-with-aad]+ (t2/insert! (t2/table-name (t2/resolve-model :model/Setting))+ :key setting-key, :value value, :value_with_aad value-with-aad))++(defn update-user-settings!+ "Store `settings-json` as the user-local settings of the User with `user-id`."+ [user-id settings-json]+ (t2/update! :model/User user-id {:settings settings-json}))diff --git a/src/metabase/settings/models/setting.clj b/src/metabase/settings/models/setting.cljindex 8d88301fd4c..7f5ee026594 100644--- a/src/metabase/settings/models/setting.clj+++ b/src/metabase/settings/models/setting.clj@@ -14,6 +14,7 @@[metabase.config.core :as config][metabase.events.core :as events][metabase.models.serialization :as serdes]+ [metabase.settings.db :as settings.db][metabase.settings.models.setting.cache :as setting.cache][metabase.util :as u][metabase.util.date-2 :as u.date]@@ -405,7 +406,7 @@;; Update the atom in *user-local-values* with the new value before writing to the DB. This ensures that;; subsequent setting updates within the same API request will not overwrite this value.(swap! @*user-local-values* u/assoc-dissoc setting-name value)- (t2/update! 'User api/*current-user-id* {:settings (json/encode @@*user-local-values*)})))+ (settings.db/update-user-settings! api/*current-user-id* (json/encode @@*user-local-values*))))(def ^:dynamic *enforce-setting-access-checks*"A dynamic var that controls whether we should enforce checks on setting access. Defaults to false; should be@@ -545,14 +546,14 @@"Look up a single setting key in the DB or cache. Returns the raw (possibly empty) string, or nil."^String [setting-name-str](if config/*disable-setting-cache*- (t2/select-one-fn :value :model/Setting :key setting-name-str)+ (settings.db/setting-value setting-name-str)(do;; gotcha - returns immediately if another process is restoring it, i.e. before it's been populated(setting.cache/restore-cache-if-needed!)(let [cache (setting.cache/cache)](if (nil? cache);; nil if we returned early above, and the cache is still being restored - in that case hit the db- (t2/select-one-fn :value :model/Setting :key setting-name-str)+ (settings.db/setting-value setting-name-str)(core/get cache setting-name-str))))))(def ^:dynamic *deprecated-db-key-warned*@@ -804,14 +805,12 @@(assert (not= setting-name setting.cache/settings-last-updated-key)(tru "You cannot update `settings-last-updated` yourself! This is done automatically."));; Toucan 2 version of `update!` will do transforms and stuff like that- (t2/update! :model/Setting :key setting-name {:value new-value}))+ (settings.db/update-setting-value! setting-name new-value))(defn- set-new-setting!"Insert a new row for a Setting. Used internally by [[set-value-of-type!]] for `:string` below; do not use directly."[setting-name new-value]- (try (first (t2/insert-returning-instances! :model/Setting- :key setting-name- :value new-value))+ (try (settings.db/insert-setting! setting-name new-value);; if for some reason inserting the new value fails it almost certainly means the cache is out of date;; and there's actually a row in the DB that's not in the cache for some reason. Go ahead and update the;; existing value and log a warning@@ -881,11 +880,11 @@(cond(nil? new-value)(do- (t2/delete! (t2/table-name :model/Setting) :key setting-name)+ (settings.db/delete-setting! setting-name);; also clear the deprecated-name key so that fallback doesn't resurface an old value(when-let [deprecated-name (:deprecated-name setting)](let [deprecated-key (core/name deprecated-name)]- (t2/delete! (t2/table-name :model/Setting) :key deprecated-key)+ (settings.db/delete-setting! deprecated-key)(setting.cache/update-cache! deprecated-key nil))));; if there's a value in the cache then the row already exists in the DB; update thatdiff --git a/src/metabase/settings/models/setting/cache.clj b/src/metabase/settings/models/setting/cache.cljindex 85fb9922dd9..faf5913e670 100644--- a/src/metabase/settings/models/setting/cache.clj+++ b/src/metabase/settings/models/setting/cache.clj@@ -6,10 +6,10 @@[clojure.string :as str][metabase.app-db.core :as mdb][metabase.app-db.setting :as mdb.setting]+ [metabase.settings.db :as settings.db][metabase.util :as u][metabase.util.encryption :as encryption]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.util.concurrent.atomic AtomicLong)(java.util.concurrent.locks ReentrantLock)))@@ -78,14 +78,13 @@(let [value (mdb/current-timestamp-string (mdb/db-type))value-with-aad (encryption/maybe-encrypt value {:aad (mdb.setting/setting-aad settings-last-updated-key)})];; attempt to UPDATE the existing row. If no row exists, `t2/update!` will return 0...- (or (pos? (t2/update! :setting {:key settings-last-updated-key} {:value value, :value_with_aad value-with-aad}))+ (or (pos? (settings.db/update-raw-setting-row! settings-last-updated-key value value-with-aad));; ...at which point we will try to INSERT a new row. Note that it is entirely possible two instances can both;; try to INSERT it at the same time; one instance would fail because it would violate the PK constraint on;; `key`, and throw a SQLException. As long as one instance updates the value, we are fine, so we can go ahead;; and ignore that Exception if one is thrown.(try- (t2/insert! (t2/table-name (t2/resolve-model :model/Setting))- :key settings-last-updated-key, :value value, :value_with_aad value-with-aad)+ (settings.db/insert-raw-setting-row! settings-last-updated-key value value-with-aad)(catch java.sql.SQLException e;; go ahead and log the whole SQLException message chain anyway on the off chance that it *wasn't* just a;; race condition issue@@ -93,7 +92,7 @@(str/join "; " (keep ex-message (take-while some? (iterate #(.getNextException ^java.sql.SQLException %) e)))))))));; Now that we updated the value in the DB, go ahead and update our cached value as well, because we know about the;; changes- (swap! (cache*) assoc settings-last-updated-key (t2/select-one-fn :value :model/Setting :key settings-last-updated-key)))+ (swap! (cache*) assoc settings-last-updated-key (settings.db/setting-value settings-last-updated-key)))(defn cache-last-updated-at"Fetch the value of `settings-last-updated`, indicating the timestamp of the settings cache. Possibly null."@@ -121,7 +120,7 @@;; compare it to the value in the DB. This is done be seeing whether a row exists;; WHERE value > <local-value>;; compared here rather than in SQL: what is stored is ciphertext, so only the decrypted timestamps can be ordered- (u/prog1 (when-let [db-value (t2/select-one-fn :value :model/Setting :key settings-last-updated-key)]+ (u/prog1 (when-let [db-value (settings.db/setting-value settings-last-updated-key)](when (pos? (compare db-value last-known-update))db-value))(log/trace "last known Settings update: " (pr-str last-known-update))@@ -145,7 +144,7 @@"Populate cache with the latest hotness from the db"[](log/debug "Refreshing Settings cache...")- (reset! (cache*) (t2/select-fn->fn :key :value :model/Setting)))+ (reset! (cache*) (settings.db/setting-values-by-key)))(defonce ^:private ^ReentrantLock restore-cache-lock (ReentrantLock.))diff --git a/src/metabase/setup/db.clj b/src/metabase/setup/db.cljnew file mode 100644index 00000000000..36cdfc266f1--- /dev/null+++ b/src/metabase/setup/db.clj@@ -0,0 +1,10 @@+(ns metabase.setup.db+ "Application database queries for the setup module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn users-except+ "Every User other than the one with `user-id`."+ [user-id]+ (t2/select :model/User {:where [:not= :id user-id]}))diff --git a/src/metabase/setup/settings.clj b/src/metabase/setup/settings.cljindex 9f9cf53b14a..86e6609b4cf 100644--- a/src/metabase/setup/settings.clj+++ b/src/metabase/setup/settings.clj@@ -3,8 +3,8 @@[metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.settings.core :as setting :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru tru]]- [toucan2.core :as t2]))+ [metabase.setup.db :as setup.db]+ [metabase.util.i18n :refer [deferred-tru tru]]))(defsetting setup-token"A token used to signify that an instance has permissions to create the initial User. This is created upon the first@@ -25,7 +25,7 @@(if (some? possible-override)possible-override(or (get @app-db-id->user-exists? (mdb/unique-identifier))- (let [exists? (boolean (seq (t2/select :model/User {:where [:not= :id config/internal-mb-user-id]})))]+ (let [exists? (boolean (seq (setup.db/users-except config/internal-mb-user-id)))](swap! app-db-id->user-exists? assoc (mdb/unique-identifier) exists?)exists?))))))diff --git a/src/metabase/setup_rest/api.clj b/src/metabase/setup_rest/api.cljindex d72e51687fd..3be51c908f0 100644--- a/src/metabase/setup_rest/api.clj+++ b/src/metabase/setup_rest/api.clj@@ -8,6 +8,7 @@[metabase.events.core :as events][metabase.request.core :as request][metabase.settings.core :as setting]+ [metabase.setup-rest.db :as setup-rest.db][metabase.setup.core :as setup][metabase.system.core :as system][metabase.util :as u]@@ -41,11 +42,7 @@(throw (ex-info(tru "The /api/setup route can only be used to create the first user, however a user currently exists."){:status-code 403})))- (let [new-user (first (t2/insert-returning-instances! :model/User- :email email- :first_name first-name- :last_name last-name- :is_superuser true))+ (let [new-user (setup-rest.db/insert-superuser! email first-name last-name)user-id (u/the-id new-user)](auth-identity/set-password! user-id password)(let [session (auth-identity/create-session-with-auth-tracking! new-user device-info :provider/password)]@@ -103,7 +100,7 @@(setting/restore-cache!)(throw e))))](let [{:keys [user-id session-key session]} (create!)- superuser (t2/select-one :model/User :id user-id)]+ superuser (setup-rest.db/user user-id)](events/publish-event! :event/user-login {:user-id user-id})(when-not (:last_login superuser)(events/publish-event! :event/user-joined {:user-id user-id}))diff --git a/src/metabase/setup_rest/db.clj b/src/metabase/setup_rest/db.cljnew file mode 100644index 00000000000..61c2cb15c4c--- /dev/null+++ b/src/metabase/setup_rest/db.clj@@ -0,0 +1,19 @@+(ns metabase.setup-rest.db+ "Application database queries for the setup REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn insert-superuser!+ "Insert a superuser with the given email and name and return the User instance."+ [email first-name last-name]+ (t2/insert-returning-instance! :model/User+ :email email+ :first_name first-name+ :last_name last-name+ :is_superuser true))++(defn user+ "The User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User :id user-id))diff --git a/src/metabase/slackbot/api.clj b/src/metabase/slackbot/api.cljindex 4c1bf6d609b..464af325d89 100644--- a/src/metabase/slackbot/api.clj+++ b/src/metabase/slackbot/api.clj@@ -15,6 +15,7 @@[metabase.settings.core :as setting][metabase.slackbot.client :as slackbot.client][metabase.slackbot.config :as slackbot.config]+ [metabase.slackbot.db :as slackbot.db][metabase.slackbot.events :as slackbot.events][metabase.slackbot.persistence :as slackbot.persistence][metabase.slackbot.settings :as slackbot.settings]@@ -29,8 +30,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [ring.util.codec :as codec]- [toucan2.core :as t2])+ [ring.util.codec :as codec])(:import(java.util.concurrent ExecutorService Executors ThreadFactory)))@@ -102,12 +102,7 @@signing secret version, so that rotating the secret automatically invalidates existing identity links. Legacyidentities without an explicit version are treated as version 0."[slack-user-id]- (let [identity (t2/select-one [:model/AuthIdentity :user_id :metadata]- :provider "slack-connect"- :provider_id slack-user-id- {:join [[:core_user :user] [:= :user.id :auth_identity.user_id]]- :where [:= :user.is_active true]- :order-by [[:created_at :desc]]})]+ (let [identity (slackbot.db/active-slack-connect-identity slack-user-id)](when (= (auth-identity-signing-secret-version identity)(current-signing-secret-version))(:user_id identity))))@@ -591,9 +586,7 @@[{:keys [message_external_id channel_id message_ts]}](or message_external_id(when (and channel_id message_ts)- (t2/select-one-fn :external_id :model/MetabotMessage- :channel_id channel_id- :slack_msg_id message_ts))))+ (slackbot.db/metabot-message-external-id channel_id message_ts))))(defn- handle-feedback-modal-submission"Handle submission of the feedback details modal.diff --git a/src/metabase/slackbot/db.clj b/src/metabase/slackbot/db.cljnew file mode 100644index 00000000000..6a2188f30af--- /dev/null+++ b/src/metabase/slackbot/db.clj@@ -0,0 +1,68 @@+(ns metabase.slackbot.db+ "Application database queries for the Slack bot module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn active-slack-connect-identity+ "The user id and metadata of the newest Slack Connect AuthIdentity of an active User for `slack-user-id`, or nil."+ [slack-user-id]+ (t2/select-one [:model/AuthIdentity :user_id :metadata]+ :provider "slack-connect"+ :provider_id slack-user-id+ {:join [[:core_user :user] [:= :user.id :auth_identity.user_id]]+ :where [:= :user.is_active true]+ :order-by [[:created_at :desc]]}))++(defn metabot-message-external-id+ "The external id of the MetabotMessage posted to `channel-id` as `slack-msg-id`, or nil."+ [channel-id slack-msg-id]+ (t2/select-one-fn :external_id :model/MetabotMessage :channel_id channel-id :slack_msg_id slack-msg-id))++(defn assistant-messages-by-slack-ids+ "The non-deleted assistant MetabotMessages of `conversation-id` posted as one of `slack-msg-ids`."+ [conversation-id slack-msg-ids]+ (t2/select :model/MetabotMessage+ :conversation_id conversation-id+ :role "assistant"+ :deleted_at nil+ :slack_msg_id [:in slack-msg-ids]))++(defn deleted-assistant-slack-msg-ids+ "The Slack message ids among `slack-msg-ids` of deleted assistant MetabotMessages of `conversation-id`."+ [conversation-id slack-msg-ids]+ (t2/select-fn-set :slack_msg_id+ :model/MetabotMessage+ :conversation_id conversation-id+ :role "assistant"+ :deleted_at [:not= nil]+ :slack_msg_id [:in slack-msg-ids]))++(defn assistant-state-messages+ "The id, role, state, error, and finished flag of the non-deleted assistant MetabotMessages of `conversation-id`,+ oldest first."+ [conversation-id]+ (t2/select [:model/MetabotMessage :id :role :state :error :finished]+ :conversation_id conversation-id+ :role "assistant"+ :deleted_at nil+ {:order-by [[:created_at :asc] [:id :asc]]}))++(defn assistant-response-user-id+ "The id of the User who triggered the assistant MetabotMessage posted to `channel-id` as `slack-msg-id`, or nil."+ [channel-id slack-msg-id]+ (t2/select-one-fn :user_id+ :model/MetabotMessage+ :channel_id channel-id+ :slack_msg_id slack-msg-id+ :role "assistant"))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))diff --git a/src/metabase/slackbot/persistence.clj b/src/metabase/slackbot/persistence.cljindex 21b5b99104d..755f51b862e 100644--- a/src/metabase/slackbot/persistence.clj+++ b/src/metabase/slackbot/persistence.clj@@ -3,7 +3,7 @@(:require[metabase.metabot.persistence :as metabot.persistence][metabase.metabot.schema.v2 :as schema.v2]- [toucan2.core :as t2]))+ [metabase.slackbot.db :as slackbot.db]))(set! *warn-on-reflection* true)@@ -22,11 +22,7 @@Only [[metabase.metabot.persistence/replayable-assistant-row?]] rows contribute."[conversation-id slack-msg-ids](when (seq slack-msg-ids)- (->> (t2/select :model/MetabotMessage- :conversation_id conversation-id- :role "assistant"- :deleted_at nil- :slack_msg_id [:in slack-msg-ids])+ (->> (slackbot.db/assistant-messages-by-slack-ids conversation-id slack-msg-ids);; A failed turn's state is dropped by [[metabase.metabot.persistence/conversation-state]], so;; replaying its tool calls would announce queries the seeded state does not contain.(filter metabot.persistence/replayable-assistant-row?)@@ -39,12 +35,7 @@"Slack message ids for assistant responses that were soft-deleted."[conversation-id slack-msg-ids](when (seq slack-msg-ids)- (t2/select-fn-set :slack_msg_id- :model/MetabotMessage- :conversation_id conversation-id- :role "assistant"- :deleted_at [:not= nil]- :slack_msg_id [:in slack-msg-ids])))+ (slackbot.db/deleted-assistant-slack-msg-ids conversation-id slack-msg-ids)))(defn state-messages"The assistant rows of a Slack thread in reader order, for feeding@@ -54,21 +45,13 @@`data` blobs aren't loaded just to get at `state`. Not usable for history replay —see [[message-history]] for that."[conversation-id]- (t2/select [:model/MetabotMessage :id :role :state :error :finished]- :conversation_id conversation-id- :role "assistant"- :deleted_at nil- {:order-by [[:created_at :asc] [:id :asc]]}))+ (slackbot.db/assistant-state-messages conversation-id))(defn response-owner-user-id"Find the Metabase user ID who triggered the assistant response for this Slack channel/message.Returns nil when the message is not tracked."[channel-id slack-msg-id]- (t2/select-one-fn :user_id- :model/MetabotMessage- :channel_id channel-id- :slack_msg_id slack-msg-id- :role "assistant"))+ (slackbot.db/assistant-response-user-id channel-id slack-msg-id))(defn soft-delete-response!"Mark the stored assistant response for this Slack channel/message as soft-deleted."diff --git a/src/metabase/slackbot/query.clj b/src/metabase/slackbot/query.cljindex 60b588c2340..e42d2719c03 100644--- a/src/metabase/slackbot/query.clj+++ b/src/metabase/slackbot/query.clj@@ -8,8 +8,8 @@[metabase.query-processor.core :as qp][metabase.query-processor.middleware.permissions :as qp.perms][metabase.query-processor.schema :as qp.schema]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.slackbot.db :as slackbot.db]+ [metabase.util :as u]))(set! *warn-on-reflection* true)@@ -263,7 +263,7 @@- `table` and display types not supported by static viz render as native Slack table blocks- static viz chart types render as PNG"[card-id]- (let [card (t2/select-one :model/Card :id card-id)+ (let [card (slackbot.db/card card-id)_ (when-not card(throw (ex-info "Card not found" {:card-id card-id :type :card-not-found})))card-name (:name card)diff --git a/src/metabase/slackbot/uploads.clj b/src/metabase/slackbot/uploads.cljindex 3a675bb77e8..900ef0e8989 100644--- a/src/metabase/slackbot/uploads.clj+++ b/src/metabase/slackbot/uploads.clj@@ -6,9 +6,9 @@[metabase.analytics-interface.core :as analytics][metabase.channel.settings :as channel.settings][metabase.slackbot.client :as slackbot.client]+ [metabase.slackbot.db :as slackbot.db][metabase.upload.core :as upload]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -115,7 +115,7 @@[files](when (seq files)(if-let [{:keys [db_id schema_name] :as settings} (upload-settings)]- (let [db (t2/select-one :model/Database :id db_id)]+ (let [db (slackbot.db/database db_id)](if-not (upload/can-create-upload? db schema_name){:error "You don't have permission to upload files. Contact your Metabase administrator."}(let [result (process-file-uploads settings files)]diff --git a/src/metabase/sql_tools/common.clj b/src/metabase/sql_tools/common.cljindex cf933c28b81..36f7040bc29 100644--- a/src/metabase/sql_tools/common.clj+++ b/src/metabase/sql_tools/common.clj@@ -6,11 +6,10 @@[metabase.driver.sql.normalize :as sql.normalize][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.sql-tools.db :as sql-tools.db][metabase.sql-tools.interface :as sql-tools]- [metabase.util :as u][metabase.util.humanization :as u.humanization]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(defn normalize-name"Normalize a name by per driver rules."@@ -35,21 +34,10 @@`normalize-unquoted-name` is a pure case fold; both have tests."[database-id :- pos-int?table-names :- [:sequential :string]]- (if-let [names (not-empty (into #{} (map u/lower-case-en) table-names))]+ (if (seq table-names);; `set` because `select-pks-set` answers `nil`, not `#{}`, when nothing matches — which is the common case of a;; query naming a table that does not exist.- (set (t2/select-pks-set :model/Table- {:where [:and- [:= :db_id database-id]- ;; `lower()` cannot use an index on the name column, but it still beats fetching every- ;; row for the Database.- [:in [:lower :name] names]- ;; Mirrors the Table filter the MetadataProvider applies to an unfiltered fetch; an- ;; `:id` lookup does not apply it, so it has to happen here.- [:= :active true]- [:or- [:= :visibility_type nil]- [:not-in :visibility_type ["hidden" "technical" "cruft"]]]]}))+ (set (sql-tools.db/active-visible-table-ids-by-name database-id table-names))#{}))(defn find-table-or-transformdiff --git a/src/metabase/sql_tools/db.clj b/src/metabase/sql_tools/db.cljnew file mode 100644index 00000000000..3c50e341405--- /dev/null+++ b/src/metabase/sql_tools/db.clj@@ -0,0 +1,23 @@+(ns metabase.sql-tools.db+ "Application database queries for the SQL tools module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn active-visible-table-ids-by-name+ "Ids of the active, non-hidden Tables of Database `database-id` whose name case-insensitively matches one of+ `table-names`, or nil."+ [database-id table-names]+ (t2/select-pks-set :model/Table+ {:where [:and+ [:= :db_id database-id]+ ;; `lower()` cannot use an index on the name column, but it still beats fetching every+ ;; row for the Database.+ [:in [:lower :name] (into #{} (map u/lower-case-en) table-names)]+ ;; Mirrors the Table filter the MetadataProvider applies to an unfiltered fetch; an+ ;; `:id` lookup does not apply it, so it has to happen here.+ [:= :active true]+ [:or+ [:= :visibility_type nil]+ [:not-in :visibility_type ["hidden" "technical" "cruft"]]]]}))diff --git a/src/metabase/sso/common.clj b/src/metabase/sso/common.cljindex ae2e7dbea66..d113a0e8dc1 100644--- a/src/metabase/sso/common.clj+++ b/src/metabase/sso/common.clj@@ -4,9 +4,9 @@[clojure.data :as data][clojure.set :as set][metabase.permissions.core :as perms]+ [metabase.sso.db :as sso.db][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(defn- excluded-group-ids[]@@ -47,23 +47,14 @@"Update the PermissionsGroups a User belongs to, adding or deleting membership entries as needed so that Users isonly in `new-groups-or-ids`. Ignores special groups like `all-users`, and only optionally only touches groups with mappings set."([user-or-id new-groups-or-ids]- (let [current-group-ids (t2/select-fn-set :group_id :model/PermissionsGroupMembership- {:where- [:and- [:= :user_id (u/the-id user-or-id)]- [:not-in :group_id (excluded-group-ids)]]})+ (let [current-group-ids (sso.db/user-group-ids-excluding (u/the-id user-or-id) (excluded-group-ids))[to-remove to-add] (data/diff current-group-ids (set/difference (set (map u/the-id new-groups-or-ids))(excluded-group-ids)))](sync-group-memberships*! user-or-id to-remove to-add)))([user-or-id new-groups-or-ids mapped-groups-or-ids](let [mapped-group-ids (set (map u/the-id mapped-groups-or-ids))current-group-ids (when (seq mapped-group-ids)- (t2/select-fn-set :group_id :model/PermissionsGroupMembership- {:where- [:and- [:= :user_id (u/the-id user-or-id)]- [:in :group_id mapped-group-ids]- [:not-in :group_id (excluded-group-ids)]]}))+ (sso.db/user-group-ids-among (u/the-id user-or-id) mapped-group-ids (excluded-group-ids)))new-group-ids (-> (set (map u/the-id new-groups-or-ids))(set/intersection mapped-group-ids)(set/difference (excluded-group-ids)))diff --git a/src/metabase/sso/db.clj b/src/metabase/sso/db.cljnew file mode 100644index 00000000000..3627b57c076--- /dev/null+++ b/src/metabase/sso/db.clj@@ -0,0 +1,38 @@+(ns metabase.sso.db+ "Application database queries for the SSO module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself."+ (:require+ [toucan2.core :as t2]))++(defn user-group-ids-excluding+ "The ids of the PermissionsGroups the User with `user-id` belongs to, other than `excluded-group-ids`."+ [user-id excluded-group-ids]+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership+ {:where [:and+ [:= :user_id user-id]+ [:not-in :group_id excluded-group-ids]]}))++(defn user-group-ids-among+ "The ids among `group-ids` of the PermissionsGroups the User with `user-id` belongs to, other than+ `excluded-group-ids`."+ [user-id group-ids excluded-group-ids]+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership+ {:where [:and+ [:= :user_id user-id]+ [:in :group_id group-ids]+ [:not-in :group_id excluded-group-ids]]}))++(defn auth-identity-exists?+ "Whether the User with `user-id` has an AuthIdentity for `provider`."+ [user-id provider]+ (t2/exists? :model/AuthIdentity :user_id user-id :provider provider))++(defn insert-auth-identity!+ "Insert an AuthIdentity linking the User with `user-id` to `provider-id` at `provider`."+ [user-id provider provider-id]+ (t2/insert! :model/AuthIdentity {:user_id user-id, :provider provider, :provider_id provider-id}))++(defn set-auth-identity-metadata!+ "Set the `metadata` of the AuthIdentity of the User with `user-id` at `provider`."+ [user-id provider metadata]+ (t2/update! :model/AuthIdentity {:user_id user-id, :provider provider} {:metadata metadata}))diff --git a/src/metabase/sso/providers/slack_connect.clj b/src/metabase/sso/providers/slack_connect.cljindex 86763552a94..2a360e715d7 100644--- a/src/metabase/sso/providers/slack_connect.clj+++ b/src/metabase/sso/providers/slack_connect.clj@@ -4,10 +4,10 @@(:require[metabase.auth-identity.core :as auth-identity][metabase.server.settings :as server.settings]+ [metabase.sso.db :as sso.db][metabase.sso.settings :as sso-settings][metabase.util.i18n :refer [tru]]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(set! *warn-on-reflection* true)@@ -147,13 +147,8 @@Used in link-only mode where we don't create users or sessions."[user-id provider-id](when (and user-id provider-id)- (when-not (t2/exists? :model/AuthIdentity- :user_id user-id- :provider provider-name)- (t2/insert! :model/AuthIdentity- {:user_id user-id- :provider provider-name- :provider_id provider-id}))))+ (when-not (sso.db/auth-identity-exists? user-id provider-name)+ (sso.db/insert-auth-identity! user-id provider-name provider-id))))(methodical/defmethod auth-identity/login! :provider/slack-connect[provider {:keys [user authenticated-user user-data] :as request}]@@ -175,9 +170,8 @@(when (:success? result)(when-let [user-id (or (some-> result :user :id)(some-> result :authenticated-user deref :id))]- (t2/update! :model/AuthIdentity- {:user_id user-id :provider provider-name}- {:metadata {:signing_secret_version (server.settings/slack-connect-signing-secret-version)}})))+ (sso.db/set-auth-identity-metadata! user-id provider-name+ {:signing_secret_version (server.settings/slack-connect-signing-secret-version)})))(if (= sso-settings/slack-connect-auth-mode-link-only (sso-settings/slack-connect-authentication-mode))(dissoc result :user)result))diff --git a/src/metabase/sync/analyze.clj b/src/metabase/sync/analyze.cljindex b313710c636..e40eb4490db 100644--- a/src/metabase/sync/analyze.clj+++ b/src/metabase/sync/analyze.clj@@ -7,12 +7,12 @@[metabase.sync.analyze.classify :as classify][metabase.sync.analyze.fingerprint :as sync.fingerprint][metabase.sync.analyze.interestingness :as sync.interestingness]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.util :as sync-util][metabase.util :as u][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]));; How does analysis decide which Fields should get analyzed?;;@@ -55,21 +55,12 @@(mu/defn- update-fields-last-analyzed!"Update the `last_analyzed` date for all the recently re-fingerprinted/re-classified Fields in `table`."[table :- i/TableInstance]- (t2/update! :model/Field- (merge (sync.fingerprint/incomplete-analysis-kvs)- {:table_id (:id table)})- {:last_analyzed :%now}))+ (sync.db/mark-incomplete-fields-analyzed-for-table! (:id table) i/*latest-fingerprint-version*))(mu/defn- update-fields-last-analyzed-for-db!"Update the `last_analyzed` date for all the recently re-fingerprinted/re-classified Fields in `database`."[database :- i/DatabaseInstance]- (t2/update! :model/Field- (merge (sync.fingerprint/incomplete-analysis-kvs)- {:table_id [:in ^:allow-subquery- {:select [:id]- :from [(t2/table-name :model/Table)]- :where [:and sync-util/sync-tables-clause [:= :db_id (:id database)]]}]})- {:last_analyzed :%now}))+ (sync.db/mark-incomplete-fields-analyzed-for-database! (:id database) i/*latest-fingerprint-version*))(mu/defn analyze-table!"Perform in-depth analysis for a `table`."diff --git a/src/metabase/sync/analyze/classify.clj b/src/metabase/sync/analyze/classify.cljindex 9ee042991e1..f648020ebd1 100644--- a/src/metabase/sync/analyze/classify.clj+++ b/src/metabase/sync/analyze/classify.clj@@ -24,14 +24,13 @@[metabase.models.interface :as mi];; legacy usage -- don't do things like this going forward^{:clj-kondo/ignore [:deprecated-namespace :discouraged-namespace]} [metabase.query-processor.store :as qp.store]- [metabase.sync.analyze.fingerprint :as sync.fingerprint]+ [metabase.sync.db :as sync.db][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]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]));;; +----------------------------------------------------------------------------------------------------------------+;;; | CLASSIFYING INDIVIDUAL FIELDS |@@ -65,8 +64,9 @@(throw (Exception. (format "Classifiers are not allowed to set the value of %s." k)))));; cool, now we should be ok to update the model(when values-to-set- (t2/update! (mi/model original-model) (u/the-id original-model)- values-to-set)+ (case (mi/model original-model)+ :model/Field (sync.db/update-field! (u/the-id original-model) values-to-set)+ :model/Table (sync.db/update-table! (u/the-id original-model) values-to-set))true)))(mu/defn- classify!@@ -77,7 +77,7 @@(or (:fingerprint field)(when (qp.store/initialized?)(:fingerprint (lib.metadata/field (qp.store/metadata-provider) (u/the-id field))))- (t2/select-one-fn :fingerprint :model/Field :id (u/the-id field)))))+ (sync.db/field-fingerprint (u/the-id field)))))([field :- i/FieldInstance{:keys [exists-name]}@@ -101,11 +101,7 @@"Return a sequences of Fields belonging to `table` for which we should attempt to determine semantic type. Thisshould include Fields that have the latest fingerprint, but have not yet *completed* analysis."[table :- i/TableInstance]- (seq (apply t2/select :model/Field- :table_id (u/the-id table)- :active true- :visibility_type [:not-in ["sensitive" "retired"]]- (reduce concat [] (sync.fingerprint/incomplete-analysis-kvs)))))+ (seq (sync.db/incomplete-analysis-fields-for-table (u/the-id table) i/*latest-fingerprint-version*)))(mu/defn classify-fields!"Run various classifiers on the appropriate `fields` in a `table` that have not been previously analyzed. These do@@ -114,11 +110,7 @@(tracing/with-span :sync "sync.classify.fields" {:sync/table (:name table)}(let [table-id (:id table)](when-let [fields (fields-to-classify table)]- (let [existing-name-field (t2/count :model/Field- :table_id table-id- :active true- :visibility_type [:not-in ["sensitive" "retired"]]- :semantic_type :type/Name)+ (let [existing-name-field (sync.db/name-field-count-for-table table-id){:keys [fields-failed]}(reduce (fn [state field](let [result (classify! field state)]diff --git a/src/metabase/sync/analyze/fingerprint.clj b/src/metabase/sync/analyze/fingerprint.cljindex 5515efa8002..c15d67b893c 100644--- a/src/metabase/sync/analyze/fingerprint.clj+++ b/src/metabase/sync/analyze/fingerprint.clj@@ -9,6 +9,7 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.lib.schema.metadata.fingerprint :as lib.schema.metadata.fingerprint]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.settings :as sync.settings][metabase.sync.util :as sync-util]@@ -20,8 +21,7 @@[metabase.util.malli.schema :as ms][metabase.warehouse-schema.models.field :as field][metabase.warehouse-schema.models.table :as table]- [redux.core :as redux]- [toucan2.core :as t2]))+ [redux.core :as redux]))(defn incomplete-analysis-kvs"Key-value pairs corresponding to the state of Fields that have the latest fingerprint, but have not yet@@ -37,7 +37,7 @@[field :- i/FieldInstancefingerprint :- [:maybe ::lib.schema.metadata.fingerprint/fingerprint]](log/debugf "Saving fingerprint for %s" (sync-util/name-for-logging field))- (t2/update! :model/Field (u/the-id field) (merge (incomplete-analysis-kvs) {:fingerprint fingerprint})))+ (sync.db/update-field! (u/the-id field) (merge (incomplete-analysis-kvs) {:fingerprint fingerprint})))(mu/defn- mark-fingerprinting-failed!"Advance `fingerprint_version` to the latest version for `fields` without saving a fingerprint. Called when@@ -46,7 +46,7 @@left untouched so they are retried."[fields :- [:maybe [:sequential i/FieldInstance]]](when-let [ids (seq (map u/the-id fields))]- (t2/update! :model/Field :id [:in ids] {:fingerprint_version i/*latest-fingerprint-version*})))+ (sync.db/set-fields-fingerprint-version! ids i/*latest-fingerprint-version*)))(mr/def ::FingerprintStats[:map@@ -202,10 +202,7 @@id so the selection is stable across syncs. This should include NEW fields that are active and visible."[table :- i/TableInstancelimit :- ms/PositiveInt]- (seq (t2/select :model/Field- (assoc (honeysql-for-fields-that-need-fingerprint-updating table)- :order-by [[:id :asc]]- :limit limit))))+ (seq (sync.db/fields-where (:where (honeysql-for-fields-that-need-fingerprint-updating table)) limit)))(mu/defn- warn-too-many-fields!"Log that `table` has more fields to fingerprint than fingerprint-max-fields-per-table (`limit`), so only the firstdiff --git a/src/metabase/sync/analyze/interestingness.clj b/src/metabase/sync/analyze/interestingness.cljindex 4e864173635..f7fb88bea4e 100644--- a/src/metabase/sync/analyze/interestingness.clj+++ b/src/metabase/sync/analyze/interestingness.clj@@ -10,13 +10,12 @@outside the normal sync sweep, or scores null'ed to force a recompute)."(:require[metabase.interestingness.core :as interestingness]- [metabase.sync.analyze.fingerprint :as sync.fingerprint]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.util :as sync-util][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [toucan2.core :as t2][toucan2.realize :as t2.realize]))(set! *warn-on-reflection* true)@@ -26,17 +25,12 @@[field :- i/FieldInstance](sync-util/with-error-handling (format "Error scoring interestingness for %s" (sync-util/name-for-logging field))(let [dim-score (interestingness/dimension-interestingness field)]- (t2/update! :model/Field (u/the-id field)- {:dimension_interestingness dim-score}))))+ (sync.db/update-field! (u/the-id field) {:dimension_interestingness dim-score}))))(mu/defn- fields-to-score :- [:maybe [:sequential i/FieldInstance]]"Return Fields in `table` with fresh fingerprints that haven't completed analysis yet."[table :- i/TableInstance]- (seq (apply t2/select :model/Field- :table_id (u/the-id table)- :active true- :visibility_type [:not-in ["sensitive" "retired"]]- (reduce concat [] (sync.fingerprint/incomplete-analysis-kvs)))))+ (seq (sync.db/incomplete-analysis-fields-for-table (u/the-id table) i/*latest-fingerprint-version*)))(mu/defn score-fields!"Score interestingness for all qualifying Fields in `table`."@@ -80,14 +74,7 @@(update stats :fields-failed inc))(update stats :fields-scored inc))))){:fields-scored 0 :fields-failed 0}- (t2/reducible-select :model/Field- {:where [:and- [:= :active true]- [:= :dimension_interestingness nil]- [:not-in :visibility_type ["sensitive" "retired"]]- [:in :table_id ^:allow-subquery {:select [:id]- :from [(t2/table-name :model/Table)]- :where [:= :db_id (u/the-id database)]}]]})))+ (sync.db/unscored-fields-for-database-reducible (u/the-id database))))(mu/defn score-fields-for-db!"Score interestingness for all qualifying Fields in `database`."diff --git a/src/metabase/sync/api/notify.clj b/src/metabase/sync/api/notify.cljindex eba73e9f732..968d0747136 100644--- a/src/metabase/sync/api/notify.clj+++ b/src/metabase/sync/api/notify.clj@@ -7,12 +7,12 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.sync.core :as sync]+ [metabase.sync.db :as sync.db][metabase.sync.sync-metadata :as sync-metadata][metabase.sync.sync-metadata.tables :as sync-tables][metabase.sync.util :as sync-util][metabase.util.i18n :refer [trs]]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)@@ -38,10 +38,10 @@(let [schema? (when scan (#{"schema" :schema} scan))table-sync-fn (if schema? sync-metadata/sync-table-metadata! sync/sync-table!)db-sync-fn (if schema? sync-metadata/sync-db-metadata! sync/sync-database!)]- (api/let-404 [database (t2/select-one :model/Database :id id)]+ (api/let-404 [database (sync.db/database id)](let [table (cond- table_id (api/check-404 (t2/select-one :model/Table :db_id id, :id (int table_id)))- table_name (api/check-404 (t2/select-one :model/Table :db_id id, :name table_name)))]+ table_id (api/check-404 (sync.db/table-in-database id (int table_id)))+ table_name (api/check-404 (sync.db/table-by-name id table_name)))](cond-> (future (if table(table-sync-fn table)(db-sync-fn database)))@@ -88,11 +88,11 @@[:table_name {:optional true} [:maybe ms/NonBlankString]][:schema_name {:optional true} [:maybe string?]][:synchronous? {:default false} [:maybe ms/BooleanValue]]]]- (api/let-404 [database (t2/select-one :model/Database :is_attached_dwh true)]+ (api/let-404 [database (sync.db/attached-dwh-database)](if (str/blank? table_name)(cond-> (future (sync-metadata/sync-db-metadata! database))synchronous? deref)- (if-let [table (t2/select-one :model/Table :db_id (:id database), :name table_name :schema schema_name)]+ (if-let [table (sync.db/table-by-schema-and-name (:id database) schema_name table_name)](cond-> (future (sync-metadata/sync-table-metadata! table))synchronous? deref);; find and sync is always synchronous. And we want it to be so since the "can't find this table" error is@@ -113,8 +113,8 @@{:keys [schema_name table_name]} :- [:map[:schema_name ms/NonBlankString][:table_name ms/NonBlankString]]]- (api/let-404 [database (t2/select-one :model/Database :id id)]- (if-not (t2/select-one :model/Table :db_id id :name table_name :schema schema_name)+ (api/let-404 [database (sync.db/database id)]+ (if-not (sync.db/table-by-schema-and-name id schema_name table_name)(find-and-sync-new-table database table_name schema_name)(throw (without-stacktrace(ex-info (trs "Table ''{0}.{1}'' already exists"diff --git a/src/metabase/sync/db.clj b/src/metabase/sync/db.cljnew file mode 100644index 00000000000..43622ed757d--- /dev/null+++ b/src/metabase/sync/db.clj@@ -0,0 +1,399 @@+(ns metabase.sync.db+ "Application database queries for the sync module. Every function here is a direct Toucan 2 call with no additional+ logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [metabase.warehouse-schema.models.table :as table]+ [toucan2.core :as t2]))++(def ^:private sync-tables-clause+ "Honey SQL clause selecting the Tables that take part in sync: active and not hidden."+ [:and [:= :active true] [:= :visibility_type nil]])++;;; ------------------------------------------------ Database ------------------------------------------------++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn attached-dwh-database+ "The attached data warehouse Database, or nil."+ []+ (t2/select-one :model/Database :is_attached_dwh true))++(defn database-stub?+ "Whether the Database with `database-id` is a stub."+ [database-id]+ (t2/select-one-fn :is_stub :model/Database :id database-id))++(defn database-on-demand-flags+ "A map of Database ID to its `:is_on_demand` flag for `database-ids`."+ [database-ids]+ (t2/select-pk->fn :is_on_demand :model/Database :id [:in database-ids]))++(defn synced-user-database-exists?+ "Whether any non-sample, non-audit Database has completed its initial sync."+ []+ (t2/exists? :model/Database :is_sample false :is_audit false :initial_sync_status "complete"))++(defn databases-with-schedules-reducible+ "Reducible raw Database rows whose sync schedules are the sample or default ones."+ [old-sample-metadata-cron metadata-crons cache-field-values-crons]+ (t2/reducible-query {:select [:*]+ :from [:metabase_database]+ :where [:or+ [:and+ [:= :is_sample true]+ [:= :metadata_sync_schedule old-sample-metadata-cron]]+ [:in :metadata_sync_schedule metadata-crons]+ [:in :cache_field_values_schedule cache-field-values-crons]]}))++(defn update-database!+ "Apply `changes` to the Database with `database-id`."+ [database-id changes]+ (t2/update! :model/Database database-id changes))++;;; ------------------------------------------------- Table -------------------------------------------------++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn table-in-database+ "The Table with `table-id` in the Database with `database-id`, or nil."+ [database-id table-id]+ (t2/select-one :model/Table :db_id database-id :id table-id))++(defn table-by-name+ "The Table named `table-name` in the Database with `database-id`, or nil."+ [database-id table-name]+ (t2/select-one :model/Table :db_id database-id :name table-name))++(defn table-by-schema-and-name+ "The Table named `table-name` in `schema` of the Database with `database-id`, or nil."+ [database-id schema table-name]+ (t2/select-one :model/Table :db_id database-id :name table-name :schema schema))++(defn inactive-table-by-schema-and-name+ "The inactive Table named `table-name` in `schema` of the Database with `database-id`, or nil."+ [database-id schema table-name]+ (t2/select-one :model/Table :db_id database-id :schema schema :name table-name :active false))++(defn active-table-id-by-name+ "The ID of the active Table named `table-name` in the Database with `database-id`, or nil."+ [database-id table-name]+ (t2/select-one-pk :model/Table :db_id database-id :name table-name :active true))++(defn sync-tables-by-lower-name-and-schema+ "The synced Tables of the Database with `database-id` whose lower-cased name and schema match."+ [database-id lower-name lower-schema]+ (t2/select :model/Table+ :db_id database-id+ :%lower.name lower-name+ :%lower.schema lower-schema+ {:where sync-tables-clause}))++(defn tables-by-name+ "The `columns` of the Tables of the Database with `database-id` named one of `table-names`."+ [columns database-id table-names]+ (t2/select columns :db_id database-id :name [:in table-names]))++(defn tables-to-archive+ "The inactive, unarchived, non-transform-target Tables of the Database with `database-id` deactivated before the+ SQL expression `deactivated-before`."+ [database-id deactivated-before]+ (t2/select :model/Table+ :db_id database-id+ :active false+ :archived_at nil+ :transform_target false+ :deactivated_at [:< deactivated-before]))++(defn table-database-ids+ "A map of Table ID to Database ID for `table-ids`."+ [table-ids]+ (t2/select-pk->fn :db_id :model/Table :id [:in table-ids]))++(defn table-schemas-reducible+ "Reducible `:schema` rows of the Tables of the Database with `database-id`."+ [database-id]+ (t2/reducible-select [:model/Table :schema] :db_id database-id))++(defn active-table-ids-reducible+ "Reducible `:id` rows of the active Tables of the Database with `database-id`."+ [database-id]+ (t2/reducible-select [:model/Table :id] :db_id database-id :active true))++(defn active-table-count+ "The number of active Tables in the Database with `database-id`."+ [database-id]+ (t2/count :model/Table :db_id database-id :active true))++(defn sync-table-ids+ "The IDs of the synced Tables of the Database with `database-id`."+ [database-id]+ (t2/select-fn-vec :id :model/Table :db_id database-id {:where sync-tables-clause}))++(defn sync-table-schemas+ "The distinct `:schema` rows of the synced Tables of the Database with `database-id`."+ [database-id]+ (t2/query {:select-distinct [:schema]+ :from [:metabase_table]+ :where [:and sync-tables-clause [:= :db_id database-id]]}))++(defn sync-tables-count+ "The number of synced Tables in the Database with `database-id`."+ [database-id]+ (t2/count :model/Table :db_id database-id {:where sync-tables-clause}))++(defn sync-tables-reducible+ "Reducible synced Tables of the Database with `database-id` ordered by schema and name, optionally narrowed to+ `schema-names` and/or `table-names`."+ [database-id schema-names table-names]+ (t2/reducible-select :model/Table+ :db_id database-id+ {:where [:and sync-tables-clause+ (when (seq schema-names) [:in :schema schema-names])+ (when (seq table-names) [:in :name table-names])]+ :order-by [[:schema :asc] [:name :asc]]}))++(defn sync-tables-by-earliest-analyzed-reducible+ "Reducible synced Tables of the Database with `database-id` ordered by the earliest `last_analyzed` of their Fields."+ [database-id]+ (t2/reducible-select :model/Table+ {:select [:t.*]+ :from [[(t2/table-name :model/Table) :t]]+ :left-join [[^:allow-subquery {:select [:table_id+ [[:min :last_analyzed] :earliest_last_analyzed]]+ :from [(t2/table-name :model/Field)]+ :group-by [:table_id]} :sub]+ [:= :t.id :sub.table_id]]+ :where [:and sync-tables-clause [:= :t.db_id database-id]]+ :order-by [[:sub.earliest_last_analyzed :asc]]}))++(defn insert-table!+ "Insert `table` and return the new instance."+ [table]+ (t2/insert-returning-instance! :model/Table table))++(defn update-table!+ "Apply `changes` to the Table with `table-id`."+ [table-id changes]+ (t2/update! :model/Table table-id changes))++(defn update-tables!+ "Apply `changes` to the Tables with `table-ids`."+ [table-ids changes]+ (t2/update! :model/Table :id [:in table-ids] changes))++(defn deactivate-tables!+ "Mark the active Tables among `table-ids` inactive."+ [table-ids]+ (t2/update! :model/Table {:id [:in table-ids] :active true} {:active false}))++(defn rename-table-schema!+ "Move the Tables of the Database with `database-id` from `schema` to `new-schema`."+ [database-id schema new-schema]+ (t2/update! :model/Table :db_id database-id :schema schema {:schema new-schema}))++(defn archive-inactive-table!+ "Archive the inactive Table with `table-id` at `archived-at` under `new-name`, returning the number of rows updated."+ [table-id archived-at new-name]+ (t2/update! :model/Table {:id table-id :active false} {:archived_at archived-at :name new-name}))++;;; ------------------------------------------------- Field -------------------------------------------------++(defn fields+ "The Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field :id [:in field-ids]))++(defn fields-for-field-values+ "The columns needed to scan FieldValues of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :name :id :base_type :effective_type :coercion_strategy :semantic_type :visibility_type+ :table_id :has_field_values]+ :id [:in field-ids]))++(defn fields-where+ "Up to `limit` Fields matching the Honey SQL `where`, ordered by ID."+ [where limit]+ (t2/select :model/Field {:where where, :order-by [[:id :asc]], :limit limit}))++(defn field-fingerprint+ "The fingerprint of the Field with `field-id`."+ [field-id]+ (t2/select-one-fn :fingerprint :model/Field :id field-id))++(defn active-fields-metadata-for-table+ "The sync metadata columns of the active Fields of the Table with `table-id`, in field order."+ [table-id]+ (t2/select [:model/Field :name :database_type :base_type :effective_type :coercion_strategy :semantic_type+ :parent_id :id :description :database_position :nfc_path+ :database_is_auto_increment :database_required+ :database_default :database_is_generated :database_is_nullable :database_is_pk+ :database_partitioned :json_unfolding :position :preview_display]+ :table_id table-id+ :active true+ {:order-by table/field-order-rule}))++(defn normal-fields-for-table+ "Up to `limit` active, normal-visibility Fields of the Table with `table-id`, ordered by ID."+ [table-id limit]+ (t2/select :model/Field+ :table_id table-id+ :active true+ :visibility_type "normal"+ {:order-by [[:id :asc]], :limit limit}))++(defn inactive-fields-by-lower-name+ "The inactive Fields of the Table with `table-id` under `parent-id` whose lower-cased name is one of `lower-names`."+ [table-id parent-id lower-names]+ (t2/select :model/Field+ :table_id table-id+ :%lower.name [:in lower-names]+ :parent_id parent-id+ :active false))++(defn incomplete-analysis-fields-for-table+ "The active, visible Fields of the Table with `table-id` fingerprinted at `fingerprint-version` but not yet analyzed."+ [table-id fingerprint-version]+ (t2/select :model/Field+ :table_id table-id+ :active true+ :visibility_type [:not-in ["sensitive" "retired"]]+ :fingerprint_version fingerprint-version+ :last_analyzed nil))++(defn name-field-count-for-table+ "The number of active, visible Fields of the Table with `table-id` whose semantic type is `:type/Name`."+ [table-id]+ (t2/count :model/Field+ :table_id table-id+ :active true+ :visibility_type [:not-in ["sensitive" "retired"]]+ :semantic_type :type/Name))++(defn unscored-fields-for-database-reducible+ "Reducible active, visible Fields of the Database with `database-id` without a dimension interestingness score."+ [database-id]+ (t2/reducible-select :model/Field+ {:where [:and+ [:= :active true]+ [:= :dimension_interestingness nil]+ [:not-in :visibility_type ["sensitive" "retired"]]+ [:in :table_id ^:allow-subquery {:select [:id]+ :from [(t2/table-name :model/Table)]+ :where [:= :db_id database-id]}]]}))++(defn top-level-field-ids-by-name+ "The IDs of the top-level Fields of the Table with `table-id` named one of `field-names`."+ [table-id field-names]+ (t2/select-pks-vec :model/Field :name [:in field-names] :table_id table-id :parent_id nil))++(defn top-level-field-ids-by-schema-table-and-name-reducible+ "Reducible `:id` rows of the top-level Fields of the Database with `database-id` matching one of the+ `[schema table-name field-name]` triples in `schema+table+names`, with a nil schema spelled `\"__null__\"`."+ [database-id schema+table+names]+ (t2/reducible-query {:select [[:f.id]]+ :from [[(t2/table-name :model/Field) :f]]+ :inner-join [[(t2/table-name :model/Table) :t] [:= :f.table_id :t.id]]+ :where [:and+ [:in [:composite [:coalesce :t.schema "__null__"] :t.name :f.name] schema+table+names]+ [:= :t.db_id database-id]+ [:= :parent_id nil]]}))++(defn indexed-field-ids-for-table+ "The IDs of the Fields of the Table with `table-id` marked as indexed."+ [table-id]+ (t2/select-pks-set :model/Field :table_id table-id :database_indexed true))++(defn indexed-top-level-field-ids-for-database+ "The IDs of the top-level Fields of the Database with `database-id` marked as indexed."+ [database-id]+ (t2/select-pks-set :model/Field+ :table_id [:in ^:allow-subquery {:select [[:t.id]]+ :from [[(t2/table-name :model/Table) :t]]+ :where [:= :t.db_id database-id]}]+ :parent_id nil+ :database_indexed true))++(defn insert-fields!+ "Insert the Field `rows` and return their IDs."+ [rows]+ (t2/insert-returning-pks! :model/Field rows))++(defn update-field!+ "Apply `changes` to the Field with `field-id`."+ [field-id changes]+ (t2/update! :model/Field field-id changes))++(defn update-field-by-name!+ "Apply `changes` to the Field named `field-name` of the Table with `table-id`."+ [table-id field-name changes]+ (t2/update! :model/Field {:name field-name, :table_id table-id} changes))++(defn reactivate-fields!+ "Mark the Fields with `field-ids` active."+ [field-ids]+ (t2/update! :model/Field {:id [:in field-ids]} {:active true}))++(defn set-fields-fingerprint-version!+ "Set the fingerprint version of the Fields with `field-ids` to `fingerprint-version`."+ [field-ids fingerprint-version]+ (t2/update! :model/Field :id [:in field-ids] {:fingerprint_version fingerprint-version}))++(defn set-table-fields-indexed!+ "Set `database_indexed` of the Fields of the Table with `table-id` to the SQL expression `indexed-expr`."+ [table-id indexed-expr]+ (t2/update! :model/Field {:table_id table-id} {:database_indexed indexed-expr}))++(defn set-top-level-fields-indexed!+ "Set `database_indexed` of the top-level Fields with `field-ids` to `indexed?`."+ [field-ids indexed?]+ (t2/update! :model/Field :parent_id nil :id [:in field-ids] {:database_indexed indexed?}))++(defn mark-incomplete-fields-analyzed-for-table!+ "Stamp `last_analyzed` on the Fields of the Table with `table-id` fingerprinted at `fingerprint-version` but not+ yet analyzed."+ [table-id fingerprint-version]+ (t2/update! :model/Field+ {:table_id table-id, :fingerprint_version fingerprint-version, :last_analyzed nil}+ {:last_analyzed :%now}))++(defn mark-incomplete-fields-analyzed-for-database!+ "Stamp `last_analyzed` on the Fields of the synced Tables of the Database with `database-id` fingerprinted at+ `fingerprint-version` but not yet analyzed."+ [database-id fingerprint-version]+ (t2/update! :model/Field+ {:fingerprint_version fingerprint-version+ :last_analyzed nil+ :table_id [:in ^:allow-subquery+ {:select [:id]+ :from [(t2/table-name :model/Table)]+ :where [:and sync-tables-clause [:= :db_id database-id]]}]}+ {:last_analyzed :%now}))++(defn execute-one!+ "Run the SQL statement `sql` and return its single result."+ [sql]+ (t2/query-one sql))++;;; ---------------------------------------------- FieldValues ----------------------------------------------++(defn field-values-exist?+ "Whether the Field with `field-id` has FieldValues."+ [field-id]+ (t2/exists? :model/FieldValues :field_id field-id))++(defn advanced-field-values-count-before+ "The number of FieldValues of `types` for the Field with `field-id` created before the SQL expression+ `created-before`."+ [field-id types created-before]+ (t2/count :model/FieldValues :field_id field-id :type [:in types] :created_at [:< created-before]))++(defn delete-advanced-field-values-before!+ "Delete the FieldValues of `types` for the Field with `field-id` created before the SQL expression `created-before`."+ [field-id types created-before]+ (t2/delete! :model/FieldValues :field_id field-id :type [:in types] :created_at [:< created-before]))diff --git a/src/metabase/sync/fetch_metadata.clj b/src/metabase/sync/fetch_metadata.cljindex c6ad7214805..605e9c960f0 100644--- a/src/metabase/sync/fetch_metadata.clj+++ b/src/metabase/sync/fetch_metadata.clj@@ -7,12 +7,12 @@[metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.lib-be.core :as lib-be]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.util :as sync-util][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.fn :as mu.fn]- [toucan2.core :as t2]))+ [metabase.util.malli.fn :as mu.fn]))(defmacro log-if-error"Logs an error message if an exception is thrown while executing the body."@@ -63,7 +63,7 @@(eduction(mapcat (fn [table-id](try- (let [table (t2/select-one :model/Table table-id)+ (let [table (sync.db/table table-id)table-fields (table-fields-metadata database table)];; Realize the fields from this table (from `table-fields-metadata`) immediately to ensure the;; connection is closed before moving to the next table.diff --git a/src/metabase/sync/field_values.clj b/src/metabase/sync/field_values.cljindex cb4ab9f3ea7..88148a61975 100644--- a/src/metabase/sync/field_values.clj+++ b/src/metabase/sync/field_values.clj@@ -5,6 +5,7 @@[metabase.app-db.core :as mdb][metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.settings :as sync.settings][metabase.sync.util :as sync-util]@@ -13,12 +14,11 @@[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]))+ [metabase.warehouse-schema.models.field-values :as field-values]))(mu/defn- clear-field-values-for-field![field :- i/FieldInstance]- (when (t2/exists? :model/FieldValues :field_id (u/the-id field))+ (when (sync.db/field-values-exist? (u/the-id field))(log/debug (format "Based on cardinality and/or type information, %s should no longer have field values.\n"(sync-util/name-for-logging field))"Deleting FieldValues...")@@ -37,9 +37,7 @@Bounding the count keeps wide tables (e.g. document databases with huge/dynamic schemas) from loading every Fieldinto memory and issuing a warehouse request per field."[table limit]- (t2/select :model/Field- :table_id (u/the-id table), :active true, :visibility_type "normal"- {:order-by [[:id :asc]] :limit limit}))+ (sync.db/normal-fields-for-table (u/the-id table) limit))(defn- warn-too-many-fields!"Log that `table` has more fields to scan for FieldValues than scan-max-fields-per-table (`limit`), so only the first@@ -62,7 +60,7 @@Tables that fail any check fall back to the per-field path."[table]- (let [database (t2/select-one :model/Database :id (:db_id table))+ (let [database (sync.db/database (:db_id table))engine (:engine database)](and (isa? driver/hierarchy engine :sql)(driver.u/supports? engine :nested-queries database)@@ -168,7 +166,7 @@(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)]+ (let [table (sync.db/table table-id)](sync-fields-for-table! table table-fields fvs-map))))(completing (partial merge-with +))empty-counts@@ -237,10 +235,9 @@[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]))+ (sync.db/table-database-ids 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))]))]+ (sync.db/database-on-demand-flags (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?)]))))@@ -260,9 +257,7 @@(->> 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])))))+ (sync.db/fields-for-field-values 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)@@ -273,15 +268,14 @@(defn- delete-expired-advanced-field-values-for-field)- (let [conditions [:field_id (:id field)- :type [:in field-values/advanced-field-values-types]- :created_at [:< ((requiring-resolve 'metabase.util.honey-sql-2/add-interval-honeysql-form)- (mdb/db-type)- :%now- (- (t/as field-values/advanced-field-values-max-age :days))- :day)]]- rows-count (apply t2/count :model/FieldValues conditions)]- (apply t2/delete! :model/FieldValues conditions)+ (let [types field-values/advanced-field-values-types+ cutoff ((requiring-resolve 'metabase.util.honey-sql-2/add-interval-honeysql-form)+ (mdb/db-type)+ :%now+ (- (t/as field-values/advanced-field-values-max-age :days))+ :day)+ rows-count (sync.db/advanced-field-values-count-before (:id field) types cutoff)]+ (sync.db/delete-advanced-field-values-before! (:id field) types cutoff)rows-count)))(mu/defn delete-expired-advanced-field-values-for-table!diff --git a/src/metabase/sync/settings.clj b/src/metabase/sync/settings.cljindex daf184cf8f6..feafda677c7 100644--- a/src/metabase/sync/settings.clj+++ b/src/metabase/sync/settings.clj@@ -1,16 +1,13 @@(ns metabase.sync.settings(:require[metabase.settings.core :as setting :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru]]- [toucan2.core :as t2]))+ [metabase.sync.db :as sync.db]+ [metabase.util.i18n :refer [deferred-tru]]))(defn- -show-database-syncing-modal [](let [v (setting/get-value-of-type :boolean :show-database-syncing-modal)](if (nil? v)- (not (t2/exists? :model/Database- :is_sample false- :is_audit false- :initial_sync_status "complete"))+ (not (sync.db/synced-user-database-exists?));; frontend should set this value to `true` after the modal has been shown oncev)))diff --git a/src/metabase/sync/sync_metadata/dbms_version.clj b/src/metabase/sync/sync_metadata/dbms_version.cljindex e8706eb381a..7dd220ba6c9 100644--- a/src/metabase/sync/sync_metadata/dbms_version.clj+++ b/src/metabase/sync/sync_metadata/dbms_version.clj@@ -2,10 +2,10 @@(:require[metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(def DBMSVersion"Schema for the expected output of [[sync-dbms-version!]]."@@ -18,5 +18,5 @@(let [driver (driver.u/database->driver database)version (driver/dbms-version driver database)](when (not= version (:dbms_version database))- (t2/update! :model/Database (:id database) {:dbms_version version}))+ (sync.db/update-database! (:id database) {:dbms_version version}))version))diff --git a/src/metabase/sync/sync_metadata/fields.clj b/src/metabase/sync/sync_metadata/fields.cljindex 247afdb3445..d2e3b445f31 100644--- a/src/metabase/sync/sync_metadata/fields.clj+++ b/src/metabase/sync/sync_metadata/fields.clj@@ -41,6 +41,7 @@(:require[metabase.driver.settings :as driver.settings][metabase.driver.util :as driver.u]+ [metabase.sync.db :as sync.db][metabase.sync.fetch-metadata :as fetch-metadata][metabase.sync.interface :as i][metabase.sync.sync-metadata.fields.our-metadata :as fields.our-metadata]@@ -51,7 +52,6 @@[metabase.util.malli :as mu][metabase.util.malli.schema :as ms][metabase.warehouse-schema.models.table :as table]- [toucan2.core :as t2][toucan2.util :as t2.util]));;; +----------------------------------------------------------------------------------------------------------------+@@ -127,11 +127,10 @@(partition-by (juxt :table-name :table-schema))(map (fn [table-metadata](let [{:keys [table-name table-schema]} (first table-metadata)- table (->> (t2/select :model/Table- :db_id (:id database)- :%lower.name (t2.util/lower-case-en table-name)- :%lower.schema (some-> table-schema t2.util/lower-case-en)- {:where sync-util/sync-tables-clause})+ table (->> (sync.db/sync-tables-by-lower-name-and-schema+ (:id database)+ (t2.util/lower-case-en table-name)+ (some-> table-schema t2.util/lower-case-en))(sort-by (select-best-matching-name table-schema table-name))first)updated (if tablediff --git a/src/metabase/sync/sync_metadata/fields/our_metadata.clj b/src/metabase/sync/sync_metadata/fields/our_metadata.cljindex 4d829f3a7af..8643f43a91f 100644--- a/src/metabase/sync/sync_metadata/fields/our_metadata.clj+++ b/src/metabase/sync/sync_metadata/fields/our_metadata.clj@@ -5,12 +5,11 @@comparing the differences in the two sets of Metadata."(:require[medley.core :as m]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.sync-metadata.fields.common :as common][metabase.util :as u]- [metabase.util.malli :as mu]- [metabase.warehouse-schema.models.table :as table]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]));;; +----------------------------------------------------------------------------------------------------------------+;;; | FETCHING OUR CURRENT METADATA |@@ -75,14 +74,7 @@(mu/defn- table->fields :- [:maybe [:sequential i/FieldInstance]]"Fetch active Fields from the Metabase application database for a given `table`."[table :- i/TableInstance]- (t2/select [:model/Field :name :database_type :base_type :effective_type :coercion_strategy :semantic_type- :parent_id :id :description :database_position :nfc_path- :database_is_auto_increment :database_required- :database_default :database_is_generated :database_is_nullable :database_is_pk- :database_partitioned :json_unfolding :position :preview_display]- :table_id (u/the-id table)- :active true- {:order-by table/field-order-rule}))+ (sync.db/active-fields-metadata-for-table (u/the-id table)))(mu/defn our-metadata :- [:set common/TableMetadataFieldWithID]"Return information we have about Fields for a `table` in the application database in (almost) exactly the samediff --git a/src/metabase/sync/sync_metadata/fields/sync_instances.clj b/src/metabase/sync/sync_metadata/fields/sync_instances.cljindex 8396e86b251..626b49e726e 100644--- a/src/metabase/sync/sync_metadata/fields/sync_instances.clj+++ b/src/metabase/sync/sync_metadata/fields/sync_instances.clj@@ -10,6 +10,7 @@[medley.core :as m][metabase.lib.schema.id :as lib.schema.id][metabase.models.humanization :as humanization]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.sync-metadata.fields.common :as common][metabase.sync.sync-metadata.fields.our-metadata :as fields.our-metadata]@@ -17,8 +18,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));;; +----------------------------------------------------------------------------------------------------------------+;;; | CREATING / REACTIVATING FIELDS |@@ -58,11 +58,7 @@new-field-metadatas :- [:maybe [:sequential i/TableMetadataField]]parent-id :- common/ParentID](when (seq new-field-metadatas)- (t2/select :model/Field- :table_id (u/the-id table)- :%lower.name [:in (map common/canonical-name new-field-metadatas)]- :parent_id parent-id- :active false)))+ (sync.db/inactive-fields-by-lower-name (u/the-id table) parent-id (map common/canonical-name new-field-metadatas))))(mu/defn- insert-new-fields! :- [:maybe [:sequential ::lib.schema.id/field]]"Insert new Field rows for for all the Fields described by `new-field-metadatas`. Returns IDs of newly inserted@@ -71,50 +67,50 @@new-field-metadatas :- [:maybe [:sequential i/TableMetadataField]]parent-id :- common/ParentID](when (seq new-field-metadatas)- (t2/insert-returning-pks! :model/Field- (for [{:keys [base-type coercion-strategy database-is-auto-increment database-partitioned database-position- database-is-generated database-is-nullable database-default pk?- database-required database-type effective-type field-comment json-unfolding nfc-path visibility-type]- field-name :name :as field} (sort-by :database-position new-field-metadatas)- :let [semantic-type (common/semantic-type field)- has-field-values (when (sync-util/can-be-list? base-type semantic-type)- :auto-list)]]- (do- (when (and effective-type- base-type- (not= effective-type base-type)- (nil? coercion-strategy))- (log/warn (u/format-color 'red- (str- "WARNING: Field `%s`: effective type `%s` provided but no coercion strategy provided."- " Using base-type: `%s`")- field-name- effective-type- base-type)))- {:table_id (u/the-id table)- :name field-name- :display_name (humanization/name->human-readable-name field-name)- :database_type (or database-type "NULL") ; placeholder for Fields w/ no type info (e.g. Mongo) & all NULL- :base_type base-type- ;; todo test this?- :effective_type (if (and effective-type coercion-strategy) effective-type base-type)- :coercion_strategy (when effective-type coercion-strategy)- :semantic_type semantic-type- :parent_id parent-id- :nfc_path nfc-path- :description field-comment- :position database-position- :database_position database-position- :json_unfolding (or json-unfolding false)- :database_is_auto_increment (or database-is-auto-increment false)- :database_is_generated database-is-generated- :database_is_nullable database-is-nullable- :database_is_pk pk?- :database_default database-default- :database_required (or database-required false)- :database_partitioned database-partitioned ;; nullable for database that doesn't support partitioned fields- :has_field_values has-field-values- :visibility_type (or visibility-type :normal)})))))+ (sync.db/insert-fields!+ (for [{:keys [base-type coercion-strategy database-is-auto-increment database-partitioned database-position+ database-is-generated database-is-nullable database-default pk?+ database-required database-type effective-type field-comment json-unfolding nfc-path visibility-type]+ field-name :name :as field} (sort-by :database-position new-field-metadatas)+ :let [semantic-type (common/semantic-type field)+ has-field-values (when (sync-util/can-be-list? base-type semantic-type)+ :auto-list)]]+ (do+ (when (and effective-type+ base-type+ (not= effective-type base-type)+ (nil? coercion-strategy))+ (log/warn (u/format-color 'red+ (str+ "WARNING: Field `%s`: effective type `%s` provided but no coercion strategy provided."+ " Using base-type: `%s`")+ field-name+ effective-type+ base-type)))+ {:table_id (u/the-id table)+ :name field-name+ :display_name (humanization/name->human-readable-name field-name)+ :database_type (or database-type "NULL") ; placeholder for Fields w/ no type info (e.g. Mongo) & all NULL+ :base_type base-type+ ;; todo test this?+ :effective_type (if (and effective-type coercion-strategy) effective-type base-type)+ :coercion_strategy (when effective-type coercion-strategy)+ :semantic_type semantic-type+ :parent_id parent-id+ :nfc_path nfc-path+ :description field-comment+ :position database-position+ :database_position database-position+ :json_unfolding (or json-unfolding false)+ :database_is_auto_increment (or database-is-auto-increment false)+ :database_is_generated database-is-generated+ :database_is_nullable database-is-nullable+ :database_is_pk pk?+ :database_default database-default+ :database_required (or database-required false)+ :database_partitioned database-partitioned ;; nullable for database that doesn't support partitioned fields+ :has_field_values has-field-values+ :visibility_type (or visibility-type :normal)})))))(mu/defn- create-or-reactivate-fields! :- [:maybe [:sequential i/FieldInstance]]"Create (or reactivate) Metabase Field object(s) for any Fields in `new-field-metadatas`. Does *NOT* recursively@@ -125,15 +121,14 @@(let [fields-to-reactivate (matching-inactive-fields table new-field-metadatas parent-id)];; if the fields already exist but were just marked inactive then reäctivate them(when (seq fields-to-reactivate)- (t2/update! :model/Field {:id [:in (map u/the-id fields-to-reactivate)]}- {:active true}))+ (sync.db/reactivate-fields! (map u/the-id fields-to-reactivate)))(let [reactivated? (comp (set (map common/canonical-name fields-to-reactivate))common/canonical-name);; If we reactivated the fields, no need to insert them; insert new rows for any that weren't reactivatednew-field-ids (insert-new-fields! table (remove reactivated? new-field-metadatas) parent-id)];; now return the newly created or reactivated Fields(when-let [new-and-updated-fields (seq (map u/the-id (concat fields-to-reactivate new-field-ids)))]- (t2/select :model/Field :id [:in new-and-updated-fields])))))+ (sync.db/fields new-and-updated-fields)))));;; +----------------------------------------------------------------------------------------------------------------+;;; | SYNCING INSTANCES OF 'ACTIVE' FIELDS (FIELDS IN DB METADATA) |@@ -184,7 +179,7 @@[table :- i/TableInstancemetabase-field :- common/TableMetadataFieldWithID](log/infof "Marking Field ''%s'' as inactive." (common/field-metadata-name-for-logging table metabase-field))- (when (pos? (t2/update! :model/Field (u/the-id metabase-field) {:active false}))+ (when (pos? (sync.db/update-field! (u/the-id metabase-field) {:active false}))1))(mu/defn- retire-fields! :- ms/IntGreaterThanOrEqualToZerodiff --git a/src/metabase/sync/sync_metadata/fields/sync_metadata.clj b/src/metabase/sync/sync_metadata/fields/sync_metadata.cljindex 4e05ed30933..de54162f528 100644--- a/src/metabase/sync/sync_metadata/fields/sync_metadata.clj+++ b/src/metabase/sync/sync_metadata/fields/sync_metadata.clj@@ -4,6 +4,7 @@Fields that were not newly created; newly created Fields are given appropriate metadata when first synced."(:require[clojure.string :as str]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.sync.sync-metadata.crufty :as crufty][metabase.sync.sync-metadata.fields.common :as common]@@ -12,8 +13,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [metabase.warehouse-schema.models.field-user-settings :as schema.field-user-settings]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.models.field-user-settings :as schema.field-user-settings]))(defn- normalize-nfc-path"Normalize a `nfc-path` to a vector of strings so a driver emitting keywords doesn't churn against the@@ -243,7 +243,7 @@{:preview_display false}))];; if any updates need to be done, do them and return 1 (because 1 Field was updated), otherwise return 0(if (and (seq updates)- (pos? (t2/update! :model/Field (u/the-id metabase-field) updates)))+ (pos? (sync.db/update-field! (u/the-id metabase-field) updates)))10)))diff --git a/src/metabase/sync/sync_metadata/fks.clj b/src/metabase/sync/sync_metadata/fks.cljindex db883a6a7a8..b337082ac05 100644--- a/src/metabase/sync/sync_metadata/fks.clj+++ b/src/metabase/sync/sync_metadata/fks.clj@@ -4,14 +4,14 @@[honey.sql :as sql][metabase.app-db.core :as mdb][metabase.driver.util :as driver.u]+ [metabase.sync.db :as sync.db][metabase.sync.fetch-metadata :as fetch-metadata][metabase.sync.interface :as i][metabase.sync.util :as sync-util][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.warehouse-schema.models.table :as table]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.models.table :as table]))(defn ^:private mark-fk-sql"Returns [sql & params] for [[mark-fk!]] according to the application DB's dialect."@@ -93,7 +93,7 @@"Updates the `fk_target_field_id` of a Field. Returns 1 if the Field was successfully updated, 0 otherwise."[database :- i/DatabaseInstancemetadata :- i/FKMetadataEntry]- (u/prog1 (t2/query-one (mark-fk-sql (:id database) metadata))+ (u/prog1 (sync.db/execute-one! (mark-fk-sql (:id database) metadata))(when (= <> 1)(log/info (u/format-color 'cyan "Marking foreign key from %s %s -> %s %s"(sync-util/table-name-for-logging :name (:fk-table-name metadata)diff --git a/src/metabase/sync/sync_metadata/indexes.clj b/src/metabase/sync/sync_metadata/indexes.cljindex 66433def462..466411f8519 100644--- a/src/metabase/sync/sync_metadata/indexes.clj+++ b/src/metabase/sync/sync_metadata/indexes.clj@@ -3,11 +3,11 @@[clojure.data :as data][metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.sync.db :as sync.db][metabase.sync.fetch-metadata :as fetch-metadata][metabase.sync.util :as sync-util][metabase.util.log :as log]- [metabase.warehouse-schema.models.field :as field]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.models.field :as field]))(def ^:private empty-stats{:total-indexes 0@@ -20,7 +20,7 @@(let [normal-indexes (->> indexes (filter #(= (:type %) :normal-column-index)) (map :value))nested-indexes (->> indexes (filter #(= (:type %) :nested-column-index)) (map :value))normal-indexes-field-ids (when (seq normal-indexes)- (t2/select-pks-vec :model/Field :name [:in normal-indexes] :table_id table-id :parent_id nil))+ (sync.db/top-level-field-ids-by-name table-id normal-indexes))nested-indexes-field-ids (remove nil? (map #(field/nested-field-names->field-id table-id %) nested-indexes))](set (filter some? (concat normal-indexes-field-ids nested-indexes-field-ids))))))@@ -31,17 +31,17 @@(sync-util/with-error-handling (format "Error syncing Indexes for %s" (sync-util/name-for-logging table))(let [indexes (fetch-metadata/index-metadata database table)indexed-field-ids (indexes->field-ids (:id table) indexes)- existing-indexed-field-ids (t2/select-pks-set :model/Field :table_id (:id table) :database_indexed true)+ existing-indexed-field-ids (sync.db/indexed-field-ids-for-table (:id table))[removing adding] (data/diff existing-indexed-field-ids indexed-field-ids)](doseq [field-id removing](log/infof "Unmarking Field %d as indexed" field-id))(doseq [field-id adding](log/infof "Marking Field %d as indexed" field-id))(if (or (seq adding) (seq removing))- (do (t2/update! :model/Field {:table_id (:id table)}- {:database_indexed (if (seq indexed-field-ids)- [:case [:in :id indexed-field-ids] true :else false]- false)})+ (do (sync.db/set-table-fields-indexed! (:id table)+ (if (seq indexed-field-ids)+ [:case [:in :id indexed-field-ids] true :else false]+ false)){:total-indexes (count indexed-field-ids):added-indexes (count adding):removed-indexes (count removing)})@@ -58,12 +58,7 @@(completing(fn [accum index-batch](let [normal-indexes (map (juxt #(:table-schema % "__null__") :table-name :field-name) index-batch)- query (t2/reducible-query {:select [[:f.id]]- :from [[(t2/table-name :model/Field) :f]]- :inner-join [[(t2/table-name :model/Table) :t] [:= :f.table_id :t.id]]- :where [:and [:in [:composite [:coalesce :t.schema "__null__"] :t.name :f.name] normal-indexes]- [:= :t.db_id database-id]- [:= :parent_id nil]]})]+ query (sync.db/top-level-field-ids-by-schema-table-and-name-reducible database-id normal-indexes)](into accum (keep :id) query))))#{}indexes))@@ -84,13 +79,7 @@(driver/describe-indexes (driver.u/database->driver database) database))database-id (:id database)indexed-field-ids (all-indexes->field-ids database-id indexes)- existing-indexed-field-ids (t2/select-pks-set :model/Field- :table_id [:in ^:allow-subquery- {:select [[:t.id]]- :from [[(t2/table-name :model/Table) :t]]- :where [:= :t.db_id database-id]}]- :parent_id nil- :database_indexed true)+ existing-indexed-field-ids (sync.db/indexed-top-level-field-ids-for-database database-id)[removing adding] (data/diff existing-indexed-field-ids indexed-field-ids)removing-count (count removing)adding-count (count adding)]@@ -100,14 +89,14 @@(log/tracef "Unmarking Fields as indexed: %s" (pr-str field-ids)))(doseq [field-ids (partition-all *update-partition-size* removing)](log/infof "Executing batch update of at most %d fields" *update-partition-size*)- (t2/update! :model/Field :parent_id nil :id [:in field-ids] {:database_indexed false}))+ (sync.db/set-top-level-fields-indexed! field-ids false));; Set database_indexed of fields having index.(log/infof "Marking %d fields as indexed" adding-count)(doseq [field-ids (partition-all 100 adding)](log/tracef "Marking Fields as indexed: %s" (pr-str field-ids)))(doseq [field-ids (partition-all *update-partition-size* adding)](log/infof "Executing batch update of at most %d fields" *update-partition-size*)- (t2/update! :model/Field :parent_id nil :id [:in field-ids] {:database_indexed true}))+ (sync.db/set-top-level-fields-indexed! field-ids true))(if (or (seq adding) (seq removing)){:total-indexes (count indexed-field-ids):added-indexes adding-countdiff --git a/src/metabase/sync/sync_metadata/metabase_metadata.clj b/src/metabase/sync/sync_metadata/metabase_metadata.cljindex 1fe741726dc..e050119aa2b 100644--- a/src/metabase/sync/sync_metadata/metabase_metadata.clj+++ b/src/metabase/sync/sync_metadata/metabase_metadata.clj@@ -9,14 +9,14 @@[clojure.string :as str][metabase.driver :as driver][metabase.driver.util :as driver.u]+ [metabase.sync.db :as sync.db][metabase.sync.fetch-metadata :as fetch-metadata][metabase.sync.interface :as i][metabase.sync.util :as sync-util][metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(def ^:private KeypathComponents[:map@@ -47,15 +47,12 @@(when-not (= k :field_type);; fetch the corresponding Table, then set the Table or Field property(if table-name- (when-let [table-id (t2/select-one-pk :model/Table- ;; TODO: this needs to support schemas- :db_id (u/the-id database)- :name table-name- :active true)]+ ;; TODO: this needs to support schemas+ (when-let [table-id (sync.db/active-table-id-by-name (u/the-id database) table-name)](if field-name- (t2/update! :model/Field {:name field-name, :table_id table-id} {k value})- (t2/update! :model/Table table-id {k value})))- (t2/update! :model/Database (u/the-id database) {k value})))))+ (sync.db/update-field-by-name! table-id field-name {k value})+ (sync.db/update-table! table-id {k value})))+ (sync.db/update-database! (u/the-id database) {k value})))))(mu/defn- sync-metabase-metadata-table!"Databases may include a table named `_metabase_metadata` (case-insensitive) which includes descriptions or otherdiff --git a/src/metabase/sync/sync_metadata/sync_timezone.clj b/src/metabase/sync/sync_metadata/sync_timezone.cljindex 96faeec55c0..a92af10fc5f 100644--- a/src/metabase/sync/sync_metadata/sync_timezone.clj+++ b/src/metabase/sync/sync_metadata/sync_timezone.clj@@ -5,11 +5,11 @@[metabase.driver.util :as driver.u][metabase.lib.schema.expression.temporal:as lib.schema.expression.temporal]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.util.i18n :refer [trs]][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -44,5 +44,5 @@zone-id (if (= zone-id "Z") "UTC" zone-id)](log/infof "%s database %s default timezone is %s" driver (pr-str (:id database)) (pr-str zone-id))(when-not (= zone-id (:timezone database))- (t2/update! :model/Database (:id database) {:timezone zone-id}))+ (sync.db/update-database! (:id database) {:timezone zone-id})){:timezone-id zone-id})))diff --git a/src/metabase/sync/sync_metadata/tables.clj b/src/metabase/sync/sync_metadata/tables.cljindex 12c78e4b1ba..e22c08fc3ea 100644--- a/src/metabase/sync/sync_metadata/tables.clj+++ b/src/metabase/sync/sync_metadata/tables.clj@@ -12,6 +12,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.models.humanization :as humanization][metabase.models.interface :as mi]+ [metabase.sync.db :as sync.db][metabase.sync.fetch-metadata :as fetch-metadata][metabase.sync.interface :as i][metabase.sync.sync-metadata.crufty :as crufty]@@ -20,8 +21,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]))(set! *warn-on-reflection* true)@@ -95,9 +95,8 @@[database :- i/DatabaseInstancedb-metadata :- i/DatabaseMetadata](log/infof "Found new version for DB: %s" (:version db-metadata))- (t2/update! :model/Database (u/the-id database)- {:details- (assoc (:details database) :version (:version db-metadata))}))+ (sync.db/update-database! (u/the-id database)+ {:details (assoc (:details database) :version (:version db-metadata))}))(mu/defn- cruft-dependent-cols :- :map[{table-name :name :as table} :- :map@@ -132,8 +131,7 @@Throws an exception if there is already a table with the same name, schema and database ID."[database :- i/DatabaseInstancetable :- :map]- (t2/insert-returning-instance!- :model/Table+ (sync.db/insert-table!(merge (cruft-dependent-cols table database ::create){:active true:db_id (:id database)@@ -159,23 +157,19 @@is the app-DB Table instance we already hold, so we don't re-select it."[database :- i/DatabaseInstanceexisting :- (ms/InstanceOf :model/Table)]- (t2/update! :model/Table (:id existing)- (cond-> (cruft-dependent-cols existing database ::reactivate)- ;; do not unhide tables w/ cruft settings- (some? (:visibility_type existing)) (dissoc :visibility_type)- true (assoc :active true)- (:is_sample database) (assoc :data_authority :ingested- :data_source :ingested))))+ (sync.db/update-table! (:id existing)+ (cond-> (cruft-dependent-cols existing database ::reactivate)+ ;; do not unhide tables w/ cruft settings+ (some? (:visibility_type existing)) (dissoc :visibility_type)+ true (assoc :active true)+ (:is_sample database) (assoc :data_authority :ingested+ :data_source :ingested))))(mu/defn create-or-reactivate-table!"Create a single new table in the database, or mark it as active if a matching inactive one exists."[database :- i/DatabaseInstance{schema :schema table-name :name :as table} :- :map]- (if-let [existing (t2/select-one :model/Table- :db_id (u/the-id database)- :schema schema- :name table-name- :active false)]+ (if-let [existing (sync.db/inactive-table-by-schema-and-name (u/the-id database) schema table-name)](reactivate-table! database existing)(create-table! database table)))@@ -237,7 +231,7 @@[table-ids :- [:set ::lib.schema.id/table]](when (seq table-ids)(log/info "Marking tables as inactive:" (pr-str table-ids))- (t2/update! :model/Table {:id [:in table-ids] :active true} {:active false})))+ (sync.db/deactivate-tables! table-ids)))(def ^:private keys-to-update[:description :database_require_filter :estimated_row_count :visibility_type :initial_sync_status :is_writable])@@ -279,7 +273,7 @@v))(boolean(when (seq changes)- (t2/update! :model/Table (:id metabase-table) changes)+ (sync.db/update-table! (:id metabase-table) changes)true))))(mu/defn- update-tables-metadata-if-needed! :- :int@@ -326,10 +320,10 @@tables](let [names (into [] (comp (map :name) (distinct)) tables)](if (seq names)- (t2/select-fn->fn table-name+schema identity- (into [:model/Table :id :name :schema :data_authority :active] keys-to-update)- :db_id (u/the-id database)- :name [:in names])+ (m/index-by table-name+schema+ (sync.db/tables-by-name (into [:model/Table :id :name :schema :data_authority :active] keys-to-update)+ (u/the-id database)+ names)){})))(mu/defn- adjusted-schemas :- [:maybe [:map-of :string :string]]@@ -346,7 +340,7 @@(cond-> accum(not= schema new-schema) (assoc schema new-schema)))))nil- (t2/reducible-select [:model/Table :schema] :db_id (u/the-id database))))+ (sync.db/table-schemas-reducible (u/the-id database))))(mu/defn- adjust-table-schemas!"Apply the `{old-schema new-schema}` renames from [[adjusted-schemas]] to the app-DB Table rows."@@ -355,10 +349,7 @@(when schemas-to-update(log/infof "Renaming schemas: %s" (pr-str schemas-to-update)))(doseq [[schema new-schema] schemas-to-update]- (t2/update! :model/Table- :db_id (:id database)- :schema schema- {:schema new-schema})))+ (sync.db/rename-table-schema! (:id database) schema new-schema)))(def ^:private^{:doc "threshold after which deactivated tables will be archived"}@@ -377,12 +368,7 @@threshold-expr (apply(requiring-resolve 'metabase.util.honey-sql-2/add-interval-honeysql-form)(mdb/db-type) :%now archive-tables-threshold)- tables-to-archive (t2/select :model/Table- :db_id (u/the-id database)- :active false- :archived_at nil- :transform_target false- :deactivated_at [:< threshold-expr])+ tables-to-archive (sync.db/tables-to-archive (u/the-id database) threshold-expr)archived (atom 0)](doseq [table tables-to-archive:let [new-name (str (:name table) suffix)]]@@ -398,11 +384,7 @@;; in the extremely unlikely case that there already exists a table with our;; archived name, we let it fail from hitting the unique constraints violation;; and just report the failure- [(t2/update! :model/Table- {:id (:id table)- :active false}- {:archived_at (mi/now)- :name new-name})]+ [(sync.db/archive-inactive-table! (:id table) (mi/now) new-name)](catch Throwable t[0 t]))](when (zero? did-update)@@ -487,7 +469,7 @@(retire-tables! (set batch))(+ retired (count batch))))0- (t2/reducible-select [:model/Table :id] :db_id (u/the-id database) :active true)))+ (sync.db/active-table-ids-reducible (u/the-id database))))(mu/defn sync-tables-and-database!"Sync the `:model/Table` rows for `database` against its driver's `describe-database`, and the DB@@ -530,4 +512,4 @@{:updated-tables (cond-> (+ created updated)(int? retired) (+ retired)(int? archived) (+ archived))- :total-tables (t2/count :model/Table :db_id (u/the-id database) :active true)})))))+ :total-tables (sync.db/active-table-count (u/the-id database))})))))diff --git a/src/metabase/sync/task/sync_databases.clj b/src/metabase/sync/task/sync_databases.cljindex e20ca6080d0..37d70e46be5 100644--- a/src/metabase/sync/task/sync_databases.clj+++ b/src/metabase/sync/task/sync_databases.clj@@ -17,6 +17,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi][metabase.sync.analyze :as analyze]+ [metabase.sync.db :as sync.db][metabase.sync.field-values :as sync.field-values][metabase.sync.schedules :as sync.schedules][metabase.sync.sync-metadata :as sync-metadata]@@ -28,8 +29,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]- [metabase.warehouses.core :as warehouses]- [toucan2.core :as t2])+ [metabase.warehouses.core :as warehouses])(:import(org.quartzCronTrigger@@ -76,7 +76,7 @@(defn- sync-and-analyze-database*- (when-let [database (or (t2/select-one :model/Database :id database-id)+ (when-let [database (or (sync.db/database database-id)(do(unschedule-tasks-for-db! (mi/instance :model/Database {:id database-id}))(log/warnf "Cannot sync Database %d: Database does not exist." database-id)))]@@ -122,7 +122,7 @@:raw-job-context job-context:job-context (pr-str job-context)}))))- (t2/select-one-fn :is_stub :model/Database :id database-id)+ (sync.db/database-stub? database-id)(log/warnf "Skipping scheduled sync for Database %d: it is a stub." database-id):else@@ -141,7 +141,7 @@(log/debugf "Skipping scheduled field-values update for Database %d: disable-auto-sync is on." database-id)(do(log/infof "Update Field values task triggered for Database %d." database-id)- (when-let [database (or (t2/select-one :model/Database :id database-id)+ (when-let [database (or (sync.db/database database-id)(do(unschedule-tasks-for-db! (mi/instance :model/Database {:id database-id}))(log/warnf "Cannot update Field values for Database %d: Database does not exist." database-id)))]@@ -366,29 +366,21 @@counter)([counter db](try- (t2/update! :model/Database (u/the-id db)- (sync.schedules/schedule-map->cron-strings- ;; TODO (edpaget): this can go away after this patch is deployed to cloud- (if (= sync.schedules/old-sample-metadata-sync-schedule-cron-string- (:metadata_sync_schedule db))- (sync.schedules/default-randomized-schedule {:excluded-minute 43})- (sync.schedules/default-randomized-schedule))))+ (sync.db/update-database! (u/the-id db)+ (sync.schedules/schedule-map->cron-strings+ ;; TODO (edpaget): this can go away after this patch is deployed to cloud+ (if (= sync.schedules/old-sample-metadata-sync-schedule-cron-string+ (:metadata_sync_schedule db))+ (sync.schedules/default-randomized-schedule {:excluded-minute 43})+ (sync.schedules/default-randomized-schedule))))(inc counter)(catch Exception e(log/warnf "Error updating database %d for randomized schedules: %s" (u/the-id db) (ex-message e))counter))))- (t2/reducible-query- {:select [:*]- :from [:metabase_database]- :where [:or- [:and [:= :is_sample true]- [:= :metadata_sync_schedule sync.schedules/old-sample-metadata-sync-schedule-cron-string]]- [:in- :metadata_sync_schedule- sync.schedules/default-metadata-sync-schedule-cron-strings]- [:in- :cache_field_values_schedule- sync.schedules/default-cache-field-values-schedule-cron-strings]]})))+ (sync.db/databases-with-schedules-reducible+ sync.schedules/old-sample-metadata-sync-schedule-cron-string+ sync.schedules/default-metadata-sync-schedule-cron-strings+ sync.schedules/default-cache-field-values-schedule-cron-strings)))(defmethod task/init! ::SyncDatabases[_]diff --git a/src/metabase/sync/util.clj b/src/metabase/sync/util.cljindex fc19de8f9dd..3e819130ac8 100644--- a/src/metabase/sync/util.clj+++ b/src/metabase/sync/util.clj@@ -14,6 +14,7 @@[metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.query-processor.interface :as qp.i]+ [metabase.sync.db :as sync.db][metabase.sync.interface :as i][metabase.task-history.core :as task-history][metabase.tracing.core :as tracing]@@ -25,7 +26,6 @@[metabase.util.malli.schema :as ms][metabase.util.memory :as u.mem][metabase.warehouses.models.database :as database]- [toucan2.core :as t2][toucan2.realize :as t2.realize])(:import(java.time.temporal Temporal)))@@ -425,13 +425,7 @@"Marks initial sync as complete for this table so that it becomes usable in the UI, if not already set"[table](when (not= (:initial_sync_status table) "complete")- (t2/update! :model/Table (u/the-id table) {:initial_sync_status "complete"})))--(def ^:private sync-tables-kv-args- {:active true- ;; TODO (Ngoc 2025-11-13) replace this with `metabase_table.data_layer = hidden` see the docstring of- ;; [[metabase.warehouse-schema.models.table/data-layer-types]]- :visibility_type nil})+ (sync.db/update-table! (u/the-id table) {:initial_sync_status "complete"})))(def ^:dynamic *batch-size*"Size of table update partition."@@ -441,13 +435,9 @@"Marks initial sync for all tables in `db` as complete so that it becomes usable in the UI, if not alreadyset."[database-or-id]- (let [where-clause {:where (into [:and]- (map (partial into [:=]))- (merge sync-tables-kv-args- {:db_id (u/the-id database-or-id)}))}- ids (t2/select-fn-vec :id :model/Table where-clause)]+ (let [ids (sync.db/sync-table-ids (u/the-id database-or-id))](reduce (fn [acc ids']- (+ acc (t2/update! :model/Table :id [:in ids'] {:initial_sync_status "complete"})))+ (+ acc (sync.db/update-tables! ids' {:initial_sync_status "complete"})))0(partition-all *batch-size* ids))))@@ -455,23 +445,18 @@"Marks initial sync as complete for this database so that this is reflected in the UI, if not already set"[database](when (not= (:initial_sync_status database) "complete")- (t2/update! :model/Database (u/the-id database) {:initial_sync_status "complete"})))+ (sync.db/update-database! (u/the-id database) {:initial_sync_status "complete"})))(defn set-initial-database-sync-aborted!"Marks initial sync as aborted for this database so that an error can be displayed on the UI"[database](when (not= (:initial_sync_status database) "complete")- (t2/update! :model/Database (u/the-id database) {:initial_sync_status "aborted"})))+ (sync.db/update-database! (u/the-id database) {:initial_sync_status "aborted"})));;; +----------------------------------------------------------------------------------------------------------------+;;; | OTHER SYNC UTILITY FUNCTIONS |;;; +----------------------------------------------------------------------------------------------------------------+-(def sync-tables-clause- "Returns a clause that can be used inside a HoneySQL :where clause to select all the Tables that should be synced"- (into [:and] (for [[k v] sync-tables-kv-args]- [:= k v])))-(mu/defn reducible-sync-tables"Returns a reducible of all the Tables that should go through the sync processes for `database-or-id`.@@ -482,42 +467,25 @@[:id ::lib.schema.id/database]]]& {:keys [schema-names table-names]} :- ::driver/describe-fks.options](eduction (map t2.realize/realize)- (t2/reducible-select :model/Table- :db_id (u/the-id database-or-id)- {:where [:and sync-tables-clause- (when (seq schema-names) [:in :schema schema-names])- (when (seq table-names) [:in :name table-names])]- :order-by [[:schema :asc]- [:name :asc]]})))+ (sync.db/sync-tables-reducible (u/the-id database-or-id) schema-names table-names)))(defn sync-tables-count"The count of all tables that should be synced for `database-or-id`."[database-or-id]- (t2/count :model/Table :db_id (u/the-id database-or-id) {:where sync-tables-clause}))+ (sync.db/sync-tables-count (u/the-id database-or-id)))(defn refingerprint-reducible-sync-tables"A reducible collection of all the Tables that should go through the sync processes for `database-or-id`, in theorder they should be refingerprinted (by earliest last_analyzed timestamp)."[database-or-id](eduction (map t2.realize/realize)- (t2/reducible-select :model/Table- {:select [:t.*]- :from [[(t2/table-name :model/Table) :t]]- :left-join [[^:allow-subquery {:select [:table_id- [[:min :last_analyzed] :earliest_last_analyzed]]- :from [(t2/table-name :model/Field)]- :group-by [:table_id]} :sub]- [:= :t.id :sub.table_id]]- :where [:and sync-tables-clause [:= :t.db_id (u/the-id database-or-id)]]- :order-by [[:sub.earliest_last_analyzed :asc]]})))+ (sync.db/sync-tables-by-earliest-analyzed-reducible (u/the-id database-or-id))))(defn sync-schemas"Returns all the Schemas that have their metadata sync'd for `database-or-id`.Assumes the database supports schemas."[database-or-id]- (vec (map :schema (t2/query {:select-distinct [:schema]- :from [:metabase_table]- :where [:and sync-tables-clause [:= :db_id (u/the-id database-or-id)]]}))))+ (vec (map :schema (sync.db/sync-table-schemas (u/the-id database-or-id)))))(defmulti name-for-logging"Return an appropriate string for logging an object in sync logging messages. Should be something likediff --git a/src/metabase/task_history/api.clj b/src/metabase/task_history/api.cljindex 50edfbd20f4..6f712e2d956 100644--- a/src/metabase/task_history/api.clj+++ b/src/metabase/task_history/api.clj@@ -6,15 +6,14 @@[metabase.permissions.core :as perms][metabase.query-processor.parameters.dates :as params.dates][metabase.request.core :as request]+ [metabase.task-history.db :as task-history.db][metabase.task-history.models.task-history :as task-history][metabase.task-history.models.task-run :as task-run][metabase.task.core :as task][metabase.util.date-2 :as u.date]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [tru]][metabase.util.malli.registry :as mr]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -130,10 +129,10 @@[:entity_id ms/PositiveInt][:entity_name {:optional true} [:maybe :string]]])-(def ^:private entity-type->model- {:database :model/Database- :card :model/Card- :dashboard :model/Dashboard})+(def ^:private entity-type->names-fn+ {:database task-history.db/database-names-by-id+ :card task-history.db/card-names-by-id+ :dashboard task-history.db/dashboard-names-by-id})(defn- hydrate-entity-names"Hydrate entity names based on entity_type and entity_id."@@ -142,12 +141,12 @@runs(let [grouped (group-by :entity_type runs)name-lookup (into {}- (mapcat (fn [[entity-type model]]+ (mapcat (fn [[entity-type names-fn]](when-let [entity-runs (grouped entity-type)](let [ids (map :entity_id entity-runs)- names (t2/select-pk->fn :name model :id [:in ids])]+ names (names-fn ids)](map (fn [[id name]] [[entity-type id] name]) names))))- entity-type->model))]+ entity-type->names-fn))](map #(assoc % :entity_name (get name-lookup [(:entity_type %) (:entity_id %)])) runs))))(defn- hydrate-task-counts@@ -156,13 +155,7 @@(if (empty? runs)runs(let [run-ids (map :id runs)- counts (t2/query {:select [:run_id- [[:count :id] :task_count]- [[:sum [:case [:= :status [::h2x/literal "success"]] [:inline 1] :else [:inline 0]]] :success_count]- [[:sum [:case [:= :status [::h2x/literal "failed"]] [:inline 1] :else [:inline 0]]] :failed_count]]- :from :task_history- :where [:in :run_id run-ids]- :group-by [:run_id]})+ counts (task-history.db/task-counts-for-runs run-ids);; Coerce counts to int (MySQL may return BigDecimal)counts-by-id (into {} (map (fn [{:keys [run_id task_count success_count failed_count]}][run_id {:task_count (int task_count)@@ -174,79 +167,37 @@(get counts-by-id (:id %)))runs))))-(defn- timestamp-constraint- [field-name date-string]+(defn- timestamp-range+ [date-string](let [{:keys [start end]}(try(params.dates/date-string->range date-string {:inclusive-end? false})(catch Exception e(throw (ex-info (tru "Failed to parse datetime value: {0}" date-string){:status-code 400}- e))))- start (some-> start u.date/parse)- end (some-> end u.date/parse)]- (into [:and] (remove nil?)- [(when start- [:>= field-name start])- (when end- [:< field-name end])])))+ e))))]+ [(some-> start u.date/parse) (some-> end u.date/parse)]))-(defn- build-run-where-clause+(defn- run-filters[{:keys [run-type entity-type entity-id status started-at]}]- ;; columns are qualified because the entity_name/task_count sorts add joins whose tables may share column names- ;; (e.g. report_card.entity_id)- (let [conditions (cond-> []- run-type (conj [:= :task_run.run_type run-type])- entity-type (conj [:= :task_run.entity_type entity-type])- entity-id (conj [:= :task_run.entity_id entity-id])- status (conj [:= :task_run.status status])- started-at (conj (timestamp-constraint :task_run.started_at started-at)))]- (if (seq conditions)- {:where (into [:and] conditions)}- {})))--(defn- runs-order-by- "Build the honeysql fragment used to order the task runs list. Direct columns order in place; `:entity_name`- LEFT JOINs the three entity tables and orders by the coalesced name; `:task_count` LEFT JOINs a grouped- `task_history` subquery. Derived-column variants keep the selected shape to `task_run.*` and add a- deterministic `[:id :desc]` secondary key."- [{col :sort-column dir :sort-direction}]- (let [secondary [:task_run.id :desc]]- (case col- :entity_name- {:select [:task_run.*]- :left-join [[:metabase_database :sort_db]- [:and [:= :task_run.entity_type "database"] [:= :task_run.entity_id :sort_db.id]]- [:report_card :sort_card]- [:and [:= :task_run.entity_type "card"] [:= :task_run.entity_id :sort_card.id]]- [:report_dashboard :sort_dash]- [:and [:= :task_run.entity_type "dashboard"] [:= :task_run.entity_id :sort_dash.id]]]- :order-by [[[:coalesce :sort_db.name :sort_card.name :sort_dash.name] dir] secondary]}-- :task_count- {:select [:task_run.*]- :left-join [[^:allow-subquery {:select [:run_id [[:count :*] :task_count]]- :from [:task_history]- :group-by [:run_id]}- :sort_tc]- [:= :sort_tc.run_id :task_run.id]]- :order-by [[[:coalesce :sort_tc.task_count [:inline 0]] dir] secondary]}-- {:order-by [[col dir] secondary]})))+ (let [[start end] (when started-at (timestamp-range started-at))]+ {:run-type run-type+ :entity-type entity-type+ :entity-id entity-id+ :status status+ :started-at-start start+ :started-at-end end}))(api.macros/defendpoint :get "/runs" :- ::TaskRunsResponse"List task runs with optional filters. Returns runs with hydrated entity names and task counts."[_- params :- [:maybe [:merge ::RunFilterParams ::RunSortParams]]]+ {:keys [sort-column sort-direction] :as params} :- [:maybe [:merge ::RunFilterParams ::RunSortParams]]](perms/check-has-application-permission :monitoring)- (let [where-clause (build-run-where-clause params)- limit (request/limit)- offset (request/offset)- runs (t2/select :model/TaskRun (merge where-clause- (runs-order-by params)- (when limit {:limit limit})- (when offset {:offset offset})))]- {:total (t2/count :model/TaskRun where-clause)+ (let [filters (run-filters params)+ limit (request/limit)+ offset (request/offset)+ runs (task-history.db/task-runs filters sort-column sort-direction limit offset)]+ {:total (task-history.db/task-run-count filters):limit limit:offset offset:data (-> runs hydrate-entity-names hydrate-task-counts)}))@@ -255,8 +206,8 @@"Get a single task run with all its child tasks."[{:keys [id]} :- [:map [:id ms/PositiveInt]]](perms/check-has-application-permission :monitoring)- (let [run (api/check-404 (t2/select-one :model/TaskRun :id id))- tasks (t2/select :model/TaskHistory :run_id id {:order-by [[:started_at :asc]]})]+ (let [run (api/check-404 (task-history.db/task-run id))+ tasks (task-history.db/tasks-for-run id)](-> [run]hydrate-entity-nameshydrate-task-counts@@ -270,10 +221,7 @@[:run-type (into [:enum] (map name task-run/run-types))][:started-at ms/NonBlankString]]](perms/check-has-application-permission :monitoring)- (let [where-conditions [[:= :run_type (:run-type params)]- (timestamp-constraint :started_at (:started-at params))]]- (->> (t2/query {:select-distinct [:entity_type :entity_id]- :from :task_run- :where (into [:and] where-conditions)})+ (let [[start end] (timestamp-range (:started-at params))]+ (->> (task-history.db/distinct-run-entities (:run-type params) start end)(map #(update % :entity_type keyword))hydrate-entity-names)))diff --git a/src/metabase/task_history/db.clj b/src/metabase/task_history/db.cljnew file mode 100644index 00000000000..bbed033da04--- /dev/null+++ b/src/metabase/task_history/db.clj@@ -0,0 +1,202 @@+(ns metabase.task-history.db+ "Application database queries for the task history module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn database-names-by-id+ "A map of id to name for the Databases with `ids`."+ [ids]+ (t2/select-pk->fn :name :model/Database :id [:in ids]))++(defn card-names-by-id+ "A map of id to name for the Cards with `ids`."+ [ids]+ (t2/select-pk->fn :name :model/Card :id [:in ids]))++(defn dashboard-names-by-id+ "A map of id to name for the Dashboards with `ids`."+ [ids]+ (t2/select-pk->fn :name :model/Dashboard :id [:in ids]))++(defn task-counts-for-runs+ "The total, successful, and failed TaskHistory counts of the TaskRuns with `run-ids`, grouped by run."+ [run-ids]+ (t2/query {:select [:run_id+ [[:count :id] :task_count]+ [[:sum [:case [:= :status (h2x/literal "success")] [:inline 1] :else [:inline 0]]] :success_count]+ [[:sum [:case [:= :status (h2x/literal "failed")] [:inline 1] :else [:inline 0]]] :failed_count]]+ :from :task_history+ :where [:in :run_id run-ids]+ :group-by [:run_id]}))++(defn- run-where+ ;; columns are qualified because the entity_name/task_count sorts add joins whose tables may share column names+ ;; (e.g. report_card.entity_id)+ [{:keys [run-type entity-type entity-id status started-at-start started-at-end]}]+ (let [conditions (cond-> []+ run-type (conj [:= :task_run.run_type run-type])+ entity-type (conj [:= :task_run.entity_type entity-type])+ entity-id (conj [:= :task_run.entity_id entity-id])+ status (conj [:= :task_run.status status])+ started-at-start (conj [:>= :task_run.started_at started-at-start])+ started-at-end (conj [:< :task_run.started_at started-at-end]))]+ (when (seq conditions)+ {:where (into [:and] conditions)})))++(defn- runs-order-by+ "Build the honeysql fragment used to order the task runs list. Direct columns order in place; `:entity_name`+ LEFT JOINs the three entity tables and orders by the coalesced name; `:task_count` LEFT JOINs a grouped+ `task_history` subquery. Derived-column variants keep the selected shape to `task_run.*` and add a+ deterministic `[:id :desc]` secondary key."+ [sort-column sort-direction]+ (let [secondary [:task_run.id :desc]]+ (case sort-column+ :entity_name+ {:select [:task_run.*]+ :left-join [[:metabase_database :sort_db]+ [:and [:= :task_run.entity_type "database"] [:= :task_run.entity_id :sort_db.id]]+ [:report_card :sort_card]+ [:and [:= :task_run.entity_type "card"] [:= :task_run.entity_id :sort_card.id]]+ [:report_dashboard :sort_dash]+ [:and [:= :task_run.entity_type "dashboard"] [:= :task_run.entity_id :sort_dash.id]]]+ :order-by [[[:coalesce :sort_db.name :sort_card.name :sort_dash.name] sort-direction] secondary]}++ :task_count+ {:select [:task_run.*]+ :left-join [[^:allow-subquery {:select [:run_id [[:count :*] :task_count]]+ :from [:task_history]+ :group-by [:run_id]}+ :sort_tc]+ [:= :sort_tc.run_id :task_run.id]]+ :order-by [[[:coalesce :sort_tc.task_count [:inline 0]] sort-direction] secondary]}++ {:order-by [[sort-column sort-direction] secondary]})))++(defn task-runs+ "Up to `limit` (offset by `offset`) TaskRuns matching `filters` (see [[run-where]] for the supported keys), sorted+ by `sort-column`/`sort-direction`."+ [filters sort-column sort-direction limit offset]+ (t2/select :model/TaskRun+ (cond-> (merge (run-where filters) (runs-order-by sort-column sort-direction))+ limit (assoc :limit limit)+ offset (assoc :offset offset))))++(defn task-run-count+ "The number of TaskRuns matching `filters` (see [[run-where]] for the supported keys)."+ [filters]+ (t2/count :model/TaskRun (or (run-where filters) {})))++(defn task-run+ "The TaskRun with `id`, or nil."+ [id]+ (t2/select-one :model/TaskRun :id id))++(defn tasks-for-run+ "The TaskHistory rows of the TaskRun with `run-id`, oldest first."+ [run-id]+ (t2/select :model/TaskHistory :run_id run-id {:order-by [[:started_at :asc]]}))++(defn distinct-run-entities+ "The distinct entity type and id of the TaskRuns of `run-type` started in [`started-at-start`, `started-at-end`)."+ [run-type started-at-start started-at-end]+ (t2/query {:select-distinct [:entity_type :entity_id]+ :from :task_run+ :where (into [:and [:= :run_type run-type]]+ (keep identity)+ [(when started-at-start [:>= :started_at started-at-start])+ (when started-at-end [:< :started_at started-at-end])])}))++(defn nth-newest-task-history-ended-at+ "The `ended_at` of the TaskHistory row `offset` rows from the most recently ended, or nil."+ [offset]+ (t2/select-one-fn :ended_at :model/TaskHistory {:limit 1+ :offset offset+ :order-by [[:ended_at :desc]]}))++(defn delete-task-history-ended-before!+ "Delete the TaskHistory rows that ended at or before `ended-before`."+ [ended-before]+ (t2/delete! (t2/table-name :model/TaskHistory) :ended_at [:<= ended-before]))++(def ^:private join-sort-columns+ "Sort columns that require a LEFT JOIN to `metabase_database`, mapped to the joined column to order by."+ {:db_name :metabase_database.name+ :db_engine :metabase_database.engine})++(defn- task-history-where+ ;; qualified so filters stay unambiguous when the db_name/db_engine sorts join metabase_database+ [status task]+ (when (or status task)+ (cond-> [:and]+ task (conj [:= :task_history.task task])+ status (conj [:= :task_history.status (name status)]))))++(defn task-histories+ "Up to `limit` (offset by `offset`) TaskHistory rows, optionally narrowed to `status` and/or `task`, sorted by+ `sort-column` (an allow-listed column, joining to Database for `:db_name`/`:db_engine`) and `sort-direction`, with+ `:id desc` as a stable tiebreaker."+ [status task sort-column sort-direction limit offset]+ (t2/select :model/TaskHistory+ (cond-> (if-let [where (task-history-where status task)]+ {:where where}+ {})+ (join-sort-columns sort-column)+ (merge {:select [:task_history.*]+ :left-join [:metabase_database [:= :task_history.db_id :metabase_database.id]]+ :order-by [[(join-sort-columns sort-column) sort-direction] [:task_history.id :desc]]})++ (not (join-sort-columns sort-column))+ (assoc :order-by [[sort-column sort-direction] [:id :desc]])++ limit (assoc :limit limit)+ offset (assoc :offset offset))))++(defn task-history-count+ "The number of TaskHistory rows, optionally narrowed to `status` and/or `task`."+ [status task]+ (t2/count :model/TaskHistory (if-let [where (task-history-where status task)] {:where where} {})))++(defn distinct-task-names+ "The distinct task names of the TaskHistory rows, in alphabetical order."+ []+ (t2/select-fn-vec :task [:model/TaskHistory :task] {:group-by [:task]+ :order-by [:task]}))++(defn update-task-history!+ "Apply `changes` to the TaskHistory row with `id`."+ [id changes]+ (t2/update! :model/TaskHistory id changes))++(defn insert-task-history!+ "Insert the TaskHistory `row` and return its id."+ [row]+ (t2/insert-returning-pk! :model/TaskHistory row))++(defn insert-task-run!+ "Insert the TaskRun `row` and return its id."+ [row]+ (t2/insert-returning-pk! :model/TaskRun row))++(defn task-statuses-for-run+ "The set of statuses of the TaskHistory rows of the TaskRun with `run-id`."+ [run-id]+ (t2/select-fn-set :status :model/TaskHistory :run_id run-id))++(defn finish-started-task-run!+ "Set the status and end time of the started TaskRun with `run-id`."+ [run-id status ended-at]+ (t2/update! :model/TaskRun {:id run-id :status :started} {:status status, :ended_at ended-at}))++(defn heartbeat-started-task-runs!+ "Touch `updated_at` of the started TaskRuns of `process-uuid`, returning the number updated."+ [process-uuid updated-at]+ (t2/update! :model/TaskRun {:status :started, :process_uuid process-uuid} {:updated_at updated-at}))++(defn mark-started-tasks-unknown!+ "Set the started TaskHistory rows of the TaskRuns with `run-ids` to unknown, returning the number updated."+ [run-ids ended-at]+ (t2/update! :model/TaskHistory+ {:status :started, :run_id [:in run-ids]}+ {:status :unknown, :ended_at ended-at}))diff --git a/src/metabase/task_history/models/task_history.clj b/src/metabase/task_history/models/task_history.cljindex f655d41d703..7681c16311a 100644--- a/src/metabase/task_history/models/task_history.clj+++ b/src/metabase/task_history/models/task_history.clj@@ -9,6 +9,7 @@[metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features]+ [metabase.task-history.db :as task-history.db][metabase.task-history.models.task-run :as task-run][metabase.util :as u][metabase.util.json :as json]@@ -48,10 +49,8 @@;; the date that task finished, it deletes everything after that. As we continue to add TaskHistory entries, this;; ensures we'll have a good amount of history for debugging/troubleshooting, but not grow too large and fill the;; disk.- (when-let [clean-before-date (t2/select-one-fn :ended_at :model/TaskHistory {:limit 1- :offset num-rows-to-keep- :order-by [[:ended_at :desc]]})]- (t2/delete! (t2/table-name :model/TaskHistory) :ended_at [:<= clean-before-date])))+ (when-let [clean-before-date (task-history.db/nth-newest-task-history-ended-at num-rows-to-keep)]+ (task-history.db/delete-task-history-ended-before! clean-before-date)))(def ^:private task-history-status #{:started :success :failed :unknown})@@ -74,37 +73,12 @@:logs mi/transform-json:status mi/transform-keyword})-(defn- params->where- [{:keys [status task]}]- (when (or status task)- ;; qualified so filters stay unambiguous when the db_name/db_engine sorts join metabase_database- {:where (cond-> [:and]- task (conj [:= :task_history.task task])- status (conj [:= :task_history.status (name status)]))}))-(def FilterParams"Schema for filter for task history."[:map[:status {:optional true} (into [:enum] task-history-status)][:task {:optional true} [:string {:min 1}]]])-(def ^:private join-sort-columns- "Sort columns that require a LEFT JOIN to `metabase_database`, mapped to the joined column to order by."- {:db_name :metabase_database.name- :db_engine :metabase_database.engine})--(defn- params->order-by- "Build the honeysql fragment needed to order the task history list. For `:db_name`/`:db_engine` this adds a LEFT JOIN- to `metabase_database` (ordering by the joined name/engine) while keeping the selected row shape to `task_history.*`.- A secondary `[:id :desc]` key makes ordering deterministic for low-cardinality columns."- [{col :sort_column- dir :sort_direction}]- (if-let [order-col (join-sort-columns col)]- {:select [:task_history.*]- :left-join [:metabase_database [:= :task_history.db_id :metabase_database.id]]- :order-by [[order-col dir] [:task_history.id :desc]]}- {:order-by [[col dir] [:id :desc]]}))-(def ^:private available-sort-columns#{:started_at :ended_at :duration :task :status :db_name :db_engine})@@ -118,24 +92,18 @@"Return all TaskHistory entries, filtered if `filter` is provided, applying `limit` and `offset` if not nil."[limit :- [:maybe ms/PositiveInt]offset :- [:maybe ms/IntGreaterThanOrEqualToZero]- params :- [:maybe [:merge FilterParams SortParams]]]- (t2/select :model/TaskHistory (merge (params->where params)- (params->order-by params)- (when limit- {:limit limit})- (when offset- {:offset offset}))))+ {:keys [status task sort_column sort_direction]} :- [:maybe [:merge FilterParams SortParams]]]+ (task-history.db/task-histories status task (or sort_column :started_at) (or sort_direction :desc) limit offset))(mu/defn total"Return count of all, or filtered if `filter` is provided, task history entries."- [params :- FilterParams]- (t2/count :model/TaskHistory ((fnil identity {}) (params->where params))))+ [{:keys [status task]} :- FilterParams]+ (task-history.db/task-history-count status task))(defn unique-tasks"Return _vector_ of all unique tasks' names in alphabetical order."[]- (vec (t2/select-fn-vec :task [:model/TaskHistory :task] {:group-by [:task]- :order-by [:task]})))+ (vec (task-history.db/distinct-task-names)));;; +----------------------------------------------------------------------------------------------------------------+;;; | with-task-history macro |@@ -163,7 +131,7 @@(let [updated-info (merge {:ended_at (t/instant):duration (ns->ms (- (System/nanoTime) startime-ns))}info)]- (t2/update! :model/TaskHistory th-id updated-info)))+ (task-history.db/update-task-history! th-id updated-info)))(def ^:dynamic ^Clock *log-capture-clock*"The java.time.Clock used for captured log message `:timestamp` values. Can be overridden for tests."@@ -240,11 +208,11 @@info (dissoc info :on-success-info :on-fail-info)start-time-ns (System/nanoTime)run-id (task-run/current-run-id)- th-id (t2/insert-returning-pk! :model/TaskHistory- (cond-> (assoc info- :status :started- :started_at (t/instant))- run-id (assoc :run_id run-id)))+ th-id (task-history.db/insert-task-history!+ (cond-> (assoc info+ :status :started+ :started_at (t/instant))+ run-id (assoc :run_id run-id)))logs-atom (log-capture-atom)](binding [clojure.tools.logging/*logger-factory*(log-capture-factory clojure.tools.logging/*logger-factory* logs-atom)]diff --git a/src/metabase/task_history/models/task_run.clj b/src/metabase/task_history/models/task_run.cljindex db8eda58130..9aba1b67471 100644--- a/src/metabase/task_history/models/task_run.clj+++ b/src/metabase/task_history/models/task_run.clj@@ -6,6 +6,7 @@[metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features]+ [metabase.task-history.db :as task-history.db][metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]@@ -93,28 +94,26 @@"Create a new task run record. Returns the run ID."[{:keys [run_type entity_type entity_id notification_id]} :- ::TaskRunInfo](let [now (mi/now)]- (t2/insert-returning-pk! :model/TaskRun- {:run_type run_type- :entity_type entity_type- :entity_id entity_id- :notification_id notification_id- :status :started- :started_at now- :updated_at now- :process_uuid config/local-process-uuid})))+ (task-history.db/insert-task-run!+ {:run_type run_type+ :entity_type entity_type+ :entity_id entity_id+ :notification_id notification_id+ :status :started+ :started_at now+ :updated_at now+ :process_uuid config/local-process-uuid})))(mu/defn complete-task-run!"Mark a task run as complete, deriving status from child tasks.Must be called manually for async flows, or automatically via [[with-task-run]].Idempotent - only completes if status is still :started."[run-id :- ms/PositiveInt]- (let [task-statuses (t2/select-fn-set :status :model/TaskHistory :run_id run-id)+ (let [task-statuses (task-history.db/task-statuses-for-run run-id)status (if (= #{:success} task-statuses):success:failed)]- (t2/update! :model/TaskRun {:id run-id :status :started}- {:status status- :ended_at (t/instant)})))+ (task-history.db/finish-started-task-run! run-id status (t/instant))))(defmacro with-task-run"Wrap a root flow to group all tasks under a single run.diff --git a/src/metabase/task_history/task/task_run_heartbeat.clj b/src/metabase/task_history/task/task_run_heartbeat.cljindex c345ee262e9..52bbb1cd431 100644--- a/src/metabase/task_history/task/task_run_heartbeat.clj+++ b/src/metabase/task_history/task/task_run_heartbeat.clj@@ -7,10 +7,10 @@[metabase.config.core :as config][metabase.models.interface :as mi][metabase.run-tracking.core :as rt]+ [metabase.task-history.db :as task-history.db][metabase.task.core :as task][metabase.tracing.core :as tracing]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -26,10 +26,7 @@"Update updated_at for all :started runs belonging to this process."[](tracing/with-span :tasks "task.heartbeat.update" {}- (let [updated (t2/update! :model/TaskRun- {:status :started- :process_uuid config/local-process-uuid}- {:updated_at (mi/now)})]+ (let [updated (task-history.db/heartbeat-started-task-runs! config/local-process-uuid (mi/now))](when (pos? updated)(log/debugf "Sent heartbeat for %d running task runs" updated))updated)))@@ -54,11 +51,7 @@[orphaned-run-ids](when (seq orphaned-run-ids)(tracing/with-span :tasks "task.heartbeat.mark-orphaned-tasks" {:heartbeat/orphaned-run-count (count orphaned-run-ids)}- (let [orphaned (t2/update! :model/TaskHistory- {:status :started- :run_id [:in orphaned-run-ids]}- {:status :unknown- :ended_at (mi/now)})]+ (let [orphaned (task-history.db/mark-started-tasks-unknown! orphaned-run-ids (mi/now))](when (pos? orphaned)(log/infof "Marked %d orphaned tasks as :unknown" orphaned))orphaned))))diff --git a/src/metabase/testing_api/api.clj b/src/metabase/testing_api/api.cljindex 139914768c7..f2d6d193f74 100644--- a/src/metabase/testing_api/api.clj+++ b/src/metabase/testing_api/api.clj@@ -21,12 +21,12 @@[metabase.search.ingestion :as search.ingestion][metabase.search.task.search-index :as task.search-index][metabase.session.api :as session.api]+ [metabase.testing-api.db :as testing-api.db][metabase.util.date-2 :as u.date][metabase.util.files :as u.files][metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2])+ [metabase.util.malli.schema :as ms])(:import(com.mchange.v2.c3p0 PoolBackedDataSource)(java.util Queue)@@ -214,8 +214,8 @@{:status 400}))))(t/minus (t/local-date) (t/months 7)))](case model- "card" (t2/update! :model/Card :id id {:last_used_at date})- "dashboard" (t2/update! :model/Dashboard :id id {:last_viewed_at date}))))+ "card" (testing-api.db/set-card-last-used-at! id date)+ "dashboard" (testing-api.db/set-dashboard-last-viewed-at! id date))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -297,8 +297,8 @@_query-params{:keys [advisories]} :- [:map[:advisories [:sequential TestAdvisory]]]]- (t2/delete! :model/SecurityAdvisory)- (t2/insert-returning-instances! :model/SecurityAdvisory advisories))+ (testing-api.db/delete-all-security-advisories!)+ (testing-api.db/insert-security-advisories! advisories))(api.macros/defendpoint :post "/native-query" :- ::lib.schema/query"Creates a native query from a test query spec."@@ -335,48 +335,48 @@(defn- e2e-usage-auditing-group-id![]- (or (t2/select-one-pk :model/PermissionsGroup :name e2e-usage-auditing-group-name)- (t2/insert-returning-pk! :model/PermissionsGroup {:name e2e-usage-auditing-group-name})))+ (or (testing-api.db/permissions-group-id e2e-usage-auditing-group-name)+ (testing-api.db/insert-permissions-group! e2e-usage-auditing-group-name)))(defn- ensure-seeded-usage-auditing-group-membership]- (when-not (t2/exists? :model/PermissionsGroupMembership :user_id user-id :group_id group-id)+ (when-not (testing-api.db/group-membership-exists? user-id group-id)(perms/add-user-to-group! user-id group-id))))(defn- delete-seeded-usage-auditing-data![]- (t2/delete! :model/AiUsageLog {:where [:in :conversation_id e2e-usage-auditing-conversation-ids]})- (t2/delete! :model/MetabotConversation {:where [:in :id e2e-usage-auditing-conversation-ids]}))+ (testing-api.db/delete-ai-usage-logs-for-conversations! e2e-usage-auditing-conversation-ids)+ (testing-api.db/delete-metabot-conversations! e2e-usage-auditing-conversation-ids))(defn- insert-seeded-usage-auditing-conversation![{:keys [id user-id created-at source profile-id prompt-tokens completion-tokens total-tokens roles ip-address tenant-id]}]- (t2/insert! :model/MetabotConversation- {:id id- :user_id user-id- :title "E2E usage auditing conversation"- :created_at created-at- :ip_address ip-address})+ (testing-api.db/insert-metabot-conversation!+ {:id id+ :user_id user-id+ :title "E2E usage auditing conversation"+ :created_at created-at+ :ip_address ip-address})(doseq [role roles]- (t2/insert! :model/MetabotMessage- {:conversation_id id- :user_id user-id- :role role- :profile_id profile-id- :data []- :data_version 2- :total_tokens 0- :created_at created-at}))- (t2/insert! :model/AiUsageLog- (cond-> {:source source- :model "anthropic/claude-sonnet-4-6"- :conversation_id id- :user_id user-id- :prompt_tokens prompt-tokens- :completion_tokens completion-tokens- :total_tokens total-tokens- :created_at created-at}- tenant-id (assoc :tenant_id tenant-id))))+ (testing-api.db/insert-metabot-message!+ {:conversation_id id+ :user_id user-id+ :role role+ :profile_id profile-id+ :data []+ :data_version 2+ :total_tokens 0+ :created_at created-at}))+ (testing-api.db/insert-ai-usage-log!+ (cond-> {:source source+ :model "anthropic/claude-sonnet-4-6"+ :conversation_id id+ :user_id user-id+ :prompt_tokens prompt-tokens+ :completion_tokens completion-tokens+ :total_tokens total-tokens+ :created_at created-at}+ tenant-id (assoc :tenant_id tenant-id))))(defn- seed-usage-auditing-data!([user-id second-user-id]@@ -406,9 +406,9 @@(ensure-seeded-usage-auditing-group-membership! user-id)(ensure-seeded-usage-auditing-group-membership! second-user-id)(when tenant-id- (t2/update! :model/User user-id {:tenant_id tenant-id}))+ (testing-api.db/set-user-tenant! user-id tenant-id))(when second-tenant-id- (t2/update! :model/User second-user-id {:tenant_id second-tenant-id}))+ (testing-api.db/set-user-tenant! second-user-id second-tenant-id))(delete-seeded-usage-auditing-data!)(doseq [conversation [{:id (nth e2e-usage-auditing-conversation-ids 0):user-id user-id@@ -537,13 +537,13 @@[:user_id ms/PositiveInt][:count ms/PositiveInt]]](dotimes [_ count]- (t2/insert! :model/AiUsageLog- {:source e2e-usage-source- :model "test/model"- :prompt_tokens 0- :completion_tokens 0- :total_tokens 0- :user_id user_id}))+ (testing-api.db/insert-ai-usage-log!+ {:source e2e-usage-source+ :model "test/model"+ :prompt_tokens 0+ :completion_tokens 0+ :total_tokens 0+ :user_id user_id}))(clear-metabot-limit-cache!){:inserted count})@@ -555,7 +555,7 @@_query-params{:keys [user_id]} :- [:map[:user_id ms/PositiveInt]]]- (let [deleted (t2/delete! :model/AiUsageLog :user_id user_id :source e2e-usage-source)]+ (let [deleted (testing-api.db/delete-ai-usage-logs-for-user-and-source! user_id e2e-usage-source)](clear-metabot-limit-cache!){:deleted deleted}))diff --git a/src/metabase/testing_api/db.clj b/src/metabase/testing_api/db.cljnew file mode 100644index 00000000000..dcbd2c2b2ac--- /dev/null+++ b/src/metabase/testing_api/db.clj@@ -0,0 +1,75 @@+(ns metabase.testing-api.db+ "Application database queries for the testing API module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn set-card-last-used-at!+ "Set `last_used_at` of the Card with `card-id`."+ [card-id last-used-at]+ (t2/update! :model/Card :id card-id {:last_used_at last-used-at}))++(defn set-dashboard-last-viewed-at!+ "Set `last_viewed_at` of the Dashboard with `dashboard-id`."+ [dashboard-id last-viewed-at]+ (t2/update! :model/Dashboard :id dashboard-id {:last_viewed_at last-viewed-at}))++(defn delete-all-security-advisories!+ "Delete every SecurityAdvisory."+ []+ (t2/delete! :model/SecurityAdvisory))++(defn insert-security-advisories!+ "Insert `advisories` and return the inserted SecurityAdvisory instances."+ [advisories]+ (t2/insert-returning-instances! :model/SecurityAdvisory advisories))++(defn permissions-group-id+ "The id of the PermissionsGroup named `group-name`, or nil."+ [group-name]+ (t2/select-one-pk :model/PermissionsGroup :name group-name))++(defn insert-permissions-group!+ "Insert a PermissionsGroup named `group-name` and return its id."+ [group-name]+ (t2/insert-returning-pk! :model/PermissionsGroup {:name group-name}))++(defn group-membership-exists?+ "Whether the User with `user-id` is a member of the PermissionsGroup with `group-id`."+ [user-id group-id]+ (t2/exists? :model/PermissionsGroupMembership :user_id user-id :group_id group-id))++(defn delete-ai-usage-logs-for-conversations!+ "Delete the AiUsageLog rows for `conversation-ids`."+ [conversation-ids]+ (t2/delete! :model/AiUsageLog {:where [:in :conversation_id conversation-ids]}))++(defn delete-metabot-conversations!+ "Delete the MetabotConversations with `conversation-ids`."+ [conversation-ids]+ (t2/delete! :model/MetabotConversation {:where [:in :id conversation-ids]}))++(defn insert-metabot-conversation!+ "Insert the MetabotConversation `row`."+ [row]+ (t2/insert! :model/MetabotConversation row))++(defn insert-metabot-message!+ "Insert the MetabotMessage `row`."+ [row]+ (t2/insert! :model/MetabotMessage row))++(defn insert-ai-usage-log!+ "Insert the AiUsageLog `row`."+ [row]+ (t2/insert! :model/AiUsageLog row))++(defn set-user-tenant!+ "Set the `tenant_id` of the User with `user-id`."+ [user-id tenant-id]+ (t2/update! :model/User user-id {:tenant_id tenant-id}))++(defn delete-ai-usage-logs-for-user-and-source!+ "Delete the AiUsageLog rows of the User with `user-id` from `source`, returning the number deleted."+ [user-id source]+ (t2/delete! :model/AiUsageLog :user_id user-id :source source))diff --git a/src/metabase/tiles/api.clj b/src/metabase/tiles/api.cljindex 960bebbc419..7d6bc72f19c 100644--- a/src/metabase/tiles/api.clj+++ b/src/metabase/tiles/api.clj@@ -16,14 +16,14 @@[metabase.query-processor.card :as qp.card][metabase.query-processor.core :as qp][metabase.query-processor.dashboard :as qp.dashboard]+ [metabase.tiles.db :as tiles.db][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.json :as json][metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]- [metabase.util.web-mercator :as mercator]- [toucan2.core :as t2])+ [metabase.util.web-mercator :as mercator])(:import(java.awt Color)(java.awt.image BufferedImage)@@ -302,7 +302,7 @@[:parameters {:optional true} ::parameters.schema/api.parameter-values][:latField ::legacy-ref][:lonField ::legacy-ref]]]- (process-tiles-query-for-card (api/check-404 (t2/select-one :model/Card card-id))+ (process-tiles-query-for-card (api/check-404 (tiles.db/card card-id))parameters zoom x y lat-field lon-field));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -324,7 +324,7 @@[:parameters {:optional true} ::parameters.schema/api.parameter-values][:latField ::legacy-ref][:lonField ::legacy-ref]]]- (process-tiles-query-for-dashcard (api/check-404 (t2/select-one :model/Dashboard dashboard-id))- (api/check-404 (t2/select-one :model/DashboardCard dashcard-id))- (api/check-404 (t2/select-one :model/Card card-id))+ (process-tiles-query-for-dashcard (api/check-404 (tiles.db/dashboard dashboard-id))+ (api/check-404 (tiles.db/dashcard dashcard-id))+ (api/check-404 (tiles.db/card card-id))parameters zoom x y lat-field lon-field))diff --git a/src/metabase/tiles/db.clj b/src/metabase/tiles/db.cljnew file mode 100644index 00000000000..5bc5df404d6--- /dev/null+++ b/src/metabase/tiles/db.clj@@ -0,0 +1,20 @@+(ns metabase.tiles.db+ "Application database queries for the tiles module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card card-id))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard dashboard-id))++(defn dashcard+ "The DashboardCard with `dashcard-id`, or nil."+ [dashcard-id]+ (t2/select-one :model/DashboardCard dashcard-id))diff --git a/src/metabase/timeline/api/timeline.clj b/src/metabase/timeline/api/timeline.cljindex fb7c32e7f2a..788f4aca828 100644--- a/src/metabase/timeline/api/timeline.clj+++ b/src/metabase/timeline/api/timeline.clj@@ -6,6 +6,7 @@[metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as collection.root][metabase.events.core :as events]+ [metabase.timeline.db :as timeline.db][metabase.timeline.models.timeline :as timeline][metabase.timeline.models.timeline-event :as timeline-event][metabase.util :as u]@@ -41,7 +42,7 @@{:creator_id api/*current-user-id*}(when-not icon{:icon timeline-event/default-icon}))]- (u/prog1 (first (t2/insert-returning-instances! :model/Timeline tl))+ (u/prog1 (timeline.db/insert-timeline! tl)(events/publish-event! :event/timeline-create {:object <> :user-id api/*current-user-id*}))))(mu/defn list-timelines :- [:sequential (ms/InstanceOf :model/Timeline)]@@ -49,16 +50,12 @@([](list-timelines false))([archived :- ms/BooleanValue]- (t2/select :model/Timeline- {:where [:and- [:= :archived archived]- (collection/visible-collection-filter-clause)]- :order-by [[:%lower.name :asc]]})))+ (timeline.db/timelines-in-collections archived (collection/visible-collection-filter-clause))))(mu/defn get-timeline :- [:maybe (ms/InstanceOf :model/Timeline)]"Fetch a single timeline by ID. Checks read permissions but does not hydrate."[id :- ms/PositiveInt]- (api/read-check (t2/select-one :model/Timeline :id id)))+ (api/read-check (timeline.db/timeline id)))(api.macros/defendpoint :get "/" :- [:sequential ::Timeline]"Fetch a list of `Timeline`s. Can include `archived=true` to return archived timelines."@@ -113,15 +110,15 @@[:collection_id {:optional true} [:maybe ms/PositiveInt]][:archived {:optional true} [:maybe :boolean]]]](let [existing (api/write-check :model/Timeline id)- current-archived (:archived (t2/select-one :model/Timeline :id id))]+ current-archived (:archived (timeline.db/timeline id))](collection/check-allowed-to-change-collection existing timeline-updates)- (t2/update! :model/Timeline id- (u/select-keys-when timeline-updates- :present #{:description :icon :collection_id :default :archived}- :non-nil #{:name}))+ (timeline.db/update-timeline! id+ (u/select-keys-when timeline-updates+ :present #{:description :icon :collection_id :default :archived}+ :non-nil #{:name}))(when (and (some? archived) (not= current-archived archived))- (t2/update! :model/TimelineEvent {:timeline_id id} {:archived archived}))- (u/prog1 (t2/hydrate (t2/select-one :model/Timeline :id id) :creator [:collection :can_write] :is_remote_synced)+ (timeline.db/set-timeline-events-archived! id archived))+ (u/prog1 (t2/hydrate (timeline.db/timeline id) :creator [:collection :can_write] :is_remote_synced)(events/publish-event! :event/timeline-update {:object <> :user-id api/*current-user-id*}))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -133,7 +130,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](let [timeline (api/write-check :model/Timeline id)]- (t2/delete! :model/Timeline :id id)+ (timeline.db/delete-timeline! id)(events/publish-event! :event/timeline-delete {:object timeline :user-id api/*current-user-id*}))api/generic-204-no-content)@@ -162,6 +159,6 @@{:keys [include archived]} :- [:map[:include {:optional true} [:maybe [:= "events"]]][:archived {:default false} [:maybe :boolean]]]]- (api/read-check (t2/select-one :model/Collection :id id))+ (api/read-check (timeline.db/collection id))(timeline/timelines-for-collection id {:timeline/events? (= include "events"):timeline/archived? archived}))diff --git a/src/metabase/timeline/api/timeline_event.clj b/src/metabase/timeline/api/timeline_event.cljindex 7408642a928..0acb769c6de 100644--- a/src/metabase/timeline/api/timeline_event.clj+++ b/src/metabase/timeline/api/timeline_event.clj@@ -6,12 +6,12 @@[metabase.api.macros :as api.macros][metabase.collections.models.collection :as collection][metabase.events.core :as events]+ [metabase.timeline.db :as timeline.db][metabase.timeline.models.timeline-event :as timeline-event][metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.i18n :refer [tru]]- [metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.util.malli.schema :as ms]));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -34,7 +34,7 @@[:question_id {:optional true} [:maybe ms/PositiveInt]][:archived {:optional true} [:maybe :boolean]]]];; deliberately not using api/check-404 so we can have a useful error message.- (let [timeline (t2/select-one :model/Timeline :id timeline_id)]+ (let [timeline (timeline.db/timeline timeline_id)](when-not timeline(throw (ex-info (tru "Timeline with id {0} not found" timeline_id){:status-code 404})))@@ -47,15 +47,15 @@{:creator_id api/*current-user-id*:timestamp parsed}(when-not icon- {:icon (t2/select-one-fn :icon :model/Timeline :id timeline_id)}))]+ {:icon (timeline.db/timeline-icon timeline_id)}))](analytics/track-event! :snowplow/timeline(cond-> {:event :new-event-created:time_matters time_matters:collection_id (:collection_id timeline)}(boolean source) (assoc :source source)(boolean question_id) (assoc :question_id question_id)))- (u/prog1 (first (t2/insert-returning-instances! :model/TimelineEvent tl-event))- (events/publish-event! :event/timeline-create {:object (t2/select-one :model/Timeline :id (:timeline_id <>)) :user-id api/*current-user-id*})))))+ (u/prog1 (timeline.db/insert-timeline-event! tl-event)+ (events/publish-event! :event/timeline-create {:object (timeline.db/timeline (:timeline_id <>)) :user-id api/*current-user-id*})))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -93,12 +93,12 @@(when (api/column-will-change? :timeline_id existing timeline-event-updates)(api/write-check :model/Timeline (:timeline_id timeline-event-updates)));; todo: if we accept a new timestamp, must we require a timezone? gut says yes?- (t2/update! :model/TimelineEvent id- (u/select-keys-when timeline-event-updates- :present #{:description :timestamp :time_matters :timezone :icon :timeline_id :archived}- :non-nil #{:name}))- (u/prog1 (t2/select-one :model/TimelineEvent :id id)- (events/publish-event! :event/timeline-update {:object (t2/select-one :model/Timeline :id (:timeline_id <>)) :user-id api/*current-user-id*}))))+ (timeline.db/update-timeline-event! id+ (u/select-keys-when timeline-event-updates+ :present #{:description :timestamp :time_matters :timezone :icon :timeline_id :archived}+ :non-nil #{:name}))+ (u/prog1 (timeline.db/timeline-event id)+ (events/publish-event! :event/timeline-update {:object (timeline.db/timeline (:timeline_id <>)) :user-id api/*current-user-id*}))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -110,6 +110,6 @@[:id ms/PositiveInt]]](api/write-check :model/TimelineEvent id)(let [timeline-event (api/write-check :model/TimelineEvent id)]- (t2/delete! :model/TimelineEvent :id id)- (events/publish-event! :event/timeline-delete {:object (t2/select-one :model/Timeline :id (:timeline_id timeline-event)) :user-id api/*current-user-id*}))+ (timeline.db/delete-timeline-event! id)+ (events/publish-event! :event/timeline-delete {:object (timeline.db/timeline (:timeline_id timeline-event)) :user-id api/*current-user-id*}))api/generic-204-no-content)diff --git a/src/metabase/timeline/db.clj b/src/metabase/timeline/db.cljnew file mode 100644index 00000000000..c1d38783cca--- /dev/null+++ b/src/metabase/timeline/db.clj@@ -0,0 +1,105 @@+(ns metabase.timeline.db+ "Application database queries for the timeline module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn insert-timeline!+ "Insert the Timeline `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Timeline row))++(defn timelines-in-collections+ "The Timelines whose archived flag is `archived` in the Collections matching the Honey SQL `collection-clause`, in+ case-insensitive name order."+ [archived collection-clause]+ (t2/select :model/Timeline+ {:where [:and+ [:= :archived archived]+ collection-clause]+ :order-by [[:%lower.name :asc]]}))++(defn timeline+ "The Timeline with `id`, or nil."+ [id]+ (t2/select-one :model/Timeline :id id))++(defn timeline-icon+ "The icon of the Timeline with `id`, or nil."+ [id]+ (t2/select-one-fn :icon :model/Timeline :id id))++(defn timelines-by-id+ "A map of id to Timeline for the Timelines with `ids`."+ [ids]+ (t2/select-pk->fn identity :model/Timeline :id [:in ids]))++(defn timelines-for-collection+ "The Timelines of the Collection with `collection-id` whose archived flag is `archived`."+ [collection-id archived]+ (t2/select :model/Timeline :collection_id collection-id :archived archived))++(defn update-timeline!+ "Apply `changes` to the Timeline with `id`."+ [id changes]+ (t2/update! :model/Timeline id changes))++(defn set-timeline-events-archived!+ "Set the archived flag of the TimelineEvents of the Timeline with `timeline-id`."+ [timeline-id archived]+ (t2/update! :model/TimelineEvent {:timeline_id timeline-id} {:archived archived}))++(defn delete-timeline!+ "Delete the Timeline with `id`."+ [id]+ (t2/delete! :model/Timeline :id id))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn insert-timeline-event!+ "Insert the TimelineEvent `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/TimelineEvent row))++(defn timeline-event+ "The TimelineEvent with `id`, or nil."+ [id]+ (t2/select-one :model/TimelineEvent :id id))++(defn timeline-events-for-timelines+ "The TimelineEvents of the Timelines with `timeline-ids`, unarchived only unless `all?`, and (when `start` and/or+ `end` are given) within that time range (respecting each event's `:time_matters` flag)."+ [timeline-ids all? start end]+ (t2/select :model/TimelineEvent+ {:where [:and+ [:in :timeline_id timeline-ids]+ (when-not all?+ [:= :archived false])+ (when (or start end)+ [:or+ [:and+ [:= :time_matters true]+ (when start+ [:<= start :timestamp])+ (when end+ [:<= :timestamp end])]+ [:and+ [:= :time_matters false]+ (when start+ [:<= (h2x/->date start) (h2x/->date :timestamp)])+ (when end+ [:<= (h2x/->date :timestamp) (h2x/->date end)])]])]}))++(defn update-timeline-event!+ "Apply `changes` to the TimelineEvent with `id`."+ [id changes]+ (t2/update! :model/TimelineEvent id changes))++(defn delete-timeline-event!+ "Delete the TimelineEvent with `id`."+ [id]+ (t2/delete! :model/TimelineEvent :id id))diff --git a/src/metabase/timeline/models/timeline.clj b/src/metabase/timeline/models/timeline.cljindex ab6f8f4343e..7e24bd48b7b 100644--- a/src/metabase/timeline/models/timeline.clj+++ b/src/metabase/timeline/models/timeline.clj@@ -3,6 +3,7 @@[metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as collection.root][metabase.models.serialization :as serdes]+ [metabase.timeline.db :as timeline.db][metabase.timeline.models.timeline-event :as timeline-event][methodical.core :as methodical][toucan2.core :as t2]))@@ -38,11 +39,7 @@"Load timelines based on `collection-id` passed in (nil means the root collection). Hydrates the events on eachtimeline at `:events` on the timeline."[collection-id {:keys [timeline/events? timeline/archived?] :as options}]- (cond-> (t2/hydrate (t2/select :model/Timeline- :collection_id collection-id- :archived (boolean archived?))- :creator- [:collection :can_write])+ (cond-> (t2/hydrate (timeline.db/timelines-for-collection collection-id (boolean archived?)) :creator [:collection :can_write])(nil? collection-id) (->> (map collection.root/hydrate-root-collection))events? (timeline-event/include-events options)))diff --git a/src/metabase/timeline/models/timeline_event.clj b/src/metabase/timeline/models/timeline_event.cljindex 69725a082f3..c9c5131193a 100644--- a/src/metabase/timeline/models/timeline_event.clj+++ b/src/metabase/timeline/models/timeline_event.clj@@ -2,7 +2,7 @@(:require[metabase.models.interface :as mi][metabase.models.serialization :as serdes]- [metabase.util.honey-sql-2 :as h2x]+ [metabase.timeline.db :as timeline.db][methodical.core :as methodical][toucan2.core :as t2]))@@ -45,7 +45,7 @@(defmethod mi/perms-objects-set :model/TimelineEvent[event read-or-write](let [timeline (or (:timeline event)- (t2/select-one 'Timeline :id (:timeline_id event)))]+ (timeline.db/timeline (:timeline_id event)))](mi/perms-objects-set timeline read-or-write)))(defmethod mi/can-create? :model/TimelineEvent@@ -58,7 +58,7 @@[_model k events](mi/instances-with-hydrated-dataevents k- #(t2/select-pk->fn identity :model/Timeline :id [:in (map :timeline_id events)])+ #(timeline.db/timelines-by-id (map :timeline_id events)):timeline_id))(defn- fetch-events@@ -66,29 +66,7 @@well as `all?`. By default, will return only unarchived events, unless `all?` is truthy and will return all eventsregardless of archive state."[timeline-ids {:events/keys [all? start end]}]- (let [clause {:where [:and- ;; in our collections- [:in :timeline_id timeline-ids]- (when-not all?- [:= :archived false])- (when (or start end)- [:or- ;; absolute time in bounds- [:and- [:= :time_matters true]- ;; less than or equal?- (when start- [:<= start :timestamp])- (when end- [:<= :timestamp end])]- ;; non-specic time in bounds- [:and- [:= :time_matters false]- (when start- [:<= (h2x/->date start) (h2x/->date :timestamp)])- (when end- [:<= (h2x/->date :timestamp) (h2x/->date end)])]])]}]- (t2/hydrate (t2/select :model/TimelineEvent clause) :creator)))+ (t2/hydrate (timeline.db/timeline-events-for-timelines timeline-ids all? start end) :creator))(defn include-events"Include events on `timelines` passed in. Options are optional and include whether to return unarchived events or all@@ -112,9 +90,7 @@(defn dashcard-timeline-events"Look for a timeline and corresponding events associated with this dashcard."[{{:keys [collection_id] :as _card} :card}]- (let [timelines (t2/select :model/Timeline- :collection_id collection_id- :archived false)]+ (let [timelines (timeline.db/timelines-for-collection collection_id false)](->> (t2/hydrate timelines :creator [:collection :can_write])(map #(include-events-singular % {:events/all? true})))))diff --git a/src/metabase/transforms/canceling.clj b/src/metabase/transforms/canceling.cljindex 4713da74825..ab2dc0cf8fc 100644--- a/src/metabase/transforms/canceling.clj+++ b/src/metabase/transforms/canceling.clj@@ -9,12 +9,12 @@[metabase.run-tracking.core :as rt][metabase.task.core :as task][metabase.tracing.core :as tracing]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.transform-run :as transform-run][metabase.transforms.models.transform-run-cancelation :as wr.cancelation][metabase.util :as u][metabase.util.jvm :as u.jvm]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.time OffsetDateTime)(java.util.concurrent Executors ScheduledExecutorService TimeUnit)))@@ -193,7 +193,7 @@(try;; Skip silently if the run was deleted between cancelation insert and now;; — `chan-signal-cancel!` would be a no-op anyway in that case.- (when-let [run (t2/select-one :model/TransformRun :id id)]+ (when-let [run (transforms.db/run id)](cancel-run! run request-time))(catch Throwable t(log/error (str "Error canceling " id ": " (ex-message t)))))))diff --git a/src/metabase/transforms/coordinated_run.clj b/src/metabase/transforms/coordinated_run.cljindex 258911f6b66..0e9fad8dced 100644--- a/src/metabase/transforms/coordinated_run.clj+++ b/src/metabase/transforms/coordinated_run.clj@@ -6,51 +6,60 @@(:require[metabase.run-tracking.core :as rt][metabase.transforms.canceling :as canceling]- [metabase.transforms.models.transform-run-cancelation :as transform-run-cancelation]- [toucan2.core :as t2]))+ [metabase.transforms.db :as transforms.db]+ [metabase.transforms.models.transform-run-cancelation :as transform-run-cancelation]))(set! *warn-on-reflection* true)+(defn- touch-active-run!+ [model run-id]+ (case model+ :model/TransformJobRun (transforms.db/touch-active-job-run! run-id)+ :model/TransformDagRun (transforms.db/touch-active-dag-run! run-id)))++(defn- finish-active-run!+ [model run-id changes]+ (case model+ :model/TransformJobRun (transforms.db/finish-active-job-run! run-id changes)+ :model/TransformDagRun (transforms.db/finish-active-dag-run! run-id changes)))+(defn add-run-activity!"Note that a run has had activity (touches `updated_at`)."[model run-id]- (t2/update! model :id run-id :is_active true {:updated_at :%now}))+ (touch-active-run! model run-id))(defn succeed-started-run!"Mark a started run as successfully completed."([model run-id](succeed-started-run! model run-id {}))([model run-id properties]- (t2/update! model- :id run-id- :is_active true- (merge {:end_time :%now}- properties- {:status :succeeded- :is_active nil}))))+ (finish-active-run! model+ run-id+ (merge {:end_time :%now}+ properties+ {:status :succeeded+ :is_active nil}))))(defn fail-started-run!"Mark the started active run as failed and inactive."[model run-id properties]- (t2/update! model- :id run-id- :is_active true- (merge {:end_time :%now}- properties- {:status :failed- :is_active nil})))+ (finish-active-run! model+ run-id+ (merge {:end_time :%now}+ properties+ {:status :failed+ :is_active nil})))(defn cancel-started-run!"Mark an active run as canceled; a finished run is never resurrected into a canceled state.Returns the number of rows updated — 0 if the run had already finished."[model run-id]- (t2/update! model- :id run-id- :is_active true- {:status :canceled- :is_active nil- :end_time :%now- :message "Canceled"}))+ (finish-active-run! model+ run-id+ {:status :canceled+ :is_active nil+ :end_time :%now+ :message "Canceled"}))(defn cancel!"Cancel an in-progress coordinated run: mark it canceled and request cancellation of its@@ -60,7 +69,7 @@[model member-fk run-id](boolean(when (pos? (cancel-started-run! model run-id))- (doseq [member-run-id (t2/select-pks-vec :model/TransformRun member-fk run-id :is_active true)]+ (doseq [member-run-id (transforms.db/active-run-ids-of-parent member-fk run-id)](transform-run-cancelation/mark-cancel-started-run! member-run-id)(canceling/chan-signal-cancel! member-run-id))true)))diff --git a/src/metabase/transforms/crud.clj b/src/metabase/transforms/crud.cljindex 3d0eaecdf0d..2b46cb8590e 100644--- a/src/metabase/transforms/crud.clj+++ b/src/metabase/transforms/crud.clj@@ -14,6 +14,7 @@[metabase.transforms-base.interface :as transforms-base.i][metabase.transforms-base.ordering :as transforms-base.ordering][metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.transform :as transform.model][metabase.transforms.util :as transforms.u][metabase.util :as u]@@ -26,7 +27,7 @@(defn check-database-feature"Check that the target database supports the required features for this transform."[transform]- (let [database (api/check-400 (t2/select-one :model/Database (transforms-base.i/target-db-id transform))+ (let [database (api/check-400 (transforms.db/database (transforms-base.i/target-db-id transform))(deferred-tru "The target database cannot be found."))features (transforms-base.u/required-database-features transform)](api/check-400 (not (:is_sample database))@@ -59,7 +60,7 @@and leaves the Metabase table with zero fields."[transform](let [db-id (transforms-base.i/target-db-id transform)- db (t2/select-one :model/Database db-id)]+ db (transforms.db/database db-id)](when (and db (driver.u/supports? (:engine db) :schemas db))(api/check-400 (not (str/blank? (get-in transform [:target :schema])))(deferred-tru "A target schema is required for this database.")))))@@ -77,7 +78,7 @@[{:keys [source] :as transform}](when (transforms-base.u/checkpoint-source? transform)(let [checkpoint-filter-field-id (get-in source [:source-incremental-strategy :checkpoint-filter-field-id])- field (t2/select-one :model/Field checkpoint-filter-field-id)]+ field (transforms.db/field checkpoint-filter-field-id)](api/check-400 field (deferred-tru "Checkpoint field not found."))(let [column (field->column field)](api/check-400 (transforms-base.u/supported-checkpoint-column? column)@@ -91,7 +92,7 @@[{:keys [source] :as transform}](let [{:keys [lookback checkpoint-filter-field-id]} (:source-incremental-strategy source)](when-let [{:keys [unit]} (and (transforms-base.u/checkpoint-source? transform) lookback)]- (when-let [field (t2/select-one :model/Field checkpoint-filter-field-id)]+ (when-let [field (transforms.db/field checkpoint-filter-field-id)](let [column (field->column field)](api/check-400 (lib.types.isa/date-or-datetime? column)(deferred-tru "A lookback window is only supported for date or datetime checkpoint columns."))@@ -117,10 +118,7 @@[& {:keys [last-run-start-time last-run-statuses tag-ids database-id]}](let [enabled-types (transforms.u/enabled-source-types-for-user)](api/check-403 (seq enabled-types))- (let [transforms (t2/select :model/Transform {:where (into [:and [:in :source_type enabled-types]]- (when database-id- [[:= :source_database_id database-id]]))- :order-by [[:id :asc]]})]+ (let [transforms (transforms.db/transforms-of-source-types enabled-types database-id)](->> (t2/hydrate transforms :last_run :transform_tag_ids :creator :owner :can_read :can_write :can_execute)(into [](comp (transforms-base.u/->date-field-filter-xf [:last_run :start_time] last-run-start-time)@@ -133,7 +131,7 @@"The index methods the target db's driver can create on `transform`'s target table, or nil when none are available."[transform](when-let [db-id (transforms-base.i/target-db-id transform)]- (when-let [database (t2/select-one :model/Database db-id)]+ (when-let [database (transforms.db/database db-id)](let [methods (try(driver/supported-index-methods (:engine database) database)(catch Throwable e@@ -170,8 +168,7 @@;; Set owner_user_id to current user if not explicitly providedowner-user-id (when-not (:owner_email body)(or (:owner_user_id body) creator-id))- transform (t2/insert-returning-instance!- :model/Transform+ transform (transforms.db/insert-transform!(assoc (select-keys body [:name :description :source :target :run_trigger:collection_id :owner_email]):creator_id creator-id@@ -190,7 +187,7 @@[id body](let [transform (t2/with-transaction [_];; Cycle detection should occur within the transaction to avoid race- (let [old (t2/select-one :model/Transform id)+ (let [old (transforms.db/transform id)new (merge old body)target-fields #(-> % :target (select-keys [:schema :name]))](api/check-403 (and (mi/can-write? old) (mi/can-write? new)))@@ -213,11 +210,11 @@(transforms-base.u/target-table-exists? new)))403(deferred-tru "A table with that name already exists.")))- (t2/update! :model/Transform id (dissoc body :tag_ids))+ (transforms.db/update-transform! id (dissoc body :tag_ids));; Update tag associations if provided(when (contains? body :tag_ids)(transform.model/update-transform-tags! id (:tag_ids body)))- (t2/hydrate (t2/select-one :model/Transform id) :transform_tag_ids :creator :owner :can_read :can_write :can_execute))]+ (t2/hydrate (transforms.db/transform id) :transform_tag_ids :creator :owner :can_read :can_write :can_execute))](events/publish-event! :event/transform-update {:object transform :user-id api/*current-user-id*})(-> transformtransforms.u/add-source-readable)))@@ -225,7 +222,7 @@(defn delete-transform!"Delete a transform and publish the delete event."[transform]- (t2/delete! :model/Transform (:id transform))+ (transforms.db/delete-transform! (:id transform))(events/publish-event! :event/transform-delete{:object transform:user-id api/*current-user-id*})diff --git a/src/metabase/transforms/dag.clj b/src/metabase/transforms/dag.cljindex de3d6ae6b5e..91792c603da 100644--- a/src/metabase/transforms/dag.clj+++ b/src/metabase/transforms/dag.clj@@ -11,11 +11,11 @@[metabase.tracing.core :as tracing][metabase.transforms-base.ordering :as ordering][metabase.transforms.coordinated-run :as coordinated-run]+ [metabase.transforms.db :as transforms.db][metabase.transforms.jobs :as jobs][metabase.transforms.models.dag-run :as dag-run][metabase.transforms.util :as transforms.u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -53,11 +53,11 @@"Transforms with only the columns the ordering walk needs — avoids loading every transform's fullrow just to compute the dependency graph (full rows are fetched only for the resulting closure)."[]- (t2/select [:model/Transform :id :target :target_table_id :created_at :table_dependencies]))+ (transforms.db/transform-dependency-rows))(defn- full-transforms [ids](if (seq ids)- (t2/select :model/Transform :id [:in ids])+ (transforms.db/transforms ids)[]))(defn- dag-run-plandiff --git a/src/metabase/transforms/db.clj b/src/metabase/transforms/db.cljnew file mode 100644index 00000000000..3e9c91bddab--- /dev/null+++ b/src/metabase/transforms/db.clj@@ -0,0 +1,759 @@+(ns metabase.transforms.db+ "Application database queries for the transforms module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration methods,+ and transactions."+ (:require+ [medley.core :as m]+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(def ^:private no-active-run-clause+ "Honey SQL clause matching TransformRunCancelation rows whose run is no longer active."+ [:not [:exists ^:allow-subquery+ {:select [1]+ :from [[:transform_run :wr]]+ :where [:and+ [:= :wr.id :transform_run_cancelation.run_id]+ :wr.is_active]}]])++;;; ------------------------------------------------ Transform ------------------------------------------------++(defn transform+ "The Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/Transform :id transform-id))++(defn transforms+ "The Transforms with `transform-ids`."+ [transform-ids]+ (t2/select :model/Transform :id [:in transform-ids]))++(defn transforms-of-source-types+ "The Transforms whose source type is one of `source-types`, optionally narrowed to `database-id`, ordered by ID."+ [source-types database-id]+ (t2/select :model/Transform {:where [:and+ [:in :source_type source-types]+ (when database-id [:= :source_database_id database-id])]+ :order-by [[:id :asc]]}))++(defn transform-dependency-rows+ "The ID, target, target Table ID, creation time, and table dependencies of every Transform."+ []+ (t2/select [:model/Transform :id :target :target_table_id :created_at :table_dependencies]))++(defn transform-snapshot+ "The name, entity ID, and source type of the Transform with `transform-id`."+ [transform-id]+ (t2/select-one [:model/Transform :name :entity_id :source_type] :id transform-id))++(defn transform-summaries-by-id+ "A map of ID to the ID, name, and Collection ID of the Transforms with `transform-ids`."+ [transform-ids]+ (t2/select-pk->fn identity [:model/Transform :id :name :collection_id] :id [:in transform-ids]))++(defn transform-names-by-id+ "A map of ID to name for the Transforms with `transform-ids`."+ [transform-ids]+ (t2/select-pk->fn :name :model/Transform :id [:in transform-ids]))++(defn transform-last-checkpoint-value+ "The last checkpoint value of the Transform with `transform-id`."+ [transform-id]+ (t2/select-one-fn :last_checkpoint_value [:model/Transform :last_checkpoint_value] transform-id))++(defn transform-collection-id+ "The Collection ID of the Transform with `transform-id`."+ [transform-id]+ (t2/select-one-fn :collection_id :model/Transform :id transform-id))++(defn insert-transform!+ "Insert `transform` and return the new instance."+ [transform]+ (t2/insert-returning-instance! :model/Transform transform))++(defn update-transform!+ "Apply `changes` to the Transform with `transform-id`."+ [transform-id changes]+ (t2/update! :model/Transform transform-id changes))++(defn delete-transform!+ "Delete the Transform with `transform-id`."+ [transform-id]+ (t2/delete! :model/Transform transform-id))++;;; ---------------------------------------------- Transform tags ----------------------------------------------++(defn tag+ "The TransformTag with `tag-id`, or nil."+ [tag-id]+ (t2/select-one :model/TransformTag :id tag-id))++(defn existing-tag-ids+ "The subset of `tag-ids` that exist."+ [tag-ids]+ (t2/select-fn-set :id :model/TransformTag :id [:in tag-ids]))++(defn tag-name-exists?+ "Whether a TransformTag named `tag-name` exists."+ [tag-name]+ (t2/exists? :model/TransformTag :name tag-name))++(defn tag-name-exists-excluding?+ "Whether a TransformTag named `tag-name` other than `tag-id` exists."+ [tag-name tag-id]+ (t2/exists? :model/TransformTag :name tag-name :id [:not= tag-id]))++(defn transform-tag-links+ "The tag links of the Transforms with `transform-ids`, ordered by position."+ [transform-ids]+ (t2/select :model/TransformTransformTag :transform_id [:in transform-ids] {:order-by [[:position :asc]]}))++(defn transform-tag-links-for-tags+ "The tag ID and Transform ID of the tag links of the TransformTags with `tag-ids`."+ [tag-ids]+ (t2/select [:model/TransformTransformTag :tag_id :transform_id] :tag_id [:in tag-ids]))++(defn transform-ids-with-tags+ "The IDs of the Transforms tagged with one of `tag-ids`."+ [tag-ids]+ (t2/select-fn-set :transform_id :model/TransformTransformTag :tag_id [:in tag-ids]))++(defn active-job-schedules-for-transforms+ "Rows of Transform ID and the schedule of each active TransformJob that runs it through a shared tag."+ [transform-ids]+ (t2/select :model/TransformTransformTag+ {:select [:ttt.transform_id [:job.schedule :schedule]]+ :from [[:transform_transform_tag :ttt]]+ :join [[:transform_job_transform_tag :jtt] [:= :ttt.tag_id :jtt.tag_id]+ [:transform_job :job] [:= :jtt.job_id :job.id]]+ :where [:and+ [:in :ttt.transform_id transform-ids]+ [:= :job.active true]]}))++(defn insert-transform-tag-links!+ "Insert the TransformTransformTag `rows`."+ [rows]+ (t2/insert! :model/TransformTransformTag rows))++(defn set-transform-tag-position!+ "Set the position of the tag link between the Transform with `transform-id` and the tag with `tag-id`."+ [transform-id tag-id position]+ (t2/update! :model/TransformTransformTag {:transform_id transform-id, :tag_id tag-id} {:position position}))++(defn delete-transform-tag-links!+ "Delete the links between the Transform with `transform-id` and the tags with `tag-ids`."+ [transform-id tag-ids]+ (t2/delete! :model/TransformTransformTag :transform_id transform-id :tag_id [:in tag-ids]))++;;; ---------------------------------------------- Transform jobs ----------------------------------------------++(defn job+ "The TransformJob with `job-id`, or nil."+ [job-id]+ (t2/select-one :model/TransformJob :id job-id))++(defn active-jobs+ "The active TransformJobs."+ []+ (t2/select :model/TransformJob :active true))++(defn job-snapshot+ "The name, entity ID, and built-in type of the TransformJob with `job-id`."+ [job-id]+ (t2/select-one [:model/TransformJob :name :entity_id :built_in_type] :id job-id))++(defn job-names-by-id+ "A map of ID to name for the TransformJobs with `job-ids`."+ [job-ids]+ (t2/select-pk->fn :name :model/TransformJob :id [:in job-ids]))++(defn activate-job!+ "Mark the inactive TransformJob with `job-id` active, returning the number of rows updated."+ [job-id]+ (t2/update! :model/TransformJob {:id job-id, :active false} {:active true}))++(defn deactivate-job!+ "Mark the active TransformJob with `job-id` inactive, returning the number of rows updated."+ [job-id]+ (t2/update! :model/TransformJob {:id job-id, :active true} {:active false}))++(defn job-tag-ids+ "The IDs of the tags of the TransformJob with `job-id`."+ [job-id]+ (t2/select-fn-set :tag_id :model/TransformJobTransformTag :job_id job-id))++(defn job-tag-links+ "The tag links of the TransformJobs with `job-ids`, ordered by position."+ [job-ids]+ (t2/select :model/TransformJobTransformTag :job_id [:in job-ids] {:order-by [[:position :asc]]}))++(defn insert-job-tag-links!+ "Insert the TransformJobTransformTag `rows`."+ [rows]+ (t2/insert! :model/TransformJobTransformTag rows))++(defn set-job-tag-position!+ "Set the position of the tag link between the TransformJob with `job-id` and the tag with `tag-id`."+ [job-id tag-id position]+ (t2/update! :model/TransformJobTransformTag {:job_id job-id, :tag_id tag-id} {:position position}))++(defn delete-job-tag-links!+ "Delete the links between the TransformJob with `job-id` and the tags with `tag-ids`."+ [job-id tag-ids]+ (t2/delete! :model/TransformJobTransformTag :job_id job-id :tag_id [:in tag-ids]))++;;; ---------------------------------------------- Transform runs ----------------------------------------------++(defn run+ "The TransformRun with `run-id`, or nil."+ [run-id]+ (t2/select-one :model/TransformRun :id run-id))++(defn runs+ "The TransformRuns with `run-ids`."+ [run-ids]+ (t2/select :model/TransformRun :id [:in run-ids]))++(defn runs-for-transform+ "The TransformRuns of the Transform with `transform-id`, newest first."+ [transform-id]+ (t2/select :model/TransformRun :transform_id transform-id {:order-by [[:start_time :desc] [:end_time :desc]]}))++(defn runs-for-job-run+ "The TransformRuns of the TransformJobRun with `job-run-id`, oldest first."+ [job-run-id]+ (t2/select :model/TransformRun {:where [:= :job_run_id job-run-id], :order-by [[:start_time :asc]]}))++(defn runs-for-dag-run+ "The TransformRuns of the TransformDagRun with `dag-run-id`, oldest first."+ [dag-run-id]+ (t2/select :model/TransformRun {:where [:= :dag_run_id dag-run-id], :order-by [[:start_time :asc]]}))++(defn- paged-runs-where+ "Builds a `:where` clause for the paged run listing from plain filter data. `started-at-start`/`started-at-end`+ and `ended-at-start`/`ended-at-end` are instant bounds (as returned by parsing a date-range string at the call+ site); either half of a pair may be nil."+ [{:keys [started-at-start started-at-end ended-at-start ended-at-end run-methods transform-ids+ transform-tag-ids statuses user-id]}]+ (let [where-cond (cond-> []+ started-at-start (conj [:>= :start_time started-at-start])+ started-at-end (conj [:< :start_time started-at-end])+ ended-at-start (conj [:>= :end_time ended-at-start])+ ended-at-end (conj [:< :end_time ended-at-end])++ (seq run-methods)+ (conj [:in :run_method (set run-methods)])++ (seq transform-ids)+ (conj [:in :transform_id transform-ids])++ (seq transform-tag-ids)+ (conj [:in :transform_id ^:allow-subquery+ {:select [:transform_id]+ :from [:transform_transform_tag]+ :where [:in :tag_id transform-tag-ids]}])++ (seq statuses)+ (conj [:in :status (set statuses)])++ ;; optimization: is_active condition for started status+ (and (= (first statuses) "started")+ (nil? (next statuses)))+ (conj [:= :is_active true])++ (some? user-id)+ (conj [:= :user_id user-id]))]+ (when (seq where-cond)+ (into [:and] where-cond))))++(defn- paged-runs-join+ "Returns a `:left-join` clause for run listing sort columns that require joining other tables."+ [sort-column]+ (case (keyword sort-column)+ :transform-name [:transform [:= :transform_run.transform_id :transform.id]]+ nil))++(defn- label-case+ "A Honey SQL `:case` expression translating each value of `test-column` per `labels` (a map of raw value to+ display label), falling back to `fallback` (`test-column` itself, by default) when it matches none of them."+ ([test-column labels] (label-case test-column labels test-column))+ ([test-column labels fallback]+ (-> [:case]+ (into (mapcat (fn [[value label]] [[:= test-column value] label])) labels)+ (conj :else fallback))))++(defn- first-tag-name-subquery+ "A correlated subquery selecting the translated name of the first tag (by minimum position) assigned to the+ transform for a transform run. `tag-name-labels` translates built-in tag names (e.g. `\"hourly\"`); a tag with no+ matching built-in type displays its own name."+ [tag-name-labels]+ ^:allow-subquery+ {:select [[(label-case :tt.built_in_type tag-name-labels :tt.name) :tag_name]]+ :from [[:transform_transform_tag :ttt]]+ :join [[:transform_tag :tt] [:= :ttt.tag_id :tt.id]]+ :where [:and+ [:= :ttt.transform_id :transform_run.transform_id]+ [:= :ttt.position ^:allow-subquery+ {:select [[[:min :ttt2.position]]]+ :from [[:transform_transform_tag :ttt2]]+ :where [:= :ttt2.transform_id :transform_run.transform_id]}]]})++(defn- paged-runs-order-by+ "Builds a `:order-by` clause for the paged run listing, translating display values for sortable columns per+ `status-labels`/`run-method-labels`/`tag-name-labels` (maps of raw value to display label)."+ [sort-column sort-direction status-labels run-method-labels tag-name-labels]+ (let [sort-column (or (keyword sort-column) :start-time)+ sort-direction (or (keyword sort-direction) :desc)+ nulls-sort (if (= sort-direction :asc)+ :nulls-last+ :nulls-first)]+ (conj+ (case sort-column+ :transform-name [[:transform.name sort-direction]]+ :start-time [[:start_time sort-direction]]+ :end-time [[:end_time sort-direction nulls-sort]]+ :status [[(label-case :status status-labels) sort-direction]]+ :run-method [[(label-case :run_method run-method-labels) sort-direction]]+ :transform-tags [[(first-tag-name-subquery tag-name-labels) sort-direction nulls-sort]]+ ;; In-progress runs (end_time = nil) sink to the bottom in BOTH+ ;; directions — null means "no measurable duration yet," not+ ;; "longest duration."+ :duration [[[:is :end_time nil] :asc]+ [(h2x/calculate-interval-honeysql-form+ (mdb/db-type) :end_time :start_time)+ sort-direction]]+ [[:start_time sort-direction]+ [:end_time sort-direction nulls-sort]])+ [:transform_run.id sort-direction])))++(defn paged-runs+ "Up to `limit` (offset by `offset`) TransformRuns matching `filters` (see [[paged-runs-where]] for the supported+ keys), sorted by `sort-column`/`sort-direction` (translating `status`, `run-method`, and `transform-tags` sort+ columns per `status-labels`/`run-method-labels`/`tag-name-labels`)."+ [filters sort-column sort-direction status-labels run-method-labels tag-name-labels limit offset]+ (let [where-clause (paged-runs-where filters)+ join-clause (paged-runs-join sort-column)]+ (t2/select :model/TransformRun+ (m/assoc-some {:order-by (paged-runs-order-by sort-column sort-direction status-labels+ run-method-labels tag-name-labels)+ :offset offset+ :limit limit}+ :select (when join-clause [:transform_run.*])+ :where where-clause+ :left-join join-clause))))++(defn paged-run-count+ "The number of TransformRuns matching `filters` (see [[paged-runs-where]] for the supported keys)."+ [filters]+ (t2/count :model/TransformRun (m/assoc-some {} :where (paged-runs-where filters))))++(defn latest-runs-reducible+ "Reducible latest TransformRun of each Transform with `transform-ids`."+ [transform-ids]+ (t2/reducible-select :model/TransformRun+ {:with [[:latest_runs+ ^:allow-subquery+ {:select [:*+ [[:over [[:row_number]+ ^:allow-subquery {:partition-by :transform_id+ :order-by [[:start_time :desc]]}]]+ :rn]]+ :from [:transform_run]+ :where [:in :transform_id transform-ids]}]]+ :select [:*]+ :from [:latest_runs]+ :where [:= :rn [:inline 1]]}))++(defn active-run-for-transform+ "The active TransformRun of the Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/TransformRun :transform_id transform-id :is_active true))++(defn active-run-ids-of-parent+ "The IDs of the active TransformRuns whose `parent-column` is `parent-run-id`."+ [parent-column parent-run-id]+ (t2/select-pks-vec :model/TransformRun parent-column parent-run-id :is_active true))++(defn lock-active-runs+ "The active TransformRuns among `run-ids`, locked for update."+ [run-ids]+ (t2/select :model/TransformRun {:where [:and [:= :is_active true] [:in :id run-ids]]+ :for :update}))++(defn last-success-times+ "Rows of Transform ID and the latest `end_time` of its succeeded runs for `transform-ids`."+ [transform-ids]+ (t2/select :model/TransformRun+ {:select [:transform_id [[:max :end_time] :last_success]]+ :where [:and+ [:in :transform_id transform-ids]+ [:= :status "succeeded"]]+ :group-by [:transform_id]}))++(defn insert-run!+ "Insert `run` and return the new instance."+ [run]+ (t2/insert-returning-instance! :model/TransformRun run))++(defn finish-active-run!+ "Apply `changes` to the TransformRun with `run-id` if it is still active, returning the number of rows updated."+ [run-id changes]+ (t2/update! :model/TransformRun :id run-id :is_active true changes))++(defn cancel-active-runs!+ "Mark the active TransformRuns among `run-ids` canceled because the user asked but the run could not be stopped."+ [run-ids]+ (t2/update! :model/TransformRun+ :id [:in run-ids]+ :is_active true+ {:status :canceled+ :end_time :%now+ :is_active nil+ :message "Canceled by user but could not guarantee run stopped."}))++(defn mark-run-canceling!+ "Set the status of the TransformRun with `run-id` to canceling."+ [run-id]+ (t2/update! :model/TransformRun :id run-id {:status "canceling"}))++;;; -------------------------------------------- Run cancelations --------------------------------------------++(defn insert-cancelation-for-active-run!+ "Record a cancelation request for the TransformRun with `run-id` if it is active and none exists yet."+ [run-id]+ (t2/query-one [(str "INSERT INTO transform_run_cancelation (run_id) "+ "SELECT transform_run.id "+ "FROM transform_run "+ "WHERE transform_run.id = ? "+ "AND transform_run.is_active "+ "AND NOT EXISTS (SELECT 1 FROM transform_run_cancelation WHERE run_id = ?)")+ run-id run-id]))++(defn cancelations-reducible+ "Reducible TransformRunCancelations."+ []+ (t2/reducible-select :model/TransformRunCancelation))++(defn cancelations-requested-before+ "The run ID and request time of the TransformRunCancelations requested before `cutoff`."+ [cutoff]+ (t2/select [:model/TransformRunCancelation :run_id :time] :time [:< cutoff]))++(defn delete-cancelation-for-inactive-run!+ "Delete the TransformRunCancelation of the TransformRun with `run-id` if that run is no longer active."+ [run-id]+ (t2/delete! :model/TransformRunCancelation {:where [:and [:= :run_id run-id] no-active-run-clause]}))++(defn delete-cancelations-for-inactive-runs!+ "Delete every TransformRunCancelation whose run is no longer active."+ []+ (t2/delete! :model/TransformRunCancelation {:where no-active-run-clause}))++;;; ------------------------------------------- Job and DAG runs -------------------------------------------++(defn touch-active-job-run!+ "Stamp `updated_at` on the active TransformJobRun with `run-id`."+ [run-id]+ (t2/update! :model/TransformJobRun :id run-id :is_active true {:updated_at :%now}))++(defn touch-active-dag-run!+ "Stamp `updated_at` on the active TransformDagRun with `run-id`."+ [run-id]+ (t2/update! :model/TransformDagRun :id run-id :is_active true {:updated_at :%now}))++(defn finish-active-job-run!+ "Apply `changes` to the TransformJobRun with `run-id` if it is still active, returning the number of rows+ updated."+ [run-id changes]+ (t2/update! :model/TransformJobRun :id run-id :is_active true changes))++(defn finish-active-dag-run!+ "Apply `changes` to the TransformDagRun with `run-id` if it is still active, returning the number of rows+ updated."+ [run-id changes]+ (t2/update! :model/TransformDagRun :id run-id :is_active true changes))++(defn- job-run-where+ [job-id status run-method started-at-start started-at-end]+ (let [conditions (cond-> []+ job-id (conj [:= :job_id job-id])+ status (conj [:= :status status])+ (= status "started") (conj [:= :is_active true])+ run-method (conj [:= :run_method run-method])+ started-at-start (conj [:>= :start_time started-at-start])+ started-at-end (conj [:< :start_time started-at-end]))]+ (when (seq conditions)+ (into [:and] conditions))))++(defn- job-run-order-by+ [sort-column sort-direction]+ (let [sort-direction (or (keyword sort-direction) :desc)+ nulls-sort (if (= sort-direction :asc) :nulls-last :nulls-first)]+ (case (keyword sort-column)+ :start_time [[:start_time sort-direction]]+ :end_time [[:end_time sort-direction nulls-sort]]+ [[:start_time sort-direction]+ [:end_time sort-direction nulls-sort]])))++(defn job-runs+ "Up to `limit` (offset by `offset`) TransformJobRuns, optionally narrowed to `job-id`, `status`, `run-method`, and+ started in [`started-at-start`, `started-at-end`), sorted by `sort-column`/`sort-direction`."+ [job-id status run-method started-at-start started-at-end sort-column sort-direction limit offset]+ (t2/select :model/TransformJobRun+ (cond-> {:order-by (job-run-order-by sort-column sort-direction)+ :offset offset+ :limit limit}+ (job-run-where job-id status run-method started-at-start started-at-end)+ (assoc :where (job-run-where job-id status run-method started-at-start started-at-end)))))++(defn job-run-count+ "The number of TransformJobRuns, optionally narrowed to `job-id`, `status`, `run-method`, and started in+ [`started-at-start`, `started-at-end`)."+ [job-id status run-method started-at-start started-at-end]+ (t2/count :model/TransformJobRun+ (if-let [where (job-run-where job-id status run-method started-at-start started-at-end)]+ {:where where}+ {})))++(defn latest-job-runs-reducible+ "Reducible latest TransformJobRun of each TransformJob with `job-ids`."+ [job-ids]+ (t2/reducible-select :model/TransformJobRun+ {:with [[:ranked_runs+ ^:allow-subquery+ {:select [:*+ [[:over [[:row_number]+ ^:allow-subquery {:partition-by :job_id+ :order-by [[:start_time :desc]]}]]+ :rn]]+ :from [:transform_job_run]+ :where [:in :job_id job-ids]}]]+ :select [:*]+ :from [:ranked_runs]+ :where [:= :rn [:inline 1]]}))++(defn active-job-run-for-job+ "The active TransformJobRun of the TransformJob with `job-id`, or nil."+ [job-id]+ (t2/select-one :model/TransformJobRun :job_id job-id :is_active true))++(defn failed-cron-job-runs-between+ "The job ID, start time, and message of the cron TransformJobRuns that failed or timed out in `[start, end)`,+ oldest first."+ [start end]+ (t2/select [:model/TransformJobRun :job_id :start_time :message]+ {:where [:and+ [:= :run_method "cron"]+ [:in :status ["failed" "timeout"]]+ [:>= :start_time start]+ [:< :start_time end]]+ :order-by [[:start_time :asc]]}))++(defn insert-job-run!+ "Insert `job-run` and return the new instance."+ [job-run]+ (t2/insert-returning-instance! :model/TransformJobRun job-run))++(defn active-dag-run-for-transform+ "The active TransformDagRun seeded from the Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/TransformDagRun :source_transform_id transform-id :is_active true))++(defn insert-dag-run!+ "Insert `dag-run` and return the new instance."+ [dag-run]+ (t2/insert-returning-instance! :model/TransformDagRun dag-run))++;;; ------------------------------------------ Root run listing ------------------------------------------++;; Each branch must project the same columns in the same order for the UNION ALL to line up;+;; `[nil :col]` fills in columns a table lacks.++(defn- job-run-subquery [transform-ids]+ ^:allow-subquery+ {:select [[^:allow-raw-sql [:inline "job"] :run_type]+ :id+ [:job_id :entity_id]+ [:job_name :entity_name]+ [nil :direction]+ [nil :transform_count]+ :run_method+ :status :is_active :start_time :end_time :message+ [nil :user_id]]+ :from [:transform_job_run]+ :where (if (seq transform-ids)+ ;; only job runs that actually ran one of these transforms+ [:exists ^:allow-subquery {:select [[[:inline 1]]]+ :from [[:transform_run :member]]+ :where [:and+ [:= :member.job_run_id :transform_job_run.id]+ [:in :member.transform_id transform-ids]]}]+ true)})++(defn- dag-run-subquery [transform-ids]+ ^:allow-subquery+ {:select [[^:allow-raw-sql [:inline "dag"] :run_type]+ :id+ [:source_transform_id :entity_id]+ [:source_transform_name :entity_name]+ :direction+ :transform_count+ [^:allow-raw-sql [:inline "manual"] :run_method]+ :status :is_active :start_time :end_time :message+ :user_id]+ :from [:transform_dag_run]+ :where (if (seq transform-ids)+ [:exists ^:allow-subquery {:select [[[:inline 1]]]+ :from [[:transform_run :member]]+ :where [:and+ [:= :member.dag_run_id :transform_dag_run.id]+ [:in :member.transform_id transform-ids]]}]+ true)})++(defn- transform-run-subquery [transform-ids]+ ^:allow-subquery+ {:select [[^:allow-raw-sql [:inline "transform"] :run_type]+ :id+ [:transform_id :entity_id]+ [:transform_name :entity_name]+ [nil :direction]+ [nil :transform_count]+ :run_method+ :status :is_active :start_time :end_time :message+ :user_id]+ :from [:transform_run]+ ;; standalone runs only: those not coordinated by a job or DAG run+ :where (cond-> [:and+ [:= :job_run_id nil]+ [:= :dag_run_id nil]]+ (seq transform-ids) (conj [:in :transform_id transform-ids]))})++(defn- union-subquery+ "The UNION ALL of the branches selected by `types` (a subset of `#{:job :dag :transform}`), each optionally+ narrowed to runs touching one of `transform-ids`."+ [types transform-ids]+ (let [types (set (or (seq types) #{:job :dag :transform}))]+ ^:allow-subquery+ {:union-all (cond-> []+ (:job types) (conj (job-run-subquery transform-ids))+ (:dag types) (conj (dag-run-subquery transform-ids))+ (:transform types) (conj (transform-run-subquery transform-ids)))}))++(defn- root-run-summaries-where+ [statuses run-methods started-at-start started-at-end ended-at-start ended-at-end]+ (let [where (into [:and] (remove nil?)+ [(when (seq statuses) [:in :status (set statuses)])+ ;; started ⇒ still active, as in the per-table run listings+ (when (= (set statuses) #{"started"}) [:= :is_active true])+ (when (seq run-methods) [:in :run_method (set run-methods)])+ (when started-at-start [:>= :start_time started-at-start])+ (when started-at-end [:< :start_time started-at-end])+ (when ended-at-start [:>= :end_time ended-at-start])+ (when ended-at-end [:< :end_time ended-at-end])])]+ (when (> (count where) 1) where)))++(defn- root-run-order-by+ "Standard `:order-by` clause for a paged root-run listing. Sorts by `sort-column` (`:start_time` or `:end_time`;+ anything else — including nil — falls back to ordering by start_time then end_time) in `sort-direction`+ (`:asc`/`:desc`, defaulting to `:desc`), with in-progress rows (null `end_time`) always ordered last."+ [sort-column sort-direction]+ (let [sort-direction (or (keyword sort-direction) :desc)+ nulls-sort (if (= sort-direction :asc) :nulls-last :nulls-first)]+ (case (keyword sort-column)+ :start_time [[:start_time sort-direction]]+ :end_time [[:end_time sort-direction nulls-sort]]+ [[:start_time sort-direction]+ [:end_time sort-direction nulls-sort]])))++(defn root-run-summaries-page+ "Up to `limit` (offset by `offset`) root-run summary rows -- see [[metabase.transforms.run-listing]] -- of `types`+ (a subset of `#{:job :dag :transform}`, or all three when empty), optionally narrowed to `statuses`,+ `run-methods`, started in [`started-at-start`, `started-at-end`), ended in [`ended-at-start`, `ended-at-end`),+ and/or touching one of `transform-ids`, sorted by `sort-column`/`sort-direction`."+ [types statuses run-methods started-at-start started-at-end ended-at-start ended-at-end transform-ids+ sort-column sort-direction limit offset]+ (let [where (root-run-summaries-where statuses run-methods started-at-start started-at-end ended-at-start+ ended-at-end)+ base (cond-> {:from [[(union-subquery types transform-ids) :runs]]}+ where (assoc :where where))]+ (t2/query (merge base {:select [:*]+ :order-by (root-run-order-by sort-column sort-direction)+ :limit limit+ :offset offset}))))++(defn root-run-summaries-count+ "The number of root-run summary rows matching the same filters as [[root-run-summaries-page]]."+ [types statuses run-methods started-at-start started-at-end ended-at-start ended-at-end transform-ids]+ (let [where (root-run-summaries-where statuses run-methods started-at-start started-at-end ended-at-start+ ended-at-end)+ base (cond-> {:from [[(union-subquery types transform-ids) :runs]]}+ where (assoc :where where))]+ (:count (first (t2/query (merge base {:select [[[:count :*] :count]]}))))))++(defn app-db-now+ "The current time according to the application database."+ []+ (:now (t2/query-one {:select [[(h2x/current-datetime-honeysql-form (mdb/db-type)) :now]]})))++;;; ----------------------------------------------- Other models -----------------------------------------------++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table table-id))++(defn databases+ "The Databases with `database-ids`."+ [database-ids]+ (t2/select :model/Database :id [:in database-ids]))++(defn database-exists?+ "Whether a Database with `database-id` exists."+ [database-id]+ (t2/exists? :model/Database :id database-id))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn table-indexes-for-transforms+ "The TableIndexes of the Transforms with `transform-ids`, ordered by index name."+ [transform-ids]+ (t2/select :model/TableIndex :transform_id [:in transform-ids] {:order-by [[:index_name :asc]]}))++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field field-id))++(defn field-exists?+ "Whether a Field with `field-id` exists."+ [field-id]+ (t2/exists? :model/Field :id field-id))++(defn active-field-ids-by-name+ "A map of name to ID for the active Fields of the Table with `table-id`."+ [table-id]+ (t2/select-fn->fn :name :id [:model/Field :name :id] :table_id table-id :active true))++(defn active-users+ "The active Users with `user-ids`."+ [user-ids]+ (t2/select :model/User :id [:in user-ids] :is_active true))++(defn active-admins+ "The active superusers."+ []+ (t2/select :model/User :is_superuser true :is_active true))++(defn user-summaries-by-id+ "A map of ID to the ID, email, and names of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))diff --git a/src/metabase/transforms/jobs.clj b/src/metabase/transforms/jobs.cljindex bf7b4d10ea8..0fa371a9c9c 100644--- a/src/metabase/transforms/jobs.clj+++ b/src/metabase/transforms/jobs.clj@@ -3,7 +3,6 @@[clojure.set :as set][clojure.string :as str][flatland.ordered.set :as ordered-set]- [metabase.app-db.core :as mdb][metabase.channel.urls :as urls][metabase.events.core :as events][metabase.revisions.core :as revisions]@@ -14,6 +13,7 @@[metabase.transforms-base.util :as transforms-base.u][metabase.transforms.canceling :as canceling][metabase.transforms.coordinated-run :as coordinated-run]+ [metabase.transforms.db :as transforms.db][metabase.transforms.execute :as transforms.execute][metabase.transforms.freshness :as freshness][metabase.transforms.instrumentation :as transforms.instrumentation]@@ -24,10 +24,8 @@[metabase.transforms.usage :as transforms.usage][metabase.transforms.util :as transforms.u][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :as i18n]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -85,7 +83,7 @@(defn- get-plan [transform-ids](tracing/with-span :tasks "task.transform.plan" {:transform/count (count transform-ids)}- (let [all-transforms (t2/select [:model/Transform :id :target :target_table_id :created_at :table_dependencies])+ (let [all-transforms (transforms.db/transform-dependency-rows);; Walk only the dependency closure of the transforms we're asked to run.;; `table-dependencies` (and the QP preprocessing it triggers) is therefore called;; only on transforms in that closure — never on unrelated transforms elsewhere in@@ -103,7 +101,7 @@(transforms-base.ordering/persist-table-dependencies! uncached);; Fetch full rows only for the closure, which is what callers actually consume.(let [closure-transforms (if (seq dependencies)- (t2/select :model/Transform :id [:in (keys dependencies)])+ (transforms.db/transforms (keys dependencies))[])](dependencies->plan dependencies closure-transforms)))))@@ -337,7 +335,7 @@(defn- app-db-now[]- (:now (t2/query-one {:select [[(h2x/current-datetime-honeysql-form (mdb/db-type)) :now]]})))+ (transforms.db/app-db-now))(defn run-transforms!"Run the transforms of `plan`, honoring the DAG.@@ -404,9 +402,9 @@:else {::status :succeeded})))(defn- job-transform-ids [job-id]- (let [tag-ids (t2/select-fn-set :tag_id :model/TransformJobTransformTag :job_id job-id)]+ (let [tag-ids (transforms.db/job-tag-ids job-id)](if (seq tag-ids)- (or (t2/select-fn-set :transform_id :model/TransformTransformTag :tag_id [:in tag-ids])+ (or (transforms.db/transform-ids-with-tags tag-ids)#{})#{})))@@ -493,18 +491,18 @@(when-some [revisions (seq (revisions/revisions :model/Transform transform-id))](let [user-ids (map :user_id revisions)distinct-user-ids (distinct user-ids)- users (t2/select :model/User :id [:in distinct-user-ids] :is_active true)+ users (transforms.db/active-users distinct-user-ids)by-id (u/index-by :id users)];; maintain order(map by-id distinct-user-ids))))(defn- active-admins[]- (t2/select :model/User :is_superuser true :is_active true))+ (transforms.db/active-admins))(defn- transform-creator[transform]- (t2/select :model/User :id (:creator_id transform) :is_active true))+ (transforms.db/active-users [(:creator_id transform)]))(defn- users-to-notify-of-transform-failure [transform](or (seq (take 1 (active-users-to-edit-transform (:id transform))))@@ -527,7 +525,7 @@;; We hope that this will be the most recent user.;; Only root-cause failures are reported individually; dependents that never ran because an;; upstream transform failed are summarized as a count to avoid a cascade of redundant errors.- (let [job (t2/select-one :model/TransformJob job-id)+ (let [job (transforms.db/job job-id)[roots cascades] (split-cascade-failures failures)roots (map (fn [failure](let [transform (::transform failure)]diff --git a/src/metabase/transforms/models/dag_run.clj b/src/metabase/transforms/models/dag_run.cljindex 6d3edb6c89a..bfbda744096 100644--- a/src/metabase/transforms/models/dag_run.clj+++ b/src/metabase/transforms/models/dag_run.clj@@ -6,6 +6,7 @@via `transform_run.dag_run_id`."(:require[metabase.models.interface :as mi]+ [metabase.transforms.db :as transforms.db][methodical.core :as methodical][toucan2.core :as t2]))@@ -27,9 +28,8 @@Snapshots the seed transform's name and entity_id so the run stays displayable after thetransform is deleted (its FK is SET NULL, as for `transform_run.transform_id`)."[source-transform-id direction user-id transform-count]- (let [transform (t2/select-one [:model/Transform :name :entity_id] :id source-transform-id)]- (t2/insert-returning-instance! :model/TransformDagRun- {:source_transform_id source-transform-id+ (let [transform (transforms.db/transform-snapshot source-transform-id)]+ (transforms.db/insert-dag-run! {:source_transform_id source-transform-id:source_transform_name (:name transform):source_transform_entity_id (:entity_id transform):direction direction@@ -41,13 +41,9 @@(defn running-run-for-source-transform-id"Return the single active DAG run seeded from `source-transform-id`, or nil."[source-transform-id]- (t2/select-one :model/TransformDagRun- :source_transform_id source-transform-id- :is_active true))+ (transforms.db/active-dag-run-for-transform source-transform-id))(defn transform-runs-for-dag-run"Return the transform runs that were part of the given DAG run, ordered by start time."[dag-run-id]- (t2/select :model/TransformRun- {:where [:= :dag_run_id dag-run-id]- :order-by [[:start_time :asc]]}))+ (transforms.db/runs-for-dag-run dag-run-id))diff --git a/src/metabase/transforms/models/job_run.clj b/src/metabase/transforms/models/job_run.cljindex 305d1e0c030..ca8173334ed 100644--- a/src/metabase/transforms/models/job_run.clj+++ b/src/metabase/transforms/models/job_run.clj@@ -2,6 +2,7 @@(:require[metabase.models.interface :as mi][metabase.transforms.coordinated-run :as coordinated-run]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.util :as transforms.models.u][methodical.core :as methodical][toucan2.core :as t2]@@ -18,23 +19,12 @@{:status mi/transform-keyword:run_method mi/transform-keyword})-(defn- latest-runs-query [job-ids]- {:with [[:ranked_runs- ^:allow-subquery- {:select [:*- [[:over [[:row_number] ^:allow-subquery {:partition-by :job_id, :order-by [[:start_time :desc]]}]] :rn]]- :from [:transform_job_run]- :where [:in :job_id job-ids]}]]- :select [:*]- :from [:ranked_runs]- :where [:= :rn [:inline 1]]})-(defn latest-runs"Return the latest runs for `job-ids`."[job-ids](when (seq job-ids)(into [] (map (comp t2.realize/realize #(dissoc % :rn)))- (t2/reducible-select :model/TransformJobRun (latest-runs-query job-ids)))))+ (transforms.db/latest-job-runs-reducible job-ids))))(defn start-run!"Start a run. Snapshots the job's name and entity_id so the run stays displayable after the job@@ -42,9 +32,8 @@([job-id run-method];; :built_in_type so the after-select hook localizes built-in job names; str realizes the;; LocalizedString into the snapshot- (let [job (t2/select-one [:model/TransformJob :name :entity_id :built_in_type] :id job-id)]- (t2/insert-returning-instance! :model/TransformJobRun- {:job_id job-id+ (let [job (transforms.db/job-snapshot job-id)]+ (transforms.db/insert-job-run! {:job_id job-id:job_name (some-> (:name job) str):job_entity_id (:entity_id job):run_method run-method@@ -60,36 +49,22 @@(defn running-run-for-job-id"Return a single active job run or nil."[id]- (t2/select-one :model/TransformJobRun- :job_id id- :is_active true))+ (transforms.db/active-job-run-for-job id))(defn paged-job-runs"Return a page of the list of job runs.Follows the conventions used by the FE."[{:keys [sort-column sort-direction job-id status run-method start-time offset limit]}]- (let [offset (or offset 0)- limit (or limit 20)- where-cond (cond-> []- job-id (conj [:= :job_id job-id])- status (conj [:= :status status])- (= status "started") (conj [:= :is_active true])- run-method (conj [:= :run_method run-method])- start-time (conj (transforms.models.u/timestamp-constraint :start_time start-time)))- where (when (seq where-cond) (into [:and] where-cond))]- {:data (t2/select :model/TransformJobRun- (cond-> {:order-by (transforms.models.u/run-order-by sort-column sort-direction)- :offset offset- :limit limit}- where (assoc :where where)))+ (let [offset (or offset 0)+ limit (or limit 20)+ [start-at end-at] (when start-time (transforms.models.u/timestamp-range start-time))]+ {:data (transforms.db/job-runs job-id status run-method start-at end-at sort-column sort-direction limit offset):limit limit:offset offset- :total (t2/count :model/TransformJobRun (if where {:where where} {}))}))+ :total (transforms.db/job-run-count job-id status run-method start-at end-at)}))(defn transform-runs-for-job-run"Return transform runs that were part of the given job run, ordered by start time."[job-run-id]- (t2/select :model/TransformRun- {:where [:= :job_run_id job-run-id]- :order-by [[:start_time :asc]]}))+ (transforms.db/runs-for-job-run job-run-id))diff --git a/src/metabase/transforms/models/transform.clj b/src/metabase/transforms/models/transform.cljindex 3d20d9e82af..81d1a27172b 100644--- a/src/metabase/transforms/models/transform.clj+++ b/src/metabase/transforms/models/transform.clj@@ -17,6 +17,7 @@[metabase.search.spec :as search.spec][metabase.transforms-base.interface :as transforms-base.i][metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.transform-run :as transform-run][metabase.transforms.util :as transforms.u][metabase.util :as u]@@ -70,14 +71,14 @@([instance](transform-readable? instance))([_model pk]- (when-let [transform (t2/select-one :model/Transform :id pk)]+ (when-let [transform (transforms.db/transform pk)](mi/can-read? transform))))(defmethod mi/can-write? :model/Transform([instance](transform-writable? instance))([_model pk]- (when-let [transform (t2/select-one :model/Transform :id pk)]+ (when-let [transform (transforms.db/transform pk)](mi/can-write? transform))));; Users who can read the transform can also query it. This is a duplicate, but keeps things explicit.@@ -153,7 +154,7 @@(when collection_id(collection/check-allowed-content :model/Transform collection_id))(let [target-db-id (transforms-base.i/target-db-id transform)- valid-db-id? (and target-db-id (t2/exists? :model/Database :id target-db-id))]+ valid-db-id? (and target-db-id (transforms.db/database-exists? target-db-id))];; Don't warn when target-db-id is nil — that's an orphan source (e.g. a;; serdes-imported transform whose source database is missing), not a;; misconfiguration. Only warn when an id is supplied but invalid.@@ -176,7 +177,7 @@(if (and (transforms-base.u/merge-target? {:target target})table-id(some #(nil? (:field-id %)) unique-key))- (let [name->id (t2/select-fn->fn :name :id [:model/Field :name :id] :table_id table-id :active true)]+ (let [name->id (transforms.db/active-field-ids-by-name table-id)](assoc transform :target(assoc-in target [:target-incremental-strategy :unique-key](mapv (fn [e] (cond-> e (:name e) (assoc :field-id (name->id (:name e)))))@@ -264,7 +265,7 @@runs(let [transform-ids (into #{} (keep :transform_id) runs)id->transform (when (seq transform-ids)- (t2/select-pk->fn identity [:model/Transform :id :name :collection_id] :id [:in transform-ids]))]+ (transforms.db/transform-summaries-by-id transform-ids))](for [run runs](assoc run :transform(if-let [transform-id (:transform_id run)]@@ -289,7 +290,7 @@(assoc transform :last_checkpoint_value checkpoint_hi_value);; latest transform value wins, could be reset(assoc transform :last_checkpoint_value- (t2/select-one-fn :last_checkpoint_value [:model/Transform :last_checkpoint_value] transform-id)))+ (transforms.db/transform-last-checkpoint-value transform-id)))transform))))))(methodical/defmethod t2/batched-hydrate [:model/Transform :transform_tag_ids]@@ -298,11 +299,7 @@(if-not (seq transforms)transforms(let [transform-ids (into #{} (map :id) transforms)- tag-associations (t2/select- [:model/TransformTransformTag :transform_id :tag_id :position]- :transform_id- [:in transform-ids]- {:order-by [[:position :asc]]})+ tag-associations (transforms.db/transform-tag-links transform-ids)transform-id->tag-ids (reduce(fn [acc {:keys [transform_id tag_id]}](update acc transform_id (fnil conj []) tag_id))@@ -316,8 +313,7 @@(if-not (seq transforms)transforms(let [creator-ids (into #{} (map :creator_id) transforms)- id->creator (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id [:in creator-ids])]+ id->creator (transforms.db/user-summaries-by-id creator-ids)](for [transform transforms](assoc transform :creator (get id->creator (:creator_id transform)))))))@@ -329,8 +325,7 @@transforms(let [owner-user-ids (into #{} (keep :owner_user_id) transforms)id->owner (when (seq owner-user-ids)- (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id [:in owner-user-ids]))]+ (transforms.db/user-summaries-by-id owner-user-ids))](for [transform transforms](assoc transform :owner(cond@@ -365,14 +360,11 @@(let [;; Deduplicate while preserving order of first occurrencededuped-tag-ids (vec (distinct tag-ids));; Get current associations- current-associations (t2/select [:model/TransformTransformTag :tag_id :position]- :transform_id transform-id- {:order-by [[:position :asc]]})+ current-associations (transforms.db/transform-tag-links [transform-id])current-tag-ids (mapv :tag_id current-associations);; Validate that new tag IDs existvalid-tag-ids (when (seq deduped-tag-ids)- (into #{} (t2/select-fn-set :id :model/TransformTag- :id [:in deduped-tag-ids])))+ (into #{} (transforms.db/existing-tag-ids deduped-tag-ids)));; Filter to only valid tags, preserving ordernew-tag-ids (if valid-tag-ids(filterv valid-tag-ids deduped-tag-ids)@@ -386,22 +378,17 @@new-positions (zipmap new-tag-ids (range))];; Delete removed associations(when (seq to-delete)- (t2/delete! :model/TransformTransformTag- :transform_id transform-id- :tag_id [:in to-delete]))+ (transforms.db/delete-transform-tag-links! transform-id to-delete));; Update positions for existing tags that moved(doseq [tag-id (filter current-set new-tag-ids)](let [new-pos (get new-positions tag-id)]- (t2/update! :model/TransformTransformTag- {:transform_id transform-id :tag_id tag-id}- {:position new-pos})))+ (transforms.db/set-transform-tag-position! transform-id tag-id new-pos)));; Insert new associations with correct positions(when (seq to-insert)- (t2/insert! :model/TransformTransformTag- (for [tag-id to-insert]- {:transform_id transform-id- :tag_id tag-id- :position (get new-positions tag-id)})))))))+ (transforms.db/insert-transform-tag-links! (for [tag-id to-insert]+ {:transform_id transform-id+ :tag_id tag-id+ :position (get new-positions tag-id)})))))));;; ------------------------------------------------- Serialization ------------------------------------------------@@ -412,9 +399,7 @@(when (seq transforms)(let [transform-ids (into #{} (map u/the-id) transforms)tag-mappings (group-by :transform_id- (t2/select :model/TransformTransformTag- :transform_id [:in transform-ids]- {:order-by [[:position :asc]]}))]+ (transforms.db/transform-tag-links transform-ids))](for [transform transforms](assoc transform :tags (get tag-mappings (u/the-id transform) []))))))@@ -426,9 +411,7 @@(let [transform-ids (into #{} (map u/the-id) transforms)idx-mappings (group-by :transform_id(filter table-index/applicable?- (t2/select :model/TableIndex- :transform_id [:in transform-ids]- {:order-by [[:index_name :asc]]})))]+ (transforms.db/table-indexes-for-transforms transform-ids)))](for [transform transforms](assoc transform :indexes (get idx-mappings (u/the-id transform) []))))))@@ -438,7 +421,7 @@[transforms](let [table-ids (into #{} (keep :target_table_id) transforms)id->table (when (seq table-ids)- (m/index-by :id (-> (t2/select :model/Table :id [:in table-ids])+ (m/index-by :id (-> (transforms.db/tables table-ids)(t2/hydrate :db :fields))))](for [transform transforms](assoc transform :table@@ -463,7 +446,7 @@"Portable ref for the checkpoint field. A dangling id (field since deleted) is exported as-is:the importer passes numbers through, so one stale config can't fail the whole import."[field-id]- (if (t2/exists? :model/Field :id field-id)+ (if (transforms.db/field-exists? field-id)(serdes/*export-field-fk* field-id)field-id))@@ -546,7 +529,7 @@(defmethod serdes/required "Transform"[_model id]- (when-let [collection-id (t2/select-one-fn :collection_id :model/Transform :id id)]+ (when-let [collection-id (transforms.db/transform-collection-id id)]{["Collection" collection-id] {"Transform" id}}))(defn- maybe-extract-transform-query-text@@ -567,9 +550,8 @@Return empty list if no tag IDs are provided or no transforms are associated with the tags."[tag-ids](or (when (seq tag-ids)- (when-let [transform-ids (t2/select-fn-set :transform_id [:model/TransformTransformTag :transform_id]- :tag_id [:in tag-ids])]- (t2/select :model/Transform :id [:in transform-ids])))+ (when-let [transform-ids (transforms.db/transform-ids-with-tags tag-ids)]+ (transforms.db/transforms transform-ids)))[]));;; ------------------------------------------------- Search ---------------------------------------------------diff --git a/src/metabase/transforms/models/transform_job.clj b/src/metabase/transforms/models/transform_job.cljindex a9835ffa9bb..4e66aed712d 100644--- a/src/metabase/transforms/models/transform_job.clj+++ b/src/metabase/transforms/models/transform_job.clj@@ -6,6 +6,7 @@[metabase.app-db.cluster-lock :as cluster-lock][metabase.models.interface :as mi][metabase.models.serialization :as serdes]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.job-run :as transforms.job-run][metabase.transforms.models.transform :as transform][metabase.transforms.schedule :as transforms.schedule]@@ -41,7 +42,7 @@(every? mi/can-write? transforms)true)))))([_model pk]- (when-let [job (t2/select-one :model/TransformJob :id pk)]+ (when-let [job (transforms.db/job pk)](mi/can-write? job))))(defmethod mi/can-create? :model/TransformJob@@ -64,9 +65,7 @@(when (seq jobs)(let [job-ids (map :id jobs)tag-mappings (group-by :job_id- (t2/select [:model/TransformJobTransformTag :job_id :tag_id :position]- :job_id [:in job-ids]- {:order-by [[:position :asc]]}))+ (transforms.db/job-tag-links job-ids));; Sort each job's tags by positionsorted-mappings (update-vals tag-mappings #(sort-by :position %))](for [job jobs]@@ -97,8 +96,8 @@write."[job-id](cluster-lock/with-cluster-lock (active-flip-lock-name job-id)- (when (pos? (t2/update! :model/TransformJob {:id job-id, :active false} {:active true}))- (transforms.schedule/initialize-job! (t2/select-one :model/TransformJob :id job-id)))))+ (when (pos? (transforms.db/activate-job! job-id))+ (transforms.schedule/initialize-job! (transforms.db/job job-id)))))(defn deactivate-job!"Deactivate a transform job: set `:active` to false and remove its Quartz trigger so cron@@ -109,7 +108,7 @@[[activate-job!]]."[job-id](cluster-lock/with-cluster-lock (active-flip-lock-name job-id)- (when (pos? (t2/update! :model/TransformJob {:id job-id, :active true} {:active false}))+ (when (pos? (transforms.db/deactivate-job! job-id))(transforms.schedule/delete-trigger! job-id))))(defn update-job-tags!@@ -122,14 +121,11 @@(let [;; Deduplicate, just in casededuped-tag-ids (vec (distinct tag-ids));; Get current associations- current-associations (t2/select [:model/TransformJobTransformTag :tag_id :position]- :job_id job-id- {:order-by [[:position :asc]]})+ current-associations (transforms.db/job-tag-links [job-id])current-tag-ids (mapv :tag_id current-associations);; Validate that new tag IDs existvalid-tag-ids (when (seq deduped-tag-ids)- (into #{} (t2/select-fn-set :id :model/TransformTag- :id [:in deduped-tag-ids])))+ (into #{} (transforms.db/existing-tag-ids deduped-tag-ids)));; Filter to only valid tags, preserving ordernew-tag-ids (if valid-tag-ids(filterv valid-tag-ids deduped-tag-ids)@@ -143,22 +139,17 @@new-positions (zipmap new-tag-ids (range))];; Delete removed associations(when (seq to-delete)- (t2/delete! :model/TransformJobTransformTag- :job_id job-id- :tag_id [:in to-delete]))+ (transforms.db/delete-job-tag-links! job-id to-delete));; Update positions for existing tags that moved(doseq [tag-id (filter current-set new-tag-ids)](let [new-pos (get new-positions tag-id)]- (t2/update! :model/TransformJobTransformTag- {:job_id job-id :tag_id tag-id}- {:position new-pos})))+ (transforms.db/set-job-tag-position! job-id tag-id new-pos)));; Insert new associations with correct positions(when (seq to-insert)- (t2/insert! :model/TransformJobTransformTag- (for [tag-id to-insert]- {:job_id job-id- :tag_id tag-id- :position (get new-positions tag-id)})))))))+ (transforms.db/insert-job-tag-links! (for [tag-id to-insert]+ {:job_id job-id+ :tag_id tag-id+ :position (get new-positions tag-id)})))))))(defn- translated-name-and-description [job](let [values {"hourly"@@ -202,9 +193,7 @@(when (seq jobs)(let [job-ids (into #{} (map u/the-id) jobs)tag-mappings (group-by :job_id- (t2/select :model/TransformJobTransformTag- :job_id [:in job-ids]- {:order-by [[:position :asc]]}))]+ (transforms.db/job-tag-links job-ids))](for [job jobs](assoc job :job_tags (get tag-mappings (u/the-id job) []))))))diff --git a/src/metabase/transforms/models/transform_run.clj b/src/metabase/transforms/models/transform_run.cljindex 9edea26d4f2..30d365af712 100644--- a/src/metabase/transforms/models/transform_run.clj+++ b/src/metabase/transforms/models/transform_run.clj@@ -1,6 +1,5 @@(ns metabase.transforms.models.transform-run(:require- [medley.core :as m][metabase.analytics-interface.core :as analytics][metabase.app-db.core :as mdb][metabase.collections.models.collection.root :as collection.root]@@ -8,6 +7,7 @@[metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.run-tracking.core :as rt]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.transform-run-cancelation :as cancel][metabase.transforms.models.util :as transforms.models.u][metabase.util :as u]@@ -34,32 +34,14 @@:transform-runs"Add transform-runs for a transform. Must have :id field."[transform]- (t2/select :model/TransformRun- :transform_id (:id transform)- {:order-by [[:start_time :desc] [:end_time :desc]]}))--(defn- latest-run-cte- ([] (latest-run-cte nil))- ([where]- [[:latest_runs- (-> ^:allow-subquery- {:select [:*- [[:over [[:row_number] ^:allow-subquery {:partition-by :transform_id, :order-by [[:start_time :desc]]}]] :rn]]- :from [:transform_run]}- (m/assoc-some :where where))]]))--(defn- latest-runs-query [transform-ids]- {:with (latest-run-cte [:in :transform_id transform-ids])- :select [:*]- :from [:latest_runs]- :where [:= :rn [:inline 1]]})+ (transforms.db/runs-for-transform (:id transform)))(defn latest-runs"Return the latest runs for `transform-ids`."[transform-ids](when (seq transform-ids)(into [] (map (comp t2.realize/realize #(dissoc % :rn)))- (t2/reducible-select :model/TransformRun (latest-runs-query transform-ids)))))+ (transforms.db/latest-runs-reducible transform-ids))))(defn start-run!"Start a run. If `user_id` is provided in properties, it will be stored with the run@@ -68,16 +50,15 @@([transform-id](start-run! transform-id {}))([transform-id properties]- (let [transform (t2/select-one [:model/Transform :name :entity_id :source_type] :id transform-id)+ (let [transform (transforms.db/transform-snapshot transform-id)metered-as (premium-features/transform-metered-as (:source_type transform))- run (t2/insert-returning-instance! :model/TransformRun- (assoc properties- :transform_id transform-id- :transform_name (:name transform)- :transform_entity_id (:entity_id transform)- :status :started- :is_active true- :metered_as metered-as))]+ run (transforms.db/insert-run! (assoc properties+ :transform_id transform-id+ :transform_name (:name transform)+ :transform_entity_id (:entity_id transform)+ :status :started+ :is_active true+ :metered_as metered-as))];; Pass user_id to the event so audit log properly attributes the run(events/publish-event! :event/transform-run-start(cond-> {:object run}@@ -89,25 +70,21 @@([run-id](succeed-started-run! run-id {}))([run-id properties]- (u/prog1 (t2/update! :model/TransformRun- :id run-id- :is_active true- (merge properties- {:end_time :%now- :status :succeeded- :is_active nil}))+ (u/prog1 (transforms.db/finish-active-run! run-id+ (merge properties+ {:end_time :%now+ :status :succeeded+ :is_active nil}))(cancel/delete-cancelation! run-id))))(defn fail-started-run!"Mark the started active run as failed and inactive."[run-id properties]- (u/prog1 (t2/update! :model/TransformRun- :id run-id- :is_active true- (merge properties- {:end_time :%now- :status :failed- :is_active nil}))+ (u/prog1 (transforms.db/finish-active-run! run-id+ (merge properties+ {:end_time :%now+ :status :failed+ :is_active nil}))(cancel/delete-cancelation! run-id)))(defn cancel-run!@@ -115,13 +92,11 @@([run-id](cancel-run! run-id {:message "Canceled by user"}))([run-id properties]- (u/prog1 (t2/update! :model/TransformRun- :id run-id- :is_active true- (merge properties- {:end_time :%now- :status :canceled- :is_active nil}))+ (u/prog1 (transforms.db/finish-active-run! run-id+ (merge properties+ {:end_time :%now+ :status :canceled+ :is_active nil}))(cancel/delete-cancelation! run-id))))(defn- publish-timeout-event!@@ -140,18 +115,16 @@([run-id](timeout-run! run-id {}))([run-id properties]- (u/prog1 (t2/update! :model/TransformRun- :id run-id- :is_active true- (merge properties- {:end_time :%now- :message "Timed out"- :status :timeout- :is_active nil}))+ (u/prog1 (transforms.db/finish-active-run! run-id+ (merge properties+ {:end_time :%now+ :message "Timed out"+ :status :timeout+ :is_active nil}))(cancel/delete-cancelation! run-id)(when (pos? <>)(analytics/inc! :metabase-transforms/timeouts-total {:type "transform"})- (when-let [run (t2/select-one :model/TransformRun :id run-id)]+ (when-let [run (transforms.db/run run-id)](publish-timeout-event! run))))))(defn- reap-transform-runs!@@ -208,31 +181,20 @@(t2/with-transaction [_conn](let [cutoff (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)times (into {} (map (juxt :run_id :time))- (t2/select [:model/TransformRunCancelation :run_id :time]- :time [:< cutoff]))+ (transforms.db/cancelations-requested-before cutoff))locked (when (seq times)- (t2/select :model/TransformRun- {:where [:and [:= :is_active true] [:in :id (keys times)]]- :for :update}))]+ (transforms.db/lock-active-runs (keys times)))](when (seq locked)- (t2/update! :model/TransformRun- :id [:in (mapv :id locked)]- :is_active true- {:status :canceled- :end_time :%now- :is_active nil- :message "Canceled by user but could not guarantee run stopped."})+ (transforms.db/cancel-active-runs! (mapv :id locked))(cancel/delete-old-canceling-runs!))(mapv #(assoc % :request_time (times (:id %)))(when (seq locked)- (t2/select :model/TransformRun :id [:in (mapv :id locked)]))))))+ (transforms.db/runs (mapv :id locked)))))))(defn running-run-for-transform-id"Return a single active transform run or nil."[transform-id]- (t2/select-one :model/TransformRun- :transform_id transform-id- :is_active true))+ (transforms.db/active-run-for-transform transform-id))(defn last-successful-run-times"Map each id in `transform-ids` with a succeeded run to its most recent run's `end_time`. Ids with@@ -241,153 +203,56 @@(when (seq transform-ids)(into {}(map (juxt :transform_id :last_success))- (t2/select :model/TransformRun- {:select [:transform_id [[:max :end_time] :last_success]]- :where [:and- [:in :transform_id transform-ids]- [:= :status "succeeded"]]- :group-by [:transform_id]}))))--(defn- paged-runs-join-clause- "Returns a `:left-join` clause for transform runs sort columns that require joining other tables."- [{:keys [sort-column]}]- (case (keyword sort-column)- :transform-name [:transform [:= :transform_run.transform_id :transform.id]]- nil))--(defn- paged-runs-where-clause- "Builds a `:where` clause for transform runs from the given filter parameters."- [{:keys [start-time end-time run-methods transform-ids transform-tag-ids statuses user-id]}]- (let [where-cond (cond-> []- (some? start-time)- (conj (transforms.models.u/timestamp-constraint :start_time start-time))-- (some? end-time)- (conj (transforms.models.u/timestamp-constraint :end_time end-time))-- (seq run-methods)- (conj [:in :run_method (set run-methods)])-- (seq transform-ids)- (conj [:in :transform_id transform-ids])-- (seq transform-tag-ids)- (conj [:in :transform_id ^:allow-subquery- {:select [:transform_id]- :from [:transform_transform_tag]- :where [:in :tag_id transform-tag-ids]}])+ (transforms.db/last-success-times transform-ids))))- (seq statuses)- (conj [:in :status (set statuses)])-- ;; optimization: is_active condition for started status- (and (= (first statuses) "started")- (nil? (next statuses)))- (conj [:= :is_active true])-- (some? user-id)- (conj [:= :user_id user-id]))]- (when (seq where-cond)- (into [:and] where-cond))))--(defn- translate-run-method-clause- "Returns a HoneySQL `:case` expression that translates run method values to display names."+(defn- status-labels+ "Display labels for TransformRun status values."[]- [:case- [:= :run_method "manual"] (tru "Manual")- [:= :run_method "cron"] (tru "Schedule")- :run_method])--(defn- translate-status-clause- "Returns a HoneySQL `:case` expression that translates run status values to display names."+ {"started" (tru "In progress")+ "succeeded" (tru "Success")+ "failed" (tru "Failed")+ "timeout" (tru "Timeout")+ "canceling" (tru "Canceling")+ "canceled" (tru "Canceled")})++(defn- run-method-labels+ "Display labels for TransformRun run_method values."[]- [:case- [:= :status "started"] (tru "In progress")- [:= :status "succeeded"] (tru "Success")- [:= :status "failed"] (tru "Failed")- [:= :status "timeout"] (tru "Timeout")- [:= :status "canceling"] (tru "Canceling")- [:= :status "canceled"] (tru "Canceled")- :status])+ {"manual" (tru "Manual")+ "cron" (tru "Schedule")})-(defn- translate-tag-name-clause- "Returns a HoneySQL `:case` expression that translates built-in tag names.- `name-field` is the keyword for the name column (e.g. `:transform_tag.name`),- `built-in-type-field` is the keyword for the built_in_type column (e.g. `:transform_tag.built_in_type`)."- [name-field built-in-type-field]- [:case- [:= built-in-type-field "hourly"] (tru "hourly")- [:= built-in-type-field "daily"] (tru "daily")- [:= built-in-type-field "weekly"] (tru "weekly")- [:= built-in-type-field "monthly"] (tru "monthly")- :else name-field])--(defn- first-tag-name-subquery- "Returns a correlated subquery that selects the translated name of the first tag- (by minimum position) assigned to the transform for a transform run."+(defn- tag-name-labels+ "Display labels for built-in TransformTag names."[]- ^:allow-subquery- {:select [[(translate-tag-name-clause :tt.name :tt.built_in_type) :tag_name]]- :from [[:transform_transform_tag :ttt]]- :join [[:transform_tag :tt] [:= :ttt.tag_id :tt.id]]- :where [:and- [:= :ttt.transform_id :transform_run.transform_id]- [:= :ttt.position ^:allow-subquery- {:select [[[:min :ttt2.position]]]- :from [[:transform_transform_tag :ttt2]]- :where [:= :ttt2.transform_id :transform_run.transform_id]}]]})--(defn- paged-runs-order-by-clause- "Builds a HoneySQL `:order-by` clause for transform runs, translating display values for sortable columns."- [{:keys [sort-column sort-direction]}]- (let [sort-column (or (keyword sort-column) :start-time)- sort-direction (or (keyword sort-direction) :desc)- nulls-sort (if (= sort-direction :asc)- :nulls-last- :nulls-first)]- (conj- (case sort-column- :transform-name [[:transform.name sort-direction]]- :start-time [[:start_time sort-direction]]- :end-time [[:end_time sort-direction nulls-sort]]- :status [[(translate-status-clause) sort-direction]]- :run-method [[(translate-run-method-clause) sort-direction]]- :transform-tags [[(first-tag-name-subquery) sort-direction nulls-sort]]- ;; In-progress runs (end_time = nil) sink to the bottom in BOTH- ;; directions — null means "no measurable duration yet," not- ;; "longest duration."- :duration [[[:is :end_time nil] :asc]- [(h2x/calculate-interval-honeysql-form- (mdb/db-type) :end_time :start_time)- sort-direction]]- [[:start_time sort-direction]- [:end_time sort-direction nulls-sort]])- [:transform_run.id sort-direction])))+ {"hourly" (tru "hourly")+ "daily" (tru "daily")+ "weekly" (tru "weekly")+ "monthly" (tru "monthly")})(defn paged-runs"Return a page of the list of the runs.Follows the conventions used by the FE."- [{:keys [offset limit] :as params}]- (let [offset (or offset 0)- limit (or limit 20)- order-by (paged-runs-order-by-clause params)- where-clause (paged-runs-where-clause params)- join-clause (paged-runs-join-clause params)- count-options (m/assoc-some {} :where where-clause)- query-options (m/assoc-some {:order-by order-by :offset offset :limit limit}- :select (when join-clause [:transform_run.*])- :where where-clause- :left-join join-clause)- runs (t2/select :model/TransformRun query-options)- root-collection (collection.root/hydrated-root-collection :transforms)]+ [{:keys [offset limit start-time end-time run-methods transform-ids transform-tag-ids statuses user-id+ sort-column sort-direction]}]+ (let [offset (or offset 0)+ limit (or limit 20)+ [started-at-start started-at-end] (when start-time (transforms.models.u/timestamp-range start-time))+ [ended-at-start ended-at-end] (when end-time (transforms.models.u/timestamp-range end-time))+ filters {:started-at-start started-at-start+ :started-at-end started-at-end+ :ended-at-start ended-at-start+ :ended-at-end ended-at-end+ :run-methods run-methods+ :transform-ids transform-ids+ :transform-tag-ids transform-tag-ids+ :statuses statuses+ :user-id user-id}+ runs (transforms.db/paged-runs filters sort-column sort-direction (status-labels)+ (run-method-labels) (tag-name-labels) limit offset)+ root-collection (collection.root/hydrated-root-collection :transforms)]{:data (->> (t2/hydrate runs [:transform :collection :transform_tag_ids])(map #(update % :transform collection.root/hydrate-root-collection root-collection))):limit limit:offset offset- :total (t2/count :model/TransformRun count-options)}))--(comment- (t2/select :model/TransformRun)- (cancel-run! "slo7dhL7zoclb0uI0Zchj")- -)+ :total (transforms.db/paged-run-count filters)}))diff --git a/src/metabase/transforms/models/transform_run_cancelation.clj b/src/metabase/transforms/models/transform_run_cancelation.cljindex 3467c86c9b3..aff0ab92b9d 100644--- a/src/metabase/transforms/models/transform_run_cancelation.clj+++ b/src/metabase/transforms/models/transform_run_cancelation.clj@@ -1,6 +1,7 @@(ns metabase.transforms.models.transform-run-cancelation(:require[metabase.analytics-interface.core :as analytics]+ [metabase.transforms.db :as transforms.db][metabase.util.log :as log][methodical.core :as methodical][toucan2.core :as t2]))@@ -15,17 +16,8 @@"Mark a started run for cancelation."[run-id](try- (t2/query-one- [(str "INSERT INTO transform_run_cancelation (run_id) "- "SELECT transform_run.id "- "FROM transform_run "- "WHERE transform_run.id = ? "- "AND transform_run.is_active "- "AND NOT EXISTS (SELECT 1 FROM transform_run_cancelation WHERE run_id = ?)")- run-id run-id])- (t2/update! :model/TransformRun- :id run-id- {:status "canceling"})+ (transforms.db/insert-cancelation-for-active-run! run-id)+ (transforms.db/mark-run-canceling! run-id)(log/infof "Cancelation requested for transform run %s" run-id)(analytics/inc! :metabase-transforms/cancelation-requests {:status "ok"})nil@@ -36,27 +28,14 @@(defn reducible-canceled-local-runs"Return a reducible sequence of local canceled runs."[]- (t2/reducible-select :model/TransformRunCancelation))--(defn- no-active-run-clause- []- [:not [:exists ^:allow-subquery- {:select [1]- :from [[:transform_run :wr]]- :where [:and- [:= :wr.id :transform_run_cancelation.run_id]- :wr.is_active]}]])+ (transforms.db/cancelations-reducible))(defn delete-cancelation!"Delete a cancelation once it has been handled."[run-id]- (t2/delete! :model/TransformRunCancelation- {:where [:and- [:= :run_id run-id]- (no-active-run-clause)]}))+ (transforms.db/delete-cancelation-for-inactive-run! run-id))(defn delete-old-canceling-runs!"Delete cancelations for runs that are no longer running."[]- (t2/delete! :model/TransformRunCancelation- {:where (no-active-run-clause)}))+ (transforms.db/delete-cancelations-for-inactive-runs!))diff --git a/src/metabase/transforms/models/transform_tag.clj b/src/metabase/transforms/models/transform_tag.cljindex 0277204115b..4a58501c706 100644--- a/src/metabase/transforms/models/transform_tag.clj+++ b/src/metabase/transforms/models/transform_tag.clj@@ -4,6 +4,7 @@[metabase.events.core :as events][metabase.models.interface :as mi][metabase.models.serialization :as serdes]+ [metabase.transforms.db :as transforms.db][metabase.transforms.models.transform :as transform][metabase.util.i18n :as i18n][methodical.core :as methodical]@@ -29,7 +30,7 @@(let [transforms (transform/transforms-with-tags [(:id instance)])](every? mi/can-write? transforms)))))([_model pk]- (when-let [tag (t2/select-one :model/TransformTag :id pk)]+ (when-let [tag (transforms.db/tag pk)](mi/can-write? tag))))(defmethod mi/can-create? :model/TransformTag@@ -44,24 +45,17 @@(reduce (fn [m {:keys [transform_id schedule]}](update m transform_id (fnil conj #{}) schedule)){}- (t2/select :model/TransformTransformTag- {:select [:ttt.transform_id [:job.schedule :schedule]]- :from [[:transform_transform_tag :ttt]]- :join [[:transform_job_transform_tag :jtt] [:= :ttt.tag_id :jtt.tag_id]- [:transform_job :job] [:= :jtt.job_id :job.id]]- :where [:and- [:in :ttt.transform_id transform-ids]- [:= :job.active true]]}))))+ (transforms.db/active-job-schedules-for-transforms transform-ids))))(defn tag-name-exists?"Check if a tag with the given name already exists"[tag-name]- (t2/exists? :model/TransformTag :name tag-name))+ (transforms.db/tag-name-exists? tag-name))(defn tag-name-exists-excluding?"Check if a tag with the given name exists, excluding the specified ID"[tag-name tag-id]- (t2/exists? :model/TransformTag :name tag-name :id [:not= tag-id]))+ (transforms.db/tag-name-exists-excluding? tag-name tag-id))(defn- translate-name [tag](let [values {"hourly" (i18n/deferred-trs "hourly")@@ -92,13 +86,12 @@tags(let [tag-ids (into #{} (map :id) tags);; Get all transform-tag associations- associations (t2/select [:model/TransformTransformTag :tag_id :transform_id]- :tag_id [:in tag-ids])+ associations (transforms.db/transform-tag-links-for-tags tag-ids);; Get unique transform IDstransform-ids (into #{} (map :transform_id) associations);; Fetch transforms and check can-write? for eachtransforms (when (seq transform-ids)- (t2/select :model/Transform :id [:in transform-ids]))+ (transforms.db/transforms transform-ids))transform-id->can-write (into {} (map (juxt :id mi/can-write?)) transforms);; Build tag-id -> can_run maptag-id->transform-ids (reduce (fn [acc {:keys [tag_id transform_id]}]diff --git a/src/metabase/transforms/models/util.clj b/src/metabase/transforms/models/util.cljindex 9dfdc573c33..876fb3ecb50 100644--- a/src/metabase/transforms/models/util.clj+++ b/src/metabase/transforms/models/util.clj@@ -6,33 +6,24 @@(set! *warn-on-reflection* true)-(defn timestamp-constraint- "Build a HoneySQL `[:and ...]` clause constraining `field-name` to the range expressed by `date-string`.- `date-string` uses the same format as the query-processor date parameter (e.g. \"2025-01\", \"past7days\")."- [field-name date-string]+(defn timestamp-range+ "Parse `date-string` (in the same format as the query-processor date parameter, e.g. \"2025-01\",+ \"past7days\") into a `[start end]` pair of instants (either may be nil)."+ [date-string](let [{:keys [start end]}(try(params.dates/date-string->range date-string {:inclusive-end? false})(catch Exception e(throw (ex-info (tru "Failed to parse datetime value: {0}" date-string){:status-code 400}- e))))- start (some-> start u.date/parse)- end (some-> end u.date/parse)]+ e))))]+ [(some-> start u.date/parse) (some-> end u.date/parse)]))++(defn timestamp-constraint+ "Build a HoneySQL `[:and ...]` clause constraining `field-name` to the range expressed by `date-string`.+ `date-string` uses the same format as the query-processor date parameter (e.g. \"2025-01\", \"past7days\")."+ [field-name date-string]+ (let [[start end] (timestamp-range date-string)](into [:and] (remove nil?)[(when start [:>= field-name start])(when end [:< field-name end])])))--(defn run-order-by- "Standard `:order-by` clause for a paged run listing. Sorts by `sort-column` (`:start_time` or- `:end_time`; anything else — including nil — falls back to ordering by start_time then end_time)- in `sort-direction` (`:asc`/`:desc`, defaulting to `:desc`), with in-progress rows (null- `end_time`) always ordered last."- [sort-column sort-direction]- (let [sort-direction (or (keyword sort-direction) :desc)- nulls-sort (if (= sort-direction :asc) :nulls-last :nulls-first)]- (case (keyword sort-column)- :start_time [[:start_time sort-direction]]- :end_time [[:end_time sort-direction nulls-sort]]- [[:start_time sort-direction]- [:end_time sort-direction nulls-sort]])))diff --git a/src/metabase/transforms/notification.clj b/src/metabase/transforms/notification.cljindex 45b19fc6d29..99384ed799e 100644--- a/src/metabase/transforms/notification.clj+++ b/src/metabase/transforms/notification.clj@@ -10,22 +10,16 @@[metabase.events.core :as events][metabase.query-processor.timezone :as qp.timezone][metabase.task.core :as task]+ [metabase.transforms.db :as transforms.db][metabase.util.date-2 :as u.date]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)(defn- recent-failed-cron-job-runs"Cron job runs that failed or timed out in `[start, end)`, oldest first."[start end]- (t2/select [:model/TransformJobRun :job_id :start_time :message]- {:where [:and- [:= :run_method "cron"]- [:in :status ["failed" "timeout"]]- [:>= :start_time start]- [:< :start_time end]]- :order-by [[:start_time :asc]]}))+ (transforms.db/failed-cron-job-runs-between start end))(defn failing-jobs"Summarize failed/timed-out cron job runs in `[start, end)`, one entry per job."@@ -33,7 +27,7 @@(let [runs (recent-failed-cron-job-runs start end)job-ids (distinct (map :job_id runs))id->name (when (seq job-ids)- (t2/select-pk->fn :name :model/TransformJob :id [:in job-ids]))]+ (transforms.db/job-names-by-id job-ids))](->> (group-by :job_id runs);; `runs` is oldest-first, and group-by preserves that within each job's group(map (fn [[job-id job-runs]]diff --git a/src/metabase/transforms/query_impl.clj b/src/metabase/transforms/query_impl.cljindex 4985c80dd47..7232f890867 100644--- a/src/metabase/transforms/query_impl.clj+++ b/src/metabase/transforms/query_impl.clj@@ -7,11 +7,11 @@[metabase.tracing.core :as tracing][metabase.transforms-base.interface :as transforms-base.i][metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.db :as transforms.db][metabase.transforms.instrumentation :as transforms.instrumentation][metabase.transforms.interface :as transforms.i][metabase.transforms.util :as transforms.u]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(set! *warn-on-reflection* true)@@ -20,7 +20,7 @@([{:keys [id source target owner_user_id creator_id] :as transform}{:keys [run-method on-start user-id parent-run]}](try- (let [db (t2/select-one :model/Database (get-in source [:query :database]))+ (let [db (transforms.db/database (get-in source [:query :database]))driver (:engine db)_ (transforms-base.u/throw-if-db-routing-enabled! transform db)run-user-id (if (and (= run-method :manual) user-id)diff --git a/src/metabase/transforms/run_listing.clj b/src/metabase/transforms/run_listing.cljindex e72a22826ae..d9a0600b531 100644--- a/src/metabase/transforms/run_listing.clj+++ b/src/metabase/transforms/run_listing.clj@@ -11,8 +11,8 @@(:require[medley.core :as m][metabase.transforms-base.util :as transforms-base.u]- [metabase.transforms.models.util :as transforms.models.u]- [toucan2.core :as t2]))+ [metabase.transforms.db :as transforms.db]+ [metabase.transforms.models.util :as transforms.models.u]))(set! *warn-on-reflection* true)@@ -20,81 +20,6 @@"The `run_type` discriminator values a listing row can have."[:job :dag :transform])-;;; ---------------------------------------------- Per-source subqueries ------------------------------------------------;; Each branch must project the same columns in the same order for the UNION ALL to line up;-;; `[nil :col]` fills in columns a table lacks.--(defn- job-run-subquery [transform-ids]- ^:allow-subquery- {:select [[^:allow-raw-sql [:inline "job"] :run_type]- :id- [:job_id :entity_id]- [:job_name :entity_name]- [nil :direction]- [nil :transform_count]- :run_method- :status :is_active :start_time :end_time :message- [nil :user_id]]- :from [:transform_job_run]- :where (if (seq transform-ids)- ;; only job runs that actually ran one of these transforms- [:exists ^:allow-subquery {:select [[[:inline 1]]]- :from [[:transform_run :member]]- :where [:and- [:= :member.job_run_id :transform_job_run.id]- [:in :member.transform_id transform-ids]]}]- true)})--(defn- dag-run-subquery [transform-ids]- ^:allow-subquery- {:select [[^:allow-raw-sql [:inline "dag"] :run_type]- :id- [:source_transform_id :entity_id]- [:source_transform_name :entity_name]- :direction- :transform_count- [^:allow-raw-sql [:inline "manual"] :run_method]- :status :is_active :start_time :end_time :message- :user_id]- :from [:transform_dag_run]- :where (if (seq transform-ids)- [:exists ^:allow-subquery {:select [[[:inline 1]]]- :from [[:transform_run :member]]- :where [:and- [:= :member.dag_run_id :transform_dag_run.id]- [:in :member.transform_id transform-ids]]}]- true)})--(defn- transform-run-subquery [transform-ids]- ^:allow-subquery- {:select [[^:allow-raw-sql [:inline "transform"] :run_type]- :id- [:transform_id :entity_id]- [:transform_name :entity_name]- [nil :direction]- [nil :transform_count]- :run_method- :status :is_active :start_time :end_time :message- :user_id]- :from [:transform_run]- ;; standalone runs only: those not coordinated by a job or DAG run- :where (cond-> [:and- [:= :job_run_id nil]- [:= :dag_run_id nil]]- (seq transform-ids) (conj [:in :transform_id transform-ids]))})--(defn- union-subquery- "The UNION ALL of the branches selected by `types` (a subset of [[run-types]]), each optionally- narrowed to runs touching one of `transform-ids`."- [types transform-ids]- (let [types (set (or (seq types) run-types))]- ^:allow-subquery- {:union-all (cond-> []- (:job types) (conj (job-run-subquery transform-ids))- (:dag types) (conj (dag-run-subquery transform-ids))- (:transform types) (conj (transform-run-subquery transform-ids)))}))-(defn paged-run-summaries"Return a page of root runs as a `{:data :limit :offset :total}` envelope. Rows are raw — see[[present-run-summaries]].@@ -111,27 +36,16 @@- `:sort-direction` `\"asc\"` / `\"desc\"`- `:offset`/`:limit` pagination (default 0 / 20)"[{:keys [types statuses run-methods start-time end-time transform-ids sort-column sort-direction offset limit]}]- (let [offset (or offset 0)- limit (or limit 20)- inner (union-subquery types transform-ids)- where (into [:and] (remove nil?)- [(when (seq statuses) [:in :status (set statuses)])- ;; started ⇒ still active, as in the per-table run listings- (when (= (set statuses) #{"started"}) [:= :is_active true])- (when (seq run-methods) [:in :run_method (set run-methods)])- (when start-time (transforms.models.u/timestamp-constraint :start_time start-time))- (when end-time (transforms.models.u/timestamp-constraint :end_time end-time))])- where (when (> (count where) 1) where)- base (cond-> {:from [[inner :runs]]}- where (assoc :where where))]- {:data (t2/query (merge base- {:select [:*]- :order-by (transforms.models.u/run-order-by sort-column sort-direction)- :limit limit- :offset offset}))+ (let [offset (or offset 0)+ limit (or limit 20)+ [start-at end-at] (when start-time (transforms.models.u/timestamp-range start-time))+ [ended-at end-end] (when end-time (transforms.models.u/timestamp-range end-time))]+ {:data (transforms.db/root-run-summaries-page types statuses run-methods start-at end-at ended-at end-end+ transform-ids sort-column sort-direction limit offset):limit limit:offset offset- :total (:count (first (t2/query (merge base {:select [[[:count :*] :count]]}))))}))+ :total (transforms.db/root-run-summaries-count types statuses run-methods start-at end-at ended-at end-end+ transform-ids)}))(defn present-run-summaries"Prepare raw summary rows for an API response: hydrate each row's `:name` (nil when the underlying@@ -140,8 +54,8 @@(let [by-type (group-by :run_type rows)job-ids (seq (keep :entity_id (get by-type "job")))transform-ids (seq (keep :entity_id (concat (get by-type "dag") (get by-type "transform"))))- job->name (when job-ids (t2/select-pk->fn :name :model/TransformJob :id [:in job-ids]))- transform->name (when transform-ids (t2/select-pk->fn :name :model/Transform :id [:in transform-ids]))]+ job->name (when job-ids (transforms.db/job-names-by-id job-ids))+ transform->name (when transform-ids (transforms.db/transform-names-by-id transform-ids))](map (fn [{:keys [run_type entity_id entity_name] :as row}](-> row(assoc :name (or (if (= run_type "job")diff --git a/src/metabase/transforms/schedule.clj b/src/metabase/transforms/schedule.cljindex 53af55e8b49..206900ba309 100644--- a/src/metabase/transforms/schedule.clj+++ b/src/metabase/transforms/schedule.clj@@ -8,10 +8,10 @@[metabase.query-processor.timezone :as qp.timezone][metabase.task-history.core :as task-history][metabase.task.core :as task]+ [metabase.transforms.db :as transforms.db][metabase.transforms.jobs :as transforms.jobs][metabase.transforms.settings :as transforms.settings]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.util TimeZone)(org.quartz CronTrigger TriggerKey CronExpression)))@@ -137,5 +137,5 @@(defmethod task/init! ::RunTransform [_](log/info "Initializing transform job execution jobs")- (->> (t2/select :model/TransformJob :active true)+ (->> (transforms.db/active-jobs)(run! initialize-job!)))diff --git a/src/metabase/transforms/util.clj b/src/metabase/transforms/util.cljindex d70db490d6c..0925f6589b4 100644--- a/src/metabase/transforms/util.clj+++ b/src/metabase/transforms/util.clj@@ -23,13 +23,13 @@[metabase.tracing.core :as tracing][metabase.transforms-base.util :as transforms-base.u][metabase.transforms.canceling :as canceling]+ [metabase.transforms.db :as transforms.db][metabase.transforms.feature-gating :as transforms.gating][metabase.transforms.instrumentation :as transforms.instrumentation][metabase.transforms.models.transform-run :as transform-run][metabase.transforms.settings :as transforms.settings][metabase.util :as u]- [metabase.util.log :as log]- [toucan2.core :as t2])+ [metabase.util.log :as log])(:import(java.sql SQLException)))@@ -81,7 +81,9 @@(let [resolve* (fn [model id](if models-cache(get-in models-cache [model id])- (t2/select-one model id)))+ (case model+ :model/Database (transforms.db/database id)+ :model/Table (transforms.db/table id))))source (:source transform)](case (keyword (:type source)):query@@ -123,9 +125,9 @@(let [db-ids (into #{} (keep #(get-in % [:source :query :database])) transforms)table-ids (into #{} (mapcat #(keep :table_id (get-in % [:source :source-tables]))) transforms)]{:model/Database (when (seq db-ids)- (u/index-by :id (t2/select :model/Database :id [:in db-ids])))+ (u/index-by :id (transforms.db/databases db-ids))):model/Table (when (seq table-ids)- (u/index-by :id (t2/select :model/Table :id [:in table-ids])))}))+ (u/index-by :id (transforms.db/tables table-ids)))}))(defn add-source-readable"Add :source_readable field to a transform or collection of transforms.diff --git a/src/metabase/transforms_base/db.clj b/src/metabase/transforms_base/db.cljnew file mode 100644index 00000000000..be3017f682c--- /dev/null+++ b/src/metabase/transforms_base/db.clj@@ -0,0 +1,105 @@+(ns metabase.transforms-base.db+ "Application database queries for the transforms base module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++(defn transform-source+ "The source of the Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one-fn :source [:model/Transform :id :source] transform-id))++(defn transforms-for-ordering+ "The id, name, target, target Table id, source Database id, and table dependencies of every Transform."+ []+ (t2/select [:model/Transform :id :name :target :target_table_id :source_database_id :table_dependencies]))++(defn transform+ "The Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/Transform transform-id))++(defn update-transform!+ "Apply `changes` to the Transform with `transform-id`."+ [transform-id changes]+ (t2/update! :model/Transform transform-id changes))++(defn update-transform-run!+ "Apply `changes` to the TransformRun with `run-id`."+ [run-id changes]+ (t2/update! :model/TransformRun run-id changes))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn field-table-id+ "The Table id of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one-fn :table_id :model/Field field-id))++(defn target-table+ "The Table named `table-name` in `schema` of the Database with `database-id` also matching the key-value+ `conditions`, or nil."+ [database-id schema table-name & conditions]+ (apply t2/select-one :model/Table :db_id database-id :schema schema :name table-name conditions))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table table-id))++(defn table-for-transform+ "The Table owned by the Transform with `transform-id`, or nil."+ [transform-id]+ (t2/select-one :model/Table :transform_id transform-id))++(defn update-table!+ "Apply `changes` to the Table with `table-id`."+ [table-id changes]+ (t2/update! :model/Table table-id changes))++(defn mark-table-index-failed!+ "Mark the TableIndex named `index-name` of the Transform with `transform-id` failed with `error-message`."+ [transform-id index-name error-message]+ (t2/update! :model/TableIndex+ :transform_id transform-id :index_name index-name+ {:status :failed :error_message error-message :last_executed_at :%now}))++(defn delete-table-indexes!+ "Delete the TableIndexes with `ids`."+ [ids]+ (t2/delete! :model/TableIndex :id [:in ids]))++(defn update-table-indexes!+ "Apply `changes` to the TableIndexes with `ids`."+ [ids changes]+ (t2/update! :model/TableIndex :id [:in ids] changes))++(defn active-field-names-for-table+ "The names of the active Fields of the Table with `table-id`, in position order."+ [table-id]+ (t2/select-fn-vec :name [:model/Field :name :position]+ :table_id table-id :active true+ {:order-by [[:position :asc]]}))++(defn table-refs-matching+ "The id, Database id, schema, and name of the Tables matching any of `refs` (each a `[db-id schema table-name]`+ triple; `schema` may be nil)."+ [refs]+ (t2/select [:model/Table :id :db_id :schema :name]+ {:where (into [:or]+ (map (fn [[db-id schema table-name]]+ [:and+ [:= :db_id db-id]+ (if (some? schema)+ [:= :schema schema]+ [:is :schema nil])+ [:= :name table-name]]))+ refs)}))++(defn table-refs+ "The id, Database id, schema, and name of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :db_id :schema :name] :id [:in table-ids]))diff --git a/src/metabase/transforms_base/ordering.clj b/src/metabase/transforms_base/ordering.cljindex 9c3dc233cef..6d456263da8 100644--- a/src/metabase/transforms_base/ordering.clj+++ b/src/metabase/transforms_base/ordering.clj@@ -11,12 +11,12 @@[metabase.lib.metadata :as lib.metadata][metabase.premium-features.core :refer [defenterprise]][metabase.query-processor.preprocess :as qp.preprocess]+ [metabase.transforms-base.db :as transforms-base.db][metabase.transforms-base.interface :as transforms-base.i][metabase.transforms-base.util :as transforms-base.u][metabase.util :as u][metabase.util.i18n :as i18n]- [metabase.util.malli :as mu]- [toucan2.core :as t2])+ [metabase.util.malli :as mu])(:import(clojure.lang ExceptionInfo)))@@ -74,13 +74,13 @@;; load :source on demand on a cache miss, so callers can omit the heavy blob from their select(cond-> transform(and (not (:source transform)) (:id transform))- (assoc :source (t2/select-one-fn :source [:model/Transform :id :source] (:id transform)))))))+ (assoc :source (transforms-base.db/transform-source (:id transform)))))))(defn references-card-or-snippet?"True if `transform`'s source query reads through a saved card or native snippet."[transform](let [query (:query (or (:source transform)- (t2/select-one-fn :source [:model/Transform :id :source] (:id transform))))]+ (transforms-base.db/transform-source (:id transform))))](boolean(when query(try@@ -254,8 +254,7 @@(if (= id transform-id)to-checktransform))- (t2/select [:model/Transform :id :name :target :target_table_id- :source_database_id :table_dependencies]))+ (transforms-base.db/transforms-for-ordering))transforms-by-id (into {}(map (juxt :id identity))transforms)diff --git a/src/metabase/transforms_base/query.clj b/src/metabase/transforms_base/query.cljindex 06f795a6604..a6cfe3618ab 100644--- a/src/metabase/transforms_base/query.clj+++ b/src/metabase/transforms_base/query.clj@@ -9,13 +9,13 @@[metabase.driver.util :as driver.u][metabase.lib.schema.common :as schema.common][metabase.query-processor.compile :as qp.compile]+ [metabase.transforms-base.db :as transforms-base.db][metabase.transforms-base.interface :as transforms-base.i][metabase.transforms-base.schema :as transforms-base.schema][metabase.transforms-base.util :as transforms-base.u][metabase.util.log :as log][metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [metabase.util.malli.registry :as mr]))(set! *warn-on-reflection* true)@@ -94,7 +94,7 @@(when (and cancelled? (cancelled?))(throw (ex-info "Transform cancelled before start" {:status :cancelled})))(let [db (get-in source [:query :database])- {driver :engine :as database} (when db (t2/select-one :model/Database db))+ {driver :engine :as database} (when db (transforms-base.db/database db))_ (when-not database(throw (ex-info "Source database for this transform has been deleted."{:transform-id (:id transform)diff --git a/src/metabase/transforms_base/util.clj b/src/metabase/transforms_base/util.cljindex 55eaeb76e03..d7683338b53 100644--- a/src/metabase/transforms_base/util.clj+++ b/src/metabase/transforms_base/util.clj@@ -25,6 +25,7 @@[metabase.query-processor.parameters.dates :as params.dates][metabase.query-processor.preprocess :as qp.preprocess][metabase.sync.core :as sync]+ [metabase.transforms-base.db :as transforms-base.db][metabase.transforms-base.interface :as transforms-base.i][metabase.transforms-base.schema :as transforms-base.schema][metabase.util :as u]@@ -146,7 +147,7 @@after the transform was made incremental."[{:keys [source]}](let [field-id (get-in source [:source-incremental-strategy :checkpoint-filter-field-id])- table-id (when field-id (t2/select-one-fn :table_id :model/Field field-id))]+ table-id (when field-id (transforms-base.db/field-table-id field-id))](table-template-tag-name (:query source) table-id)));;; ------------------------------------------------- Transform Normalization -------------------------------------------------@@ -269,9 +270,7 @@"Commits the incremental transforms :hi watermark value to the appdb."[transform-id source-range-params](let [hi-value (:value (:hi source-range-params))]- (t2/update! :model/Transform- transform-id- {:last_checkpoint_value (some-> hi-value encode-checkpoint-value)})))+ (transforms-base.db/update-transform! transform-id {:last_checkpoint_value (some-> hi-value encode-checkpoint-value)})))(defn save-run-checkpoint-range!"Persist the checkpoint range (lo/hi) on a transform run record.@@ -279,10 +278,10 @@[run-id source-range-params](when (and run-id source-range-params)(let [{:keys [checkpoint-filter-field-id lo hi]} source-range-params]- (t2/update! :model/TransformRun run-id- (cond-> {:checkpoint_filter_field_id checkpoint-filter-field-id}- lo (assoc :checkpoint_lo_value (encode-checkpoint-value (:value lo)))- hi (assoc :checkpoint_hi_value (encode-checkpoint-value (:value hi))))))))+ (transforms-base.db/update-transform-run! run-id+ (cond-> {:checkpoint_filter_field_id checkpoint-filter-field-id}+ lo (assoc :checkpoint_lo_value (encode-checkpoint-value (:value lo)))+ hi (assoc :checkpoint_hi_value (encode-checkpoint-value (:value hi))))))))(defn- coerce-to-local-datetime"Coerce a temporal value to LocalDateTime, stripping any timezone information."@@ -507,18 +506,14 @@(defn target-table"Load the `target` table of a transform from the database specified by `database-id`."[database-id target & kv-args]- (some-> (apply t2/select-one :model/Table- :db_id database-id- :schema (:schema target)- :name (:name target)- kv-args)+ (some-> (apply transforms-base.db/target-table database-id (:schema target) (:name target) kv-args)(t2/hydrate :db)))(defn target-table-exists?"Test if the target table of a transform already exists."[{:keys [target] :as transform}](let [db-id (transforms-base.i/target-db-id transform)- {driver :engine :as database} (t2/select-one :model/Database db-id)]+ {driver :engine :as database} (transforms-base.db/database db-id)](driver/table-exists? driver database target)))(defn- sync-table!@@ -531,8 +526,8 @@;; the driver's default schema. If so, fix the Table record before syncing.(let [table (if (nil? (:schema table))(if-let [actual-schema (resolve-nil-schema (:engine database) database table)]- (do (t2/update! :model/Table (:id table) {:schema actual-schema})- (-> (t2/select-one :model/Table (:id table))+ (do (transforms-base.db/update-table! (:id table) {:schema actual-schema})+ (-> (transforms-base.db/table (:id table))(t2/hydrate :db)))table)table)]@@ -548,7 +543,7 @@:is_writable false){:create? true})](when-not (:active table)- (t2/update! :model/Table (:id table) {:active true}))+ (transforms-base.db/update-table! (:id table) {:active true}))table))(defn sync-target!@@ -563,7 +558,7 @@[database target](when-let [table (sync-table! database target)];; TODO this should probably be a function in the sync module- (t2/update! :model/Table (:id table) {:active false})))+ (transforms-base.db/update-table! (:id table) {:active false})))(defn delete-target-table!"Drop a transform's output table and deactivate its app-db Table row."@@ -571,7 +566,7 @@(when target(let [database-id (transforms-base.i/target-db-id transform)](when database-id- (if-let [{driver :engine :as database} (t2/select-one :model/Database database-id)]+ (if-let [{driver :engine :as database} (transforms-base.db/database database-id)](let [drop-target (update target :type keyword)](driver/drop-transform-target! driver database drop-target)(log/info "Deactivating target " (pr-str target) "for transform" id)@@ -582,7 +577,7 @@(defn delete-target-table-by-id!"Delete the target table of the transform specified by `transform-id`."[transform-id]- (delete-target-table! (t2/select-one :model/Transform transform-id)))+ (delete-target-table! (transforms-base.db/transform transform-id)));;; ------------------------------------------------- Table DDL -------------------------------------------------@@ -640,9 +635,7 @@"Best-effort: flag the request for `index` (located by its canonical name) failed, with the error message."[transform-id index ^Throwable t](when transform-id- (t2/update! :model/TableIndex- :transform_id transform-id :index_name (reconcile/index-name index)- {:status :failed :error_message (ex-message t) :last_executed_at :%now})))+ (transforms-base.db/mark-table-index-failed! transform-id (reconcile/index-name index) (ex-message t))))(defn- apply-standalone-indexes!"Create the target's `:standalone` indexes as separate DDL, now that the table exists. `:inline` kinds render at@@ -673,7 +666,7 @@[transform](when (and (seq (:indexes (:target transform)))(full-create-run? transform))- (let [database (t2/select-one :model/Database (transforms-base.i/target-db-id transform))]+ (let [database (transforms-base.db/database (transforms-base.i/target-db-id transform))](apply-standalone-indexes! database (assoc (:target transform) :transform-id (:id transform))))))(defn- apply-index-outcomes!@@ -682,14 +675,14 @@[by-outcome](doseq [[status rows] by-outcome](if (= :delete-row status)- (t2/delete! :model/TableIndex :id [:in (map :id rows)])- (t2/update! :model/TableIndex :id [:in (map :id rows)]- (cond-> {:status status- :last_executed_at :%now}- (= status :succeeded)- (assoc :error_message nil)- (= status :failed)- (assoc :error_message "Index was not found on the target table after the transform ran."))))))+ (transforms-base.db/delete-table-indexes! (map :id rows))+ (transforms-base.db/update-table-indexes! (map :id rows)+ (cond-> {:status status+ :last_executed_at :%now}+ (= status :succeeded)+ (assoc :error_message nil)+ (= status :failed)+ (assoc :error_message "Index was not found on the target table after the transform ran."))))))(defn verify-managed-indexes!"Reconcile each index request against what's physically in the warehouse and set its `:status`.@@ -701,7 +694,7 @@(table-index/select-for-verification (:id transform) (:index-request-ids target))(table-index/select-for-transform (:id transform)))](when-let [managed (seq managed)]- (let [database (t2/select-one :model/Database (transforms-base.i/target-db-id transform))+ (let [database (transforms-base.db/database (transforms-base.i/target-db-id transform)){:keys [schema] table-name :name} (:target transform)](if-some [warehouse-indexes (reconcile/fetch-warehouse-indexes database schema table-name)](apply-index-outcomes!@@ -726,11 +719,11 @@{:keys [publish-events?]:or {publish-events? true}} optsdb-id (transforms-base.i/target-db-id transform)- database (t2/select-one :model/Database db-id)]+ database (transforms-base.db/database db-id)];; Sync target table, set target_table_id on transform, and mark table as owned by this transform(when-let [table (sync-target! target database)]- (t2/update! :model/Transform (:id transform) {:target_table_id (:id table)})- (t2/update! :model/Table (:id table) {:transform_id (:id transform)}))+ (transforms-base.db/update-transform! (:id transform) {:target_table_id (:id table)})+ (transforms-base.db/update-table! (:id table) {:transform_id (:id transform)}));; ANALYZE the target before the run is observable, so dependents don't plan on stale stats.;; Best-effort: a stats failure shouldn't fail an otherwise-successful run.(try@@ -750,7 +743,7 @@(defn output-table"Return the output table created by a transform, looked up via `transform_id`."[transform]- (t2/select-one :model/Table :transform_id (:id transform)))+ (transforms-base.db/table-for-transform (:id transform)))(defn merge-target-unique-key"Physical column names of a transform's `merge` unique key, or nil when the target isn't a merge target."@@ -762,9 +755,7 @@"Physical column names of a transform's synced target table, ordered by position, or nil."[transform](when-let [table (output-table transform)]- (not-empty (t2/select-fn-vec :name [:model/Field :name :position]- :table_id (:id table) :active true- {:order-by [[:position :asc]]}))))+ (not-empty (transforms-base.db/active-field-names-for-table (:id table)))))(defn validate-merge-unique-key!"Throws if any of `unique-key` is not present in `columns`. Returns `unique-key`."@@ -789,17 +780,10 @@[refs](when (seq refs)(let [unique-refs (distinct (map (juxt :database_id :schema :table) refs))- ref->clause (fn [[db-id schema table-name]]- [:and- [:= :db_id db-id]- (if (some? schema)- [:= :schema schema]- [:is :schema nil])- [:= :name table-name]])fetch-batch (fn [batch]- (t2/select-fn->fn (juxt :db_id :schema :name) :id- [:model/Table :id :db_id :schema :name]- {:where (into [:or] (map ref->clause batch))}))]+ (into {}+ (map (juxt (juxt :db_id :schema :name) :id))+ (transforms-base.db/table-refs-matching batch)))](into {} (mapcat fetch-batch) (partition-all batch-lookup-chunk-size unique-refs)))))(defn- source-table-ref->key@@ -832,10 +816,10 @@needs-metadata (filter (fn [e] (and (:table_id e) (not (:table e)))) source-tables)int-id->metadata (when (seq needs-metadata)(let [ids (into #{} (map :table_id) needs-metadata)]- (t2/select-pk->fn (fn [{:keys [db_id schema name]}]- {:database_id db_id :schema schema :table name})- [:model/Table :id :db_id :schema :name]- :id [:in ids])))+ (into {}+ (map (juxt :id (fn [{:keys [db_id schema name]}]+ {:database_id db_id :schema schema :table name})))+ (transforms-base.db/table-refs ids))))missing-ids (when (seq needs-metadata)(let [ids (into #{} (map :table_id) needs-metadata)](remove (or int-id->metadata {}) ids)))diff --git a/src/metabase/transforms_rest/api/transform.clj b/src/metabase/transforms_rest/api/transform.cljindex 3e71ab33473..cb0a77f919f 100644--- a/src/metabase/transforms_rest/api/transform.clj+++ b/src/metabase/transforms_rest/api/transform.clj@@ -10,6 +10,7 @@[metabase.transforms-rest.api.transform-job][metabase.transforms-rest.api.transform-tag][metabase.transforms-rest.api.util :as transforms-rest.api.u]+ [metabase.transforms-rest.db :as transforms-rest.db][metabase.transforms.core :as transforms.core][metabase.transforms.schema :as transforms.schema][metabase.transforms.util :as transforms.u]@@ -199,7 +200,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](api/read-check :model/Transform id)- (let [id->transform (t2/select-pk->fn identity :model/Transform)+ (let [id->transform (transforms-rest.db/transforms-by-id){graph :dependencies} (transforms.core/transform-ordering #{id} (vals id->transform))dep-ids (get graph id)dependencies (map id->transform dep-ids)]@@ -285,7 +286,7 @@[{:keys [run-id]} :- [:map[:run-id ms/PositiveInt]]](api/check-data-analyst)- (let [run (api/check-404 (t2/select-one :model/TransformRun :id run-id))]+ (let [run (api/check-404 (transforms-rest.db/transform-run run-id))](-> (t2/hydrate run [:transform :collection :transform_tag_ids])transforms-base.u/present-run)))@@ -339,7 +340,7 @@"Reset the stored checkpoint for an incremental transform."[{:keys [id]} :- [:map [:id ms/PositiveInt]]](api/write-check :model/Transform id)- (t2/update! :model/Transform id {:last_checkpoint_value nil})+ (transforms-rest.db/reset-checkpoint! id)nil)(defn- check-feature-and-lock!diff --git a/src/metabase/transforms_rest/api/transform_dag_run.clj b/src/metabase/transforms_rest/api/transform_dag_run.cljindex c79c0268fb2..97f66080b3c 100644--- a/src/metabase/transforms_rest/api/transform_dag_run.clj+++ b/src/metabase/transforms_rest/api/transform_dag_run.clj@@ -8,6 +8,7 @@[metabase.api.routes.common :refer [+auth]][metabase.transforms-base.util :as transforms-base.u][metabase.transforms-rest.api.util :as transforms-rest.api.u]+ [metabase.transforms-rest.db :as transforms-rest.db][metabase.transforms.core :as transforms.core][metabase.util.malli.schema :as ms][toucan2.core :as t2]))@@ -30,7 +31,7 @@(api.macros/defendpoint :get "/:run-id/transform-runs" :- [:sequential transforms-rest.api.u/MemberTransformRunResponse]"Get the transform runs that made up a specific DAG run."[{:keys [run-id]} :- [:map [:run-id ms/PositiveInt]]]- (let [dag-run (api/check-404 (t2/select-one :model/TransformDagRun :id run-id))]+ (let [dag-run (api/check-404 (transforms-rest.db/dag-run run-id))](check-seed-transform api/read-check dag-run)(->> (t2/hydrate (transforms.core/transform-runs-for-dag-run run-id)[:transform :collection :transform_tag_ids])@@ -39,7 +40,7 @@(api.macros/defendpoint :post "/:run-id/cancel" :- :nil"Cancel an in-progress manual DAG run and request cancellation of its still-running transforms."[{:keys [run-id]} :- [:map [:run-id ms/PositiveInt]]]- (let [dag-run (api/check-404 (t2/select-one :model/TransformDagRun :id run-id))]+ (let [dag-run (api/check-404 (transforms-rest.db/dag-run run-id))](check-seed-transform api/write-check dag-run)(api/check-400 (transforms.core/cancel-dag-run! run-id))nil))diff --git a/src/metabase/transforms_rest/api/transform_job.clj b/src/metabase/transforms_rest/api/transform_job.cljindex 51aba42f455..f80f53fc6d1 100644--- a/src/metabase/transforms_rest/api/transform_job.clj+++ b/src/metabase/transforms_rest/api/transform_job.clj@@ -8,6 +8,7 @@[metabase.request.core :as request][metabase.transforms-base.util :as transforms-base.u][metabase.transforms-rest.api.util :as transforms-rest.api.u]+ [metabase.transforms-rest.db :as transforms-rest.db][metabase.transforms.core :as transforms.core][metabase.transforms.util :as transforms.u][metabase.util.i18n :refer [deferred-tru LocalizedString]]@@ -105,7 +106,7 @@(deferred-tru "Invalid cron expression: {0}" schedule));; Validate tag IDs exist if provided(when (seq tag_ids)- (let [existing-tags (set (t2/select-pks-vec :model/TransformTag :id [:in tag_ids]))]+ (let [existing-tags (transforms-rest.db/existing-tag-ids tag_ids)](api/check-400 (= (set tag_ids) existing-tags)(deferred-tru "Some tag IDs do not exist"))))(let [job-data {:name name@@ -113,17 +114,16 @@:schedule schedule:ui_display_type ui_display_type}_ (api/check-403 (mi/can-create? :model/TransformJob (assoc job-data :tag_ids tag_ids)))- job (t2/insert-returning-instance! :model/TransformJob- job-data)]+ job (transforms-rest.db/insert-job! job-data)](transforms.core/initialize-job! job);; Add tag associations if provided(when (seq tag_ids)- (t2/insert! :model/TransformJobTransformTag- (map-indexed (fn [idx tag-id]- {:job_id (:id job)- :tag_id tag-id- :position idx})- tag_ids)))+ (transforms-rest.db/insert-job-tags!+ (map-indexed (fn [idx tag-id]+ {:job_id (:id job)+ :tag_id tag-id+ :position idx})+ tag_ids)));; Return with hydrated tag_ids(t2/hydrate job :tag_ids)))@@ -142,7 +142,7 @@(log/info "Setting active =" active "on all transform jobs")(let [op (if active transforms.core/activate-job! transforms.core/deactivate-job!)verb (if active "activate" "deactivate")- candidates (t2/select :model/TransformJob :active (not active))+ candidates (transforms-rest.db/jobs-with-active-flag (not active))try-op (fn [job](try(op (:id job))@@ -170,7 +170,7 @@[:active {:optional true} :boolean][:tag_ids {:optional true} [:sequential ms/PositiveInt]]]](log/info "Updating transform job" job-id)- (let [existing-job (t2/hydrate (t2/select-one :model/TransformJob :id job-id) :tag_ids)]+ (let [existing-job (t2/hydrate (transforms-rest.db/job job-id) :tag_ids)];; Check write permission on both current state and final state (with new tags if provided)(api/write-check existing-job)(when (some? tag-ids)@@ -181,7 +181,7 @@(deferred-tru "Invalid cron expression: {0}" schedule)));; Validate tag IDs if provided(when (seq tag-ids)- (let [existing-tags (set (t2/select-pks-vec :model/TransformTag :id [:in tag-ids]))]+ (let [existing-tags (transforms-rest.db/existing-tag-ids tag-ids)](api/check-400 (= (set tag-ids) existing-tags)(deferred-tru "Some tag IDs do not exist"))))(let [was-active (:active existing-job)@@ -194,7 +194,7 @@:description description:schedule schedule:ui_display_type ui_display_type)]- (t2/update! :model/TransformJob job-id updates))+ (transforms-rest.db/update-job! job-id updates))(when (some? tag-ids)(transforms.core/update-job-tags! job-id tag-ids)))(when (some? active)@@ -205,7 +205,7 @@;; activate-job! only runs when :active toggled false→true.(when (and schedule was-active will-be-active)(transforms.core/update-job! job-id schedule))- (-> (t2/select-one :model/TransformJob :id job-id)+ (-> (transforms-rest.db/job job-id)(t2/hydrate :tag_ids :last_run)(update :last_run transforms-base.u/present-run)))))@@ -213,8 +213,8 @@"Delete a transform job."[{:keys [job-id]} :- [:map [:job-id ms/PositiveInt]]](log/info "Deleting transform job" job-id)- (api/write-check (t2/hydrate (t2/select-one :model/TransformJob :id job-id) :tag_ids))- (t2/delete! :model/TransformJob :id job-id)+ (api/write-check (t2/hydrate (transforms-rest.db/job job-id) :tag_ids))+ (transforms-rest.db/delete-job! job-id)(transforms.core/delete-job! job-id)api/generic-204-no-content)@@ -231,7 +231,7 @@{:keys [run_all]} :- [:map[:run_all {:default false} :boolean]]](log/info "Manual run of transform job" job-id)- (api/write-check (t2/select-one :model/TransformJob :id job-id))+ (api/write-check (transforms-rest.db/job job-id))(transforms-rest.api.u/async-run-response(deferred-tru "Job run started"):job_run_id@@ -246,7 +246,7 @@[{:keys [job-id]} :- [:map[:job-id ms/PositiveInt]]](log/info "Getting transform job" job-id)- (-> (api/read-check (t2/select-one :model/TransformJob :id job-id))+ (-> (api/read-check (transforms-rest.db/job job-id))(t2/hydrate :tag_ids :last_run)(update :last_run transforms-base.u/present-run)))@@ -261,7 +261,7 @@[{:keys [job-id]} :- [:map[:job-id ms/PositiveInt]]](log/info "Getting the transforms of transform job" job-id)- (api/check-404 (t2/select-one-pk :model/TransformJob :id job-id))+ (api/check-404 (transforms-rest.db/job-pk job-id))(-> (transforms.core/job-transforms job-id)(#(do (api/check-403 (every? mi/can-read? %)) %))(t2/hydrate :creator)@@ -278,7 +278,7 @@[:tag-ids {:optional true} [:maybe (ms/QueryVectorOf ms/IntGreaterThanOrEqualToZero)]]]](log/info "Getting all transform jobs")(api/check-data-analyst)- (let [jobs (t2/select :model/TransformJob {:order-by [[:created_at :desc]]})]+ (let [jobs (transforms-rest.db/jobs)](into [](comp (map add-next-run)(transforms-base.u/->date-field-filter-xf [:last_run :start_time] last-run-start-time)@@ -331,7 +331,7 @@[:run-id ms/PositiveInt]]_query-params](api/read-check :model/TransformJob job-id)- (api/check-404 (t2/select-one :model/TransformJobRun :id run-id :job_id job-id))+ (api/check-404 (transforms-rest.db/job-run run-id job-id))(let [runs (transforms.core/transform-runs-for-job-run run-id)](->> (t2/hydrate runs [:transform :collection :transform_tag_ids])(map transforms-base.u/present-run))))@@ -342,7 +342,7 @@[:job-id ms/PositiveInt][:run-id ms/PositiveInt]]](api/write-check :model/TransformJob job-id)- (api/check-404 (t2/select-one :model/TransformJobRun :id run-id :job_id job-id))+ (api/check-404 (transforms-rest.db/job-run run-id job-id))(api/check-400 (transforms.core/cancel-job-run! run-id))nil)diff --git a/src/metabase/transforms_rest/api/transform_tag.clj b/src/metabase/transforms_rest/api/transform_tag.cljindex b5e04bca22f..129432a5fc3 100644--- a/src/metabase/transforms_rest/api/transform_tag.clj+++ b/src/metabase/transforms_rest/api/transform_tag.clj@@ -4,6 +4,7 @@[metabase.api.macros :as api.macros][metabase.api.routes.common :refer [+auth]][metabase.models.interface :as mi]+ [metabase.transforms-rest.db :as transforms-rest.db][metabase.transforms.core :as transforms.core][metabase.util.i18n :refer [deferred-tru LocalizedString]][metabase.util.log :as log]@@ -32,7 +33,7 @@(api/check-403 (mi/can-create? :model/TransformTag {:name name}))(api/check-400 (not (transforms.core/tag-name-exists? name))(deferred-tru "A tag with the name ''{0}'' already exists." name))- (t2/insert-returning-instance! :model/TransformTag {:name name}))+ (transforms-rest.db/insert-tag! name))(api.macros/defendpoint :put "/:tag-id" :- TransformTagResponse"Update a transform tag."@@ -42,19 +43,19 @@{:keys [name]} :- [:map[:name ms/NonBlankString]]](log/info "Updating transform tag" tag-id)- (api/write-check (t2/select-one :model/TransformTag :id tag-id))+ (api/write-check (transforms-rest.db/tag tag-id))(api/check-400 (not (transforms.core/tag-name-exists-excluding? name tag-id))(deferred-tru "A tag with the name ''{0}'' already exists." name))- (t2/update! :model/TransformTag tag-id {:name name})- (t2/select-one :model/TransformTag :id tag-id))+ (transforms-rest.db/update-tag! tag-id name)+ (transforms-rest.db/tag tag-id))(api.macros/defendpoint :delete "/:tag-id" :- :nil"Delete a transform tag. Removes it from all transforms and jobs."[{:keys [tag-id]} :- [:map[:tag-id ms/PositiveInt]]](log/info "Deleting transform tag" tag-id)- (api/write-check (t2/select-one :model/TransformTag :id tag-id))- (t2/delete! :model/TransformTag :id tag-id)+ (api/write-check (transforms-rest.db/tag tag-id))+ (transforms-rest.db/delete-tag! tag-id)nil)(api.macros/defendpoint :get "/" :- [:sequential TransformTagResponse]@@ -63,7 +64,7 @@_query-params](log/info "Getting all transform tags")(api/check-data-analyst)- (t2/hydrate (t2/select :model/TransformTag {:order-by [[:name :asc]]}) :can_run))+ (t2/hydrate (transforms-rest.db/tags) :can_run))(def ^{:arglists '([request respond raise])} routes"`/api/transform-tag` routes."diff --git a/src/metabase/transforms_rest/db.clj b/src/metabase/transforms_rest/db.cljnew file mode 100644index 00000000000..e05e7bf14bc--- /dev/null+++ b/src/metabase/transforms_rest/db.clj@@ -0,0 +1,108 @@+(ns metabase.transforms-rest.db+ "Application database queries for the transforms-rest module. Every function here is a direct Toucan 2 call+ with no additional logic, so no other namespace in the module runs a query itself."+ (:require+ [toucan2.core :as t2]))++;;; ------------------------------------------------- Transforms -------------------------------------------------++(defn transforms-by-id+ "A map of id to Transform, for every Transform."+ []+ (t2/select-pk->fn identity :model/Transform))++(defn transform-run+ "The TransformRun with `run-id`, or nil."+ [run-id]+ (t2/select-one :model/TransformRun :id run-id))++(defn reset-checkpoint!+ "Clear the stored checkpoint value of the Transform with `id`."+ [id]+ (t2/update! :model/Transform id {:last_checkpoint_value nil}))++;;; ---------------------------------------------------- Tags ------------------------------------------------------++(defn existing-tag-ids+ "The subset of `tag-ids` that are ids of existing TransformTags."+ [tag-ids]+ (set (t2/select-pks-vec :model/TransformTag :id [:in tag-ids])))++(defn tag+ "The TransformTag with `tag-id`, or nil."+ [tag-id]+ (t2/select-one :model/TransformTag :id tag-id))++(defn insert-tag!+ "Insert a TransformTag named `name` and return the inserted instance."+ [name]+ (t2/insert-returning-instance! :model/TransformTag {:name name}))++(defn update-tag!+ "Set the name of the TransformTag with `tag-id`."+ [tag-id name]+ (t2/update! :model/TransformTag tag-id {:name name}))++(defn delete-tag!+ "Delete the TransformTag with `tag-id`."+ [tag-id]+ (t2/delete! :model/TransformTag :id tag-id))++(defn tags+ "Every TransformTag, in name order."+ []+ (t2/select :model/TransformTag {:order-by [[:name :asc]]}))++;;; ---------------------------------------------------- Jobs ------------------------------------------------------++(defn insert-job!+ "Insert the TransformJob `job-data` and return the inserted instance."+ [job-data]+ (t2/insert-returning-instance! :model/TransformJob job-data))++(defn insert-job-tags!+ "Insert the TransformJobTransformTag `rows`."+ [rows]+ (t2/insert! :model/TransformJobTransformTag rows))++(defn jobs-with-active-flag+ "The TransformJobs whose `:active` flag is `active`."+ [active]+ (t2/select :model/TransformJob :active active))++(defn job+ "The TransformJob with `job-id`, or nil."+ [job-id]+ (t2/select-one :model/TransformJob :id job-id))++(defn job-pk+ "The primary key of the TransformJob with `job-id`, or nil."+ [job-id]+ (t2/select-one-pk :model/TransformJob :id job-id))++(defn update-job!+ "Apply `updates` to the TransformJob with `job-id`."+ [job-id updates]+ (t2/update! :model/TransformJob job-id updates))++(defn delete-job!+ "Delete the TransformJob with `job-id`."+ [job-id]+ (t2/delete! :model/TransformJob :id job-id))++(defn jobs+ "Every TransformJob, newest first."+ []+ (t2/select :model/TransformJob {:order-by [[:created_at :desc]]}))++(defn job-run+ "The TransformJobRun with `run-id` belonging to the TransformJob with `job-id`, or nil."+ [run-id job-id]+ (t2/select-one :model/TransformJobRun :id run-id :job_id job-id))++;;; -------------------------------------------------- DAG runs -----------------------------------------------------++(defn dag-run+ "The TransformDagRun with `run-id`, or nil."+ [run-id]+ (t2/select-one :model/TransformDagRun :id run-id))diff --git a/src/metabase/typed_schemas/db.clj b/src/metabase/typed_schemas/db.cljnew file mode 100644index 00000000000..8c88db336b9--- /dev/null+++ b/src/metabase/typed_schemas/db.clj@@ -0,0 +1,102 @@+(ns metabase.typed-schemas.db+ "Application database queries for the typed schemas module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [toucan2.core :as t2]))++(defn destination-database-ids+ "The ids among `database-ids` of Databases that are routing destinations."+ [database-ids]+ (t2/select-fn-set :id :model/Database :id [:in database-ids] :router_database_id [:not= nil]))++(defn cards-ordered-by-name+ "The Cards matching the Honey SQL `where` clause, in name then id order."+ [where]+ (t2/select :model/Card {:where where, :order-by [[:name :asc] [:id :asc]]}))++(defn field-ids-and-table-ids+ "The id and Table id of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :table_id] :id [:in field-ids]))++(defn card-dimensions+ "The dimensions and dimension mappings of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :dimensions :dimension_mappings] :id card-id))++(defn table-names+ "The id, name, and display name of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :name :display_name] :id [:in table-ids]))++(defn model-actions+ "The id, model id, name, and type of the unarchived non-HTTP Actions of the model Cards with `model-ids`."+ [model-ids]+ (t2/select [:model/Action :id :model_id :name :type]+ :model_id [:in model-ids]+ :archived false+ :type [:not= "http"]))++(defn field-table-id+ "The Table id of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one-fn :table_id :model/Field :id field-id))++(defn- scope-filter-clause+ "Compiles a resolved scope into a Honey SQL where-clause conjunct: a nil scope means unscoped (no clause), an+ empty scope matches nothing."+ [scope-ids column]+ (when scope-ids+ (if (seq scope-ids)+ [:in column scope-ids]+ ;; no row has id -1: a resolved-but-empty scope matches no rows+ [:= column -1])))++(defn active-tables-in-scope+ "The active Tables among `database-ids` and/or `table-ids` (either nil for unscoped), in name then id order."+ [database-ids table-ids]+ (t2/select :model/Table+ {:where [:and [:= :active true]+ (scope-filter-clause database-ids :db_id)+ (scope-filter-clause table-ids :id)]+ :order-by [[:name :asc] [:id :asc]]}))++(defn published-library-tables-in-collections+ "The active, published Tables in `collection-ids` (nil for unscoped), in name then id order."+ [collection-ids]+ (t2/select :model/Table+ {:where [:and+ [:= :active true]+ [:= :is_published true]+ (scope-filter-clause collection-ids :collection_id)]+ :order-by [[:name :asc] [:id :asc]]}))++(defn measure-definition+ "The definition of the Measure with `measure-id`, or nil."+ [measure-id]+ (t2/select-one-fn :definition :model/Measure :id measure-id))++(defn measure-definitions+ "The id and definition of the Measures with `measure-ids`."+ [measure-ids]+ (t2/select [:model/Measure :id :definition] :id [:in measure-ids]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn databases-named+ "The Databases named `database-name`."+ [database-name]+ (t2/select :model/Database :name database-name))++(defn collections+ "The Collections with `collection-ids`."+ [collection-ids]+ (t2/select :model/Collection :id [:in collection-ids]))++(defn collections-by-entity-ids+ "The Collections with `entity-ids`."+ [entity-ids]+ (t2/select :model/Collection :entity_id [:in entity-ids]))diff --git a/src/metabase/typed_schemas/schema/common.clj b/src/metabase/typed_schemas/schema/common.cljindex 892442e575b..1fb0c4b4666 100644--- a/src/metabase/typed_schemas/schema/common.clj+++ b/src/metabase/typed_schemas/schema/common.clj@@ -7,7 +7,7 @@[metabase.lib.core :as lib][metabase.metabot.core :as metabot][metabase.models.interface :as mi]- [toucan2.core :as t2]))+ [metabase.typed-schemas.db :as typed-schemas.db]))(set! *warn-on-reflection* true)@@ -36,7 +36,7 @@`metabase.metabot.tools.resources/check-resource-database`)."[db-ids](when (seq db-ids)- (t2/select-fn-set :id :model/Database :id [:in db-ids] :router_database_id [:not= nil])))+ (typed-schemas.db/destination-database-ids db-ids)))(defn select-schema-cards"Returns readable, non-archived cards for schema generation.@@ -45,14 +45,13 @@the same visibility, archived, database and collection filters, and exclude cards backed by adestination (routed) database -- see [[destination-db-ids]]."[card-type database-ids collection-ids]- (let [cards (->> (t2/select :model/Card- {:where (cond-> [:and- [:= :type (name card-type)]- [:= :archived false]- (collection/visible-collection-filter-clause :collection_id)]- database-ids (conj (scope-filter-clause database-ids :database_id))- collection-ids (conj (scope-filter-clause collection-ids :collection_id)))- :order-by [[:name :asc] [:id :asc]]})+ (let [cards (->> (typed-schemas.db/cards-ordered-by-name+ (cond-> [:and+ [:= :type (name card-type)]+ [:= :archived false]+ (collection/visible-collection-filter-clause :collection_id)]+ database-ids (conj (scope-filter-clause database-ids :database_id))+ collection-ids (conj (scope-filter-clause collection-ids :collection_id))))(filter mi/can-read?))destination-ids (destination-db-ids (into #{} (keep :database_id) cards))](if (seq destination-ids)diff --git a/src/metabase/typed_schemas/schema/metric.clj b/src/metabase/typed_schemas/schema/metric.cljindex ddc4b7c3335..14579a2da38 100644--- a/src/metabase/typed_schemas/schema/metric.clj+++ b/src/metabase/typed_schemas/schema/metric.clj@@ -7,10 +7,10 @@[metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.typed-schemas.common :as common]+ [metabase.typed-schemas.db :as typed-schemas.db][metabase.typed-schemas.schema.common :as schema.common][metabase.typed-schemas.schema.table :as schema.table]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(set! *warn-on-reflection* true)@@ -89,7 +89,7 @@(when (seq field-ids)(into {}(map (juxt :id :table_id))- (t2/select [:model/Field :id :table_id] :id [:in field-ids])))))+ (typed-schemas.db/field-ids-and-table-ids field-ids)))))(defn- dimension-schema"Returns the schema for a metric dimension."@@ -144,7 +144,7 @@"Syncs and returns persisted metric dimensions with mapping metadata."[{:keys [id]}](metrics/sync-dimensions! :metadata/metric id)- (let [{:keys [dimensions dimension_mappings]} (t2/select-one [:model/Card :dimensions :dimension_mappings] :id id)]+ (let [{:keys [dimensions dimension_mappings]} (typed-schemas.db/card-dimensions id)](enrich-dimensions-with-mappings dimensions dimension_mappings)))(defn- readable-table-source-rows@@ -152,7 +152,7 @@[table-ids](when (seq table-ids)(perms/prime-table-perms-cache {:table-ids (set table-ids)})- (->> (t2/select [:model/Table :id :name :display_name] :id [:in table-ids])+ (->> (typed-schemas.db/table-names table-ids)(filter mi/can-read?))))(defn- table-key-disambiguatorsdiff --git a/src/metabase/typed_schemas/schema/model.clj b/src/metabase/typed_schemas/schema/model.cljindex 1e850fc6af0..5444ee5b3c1 100644--- a/src/metabase/typed_schemas/schema/model.clj+++ b/src/metabase/typed_schemas/schema/model.clj@@ -6,9 +6,9 @@[metabase.actions.core :as actions][metabase.lib.schema.common :as lib.schema.common][metabase.typed-schemas.common :as common]+ [metabase.typed-schemas.db :as typed-schemas.db][metabase.typed-schemas.schema.common :as schema.common]- [metabase.util :as u]- [toucan2.core :as t2]))+ [metabase.util :as u]))(set! *warn-on-reflection* true)@@ -46,10 +46,7 @@(defn- action-rows"Returns raw rows so we can detect actions that cannot be resolved to action details."[model-ids]- (t2/select [:model/Action :id :model_id :name :type]- :model_id [:in model-ids]- :archived false- :type [:not= "http"]))+ (typed-schemas.db/model-actions model-ids))(defn- unresolved-action-rows"Returns action rows missing from resolved action details."@@ -203,11 +200,7 @@[models](let [model-ids (set (map :id models))](try- (actions/select-actions- models- :model_id [:in model-ids]- :archived false- :type [:not= "http"])+ (actions/select-actions-non-http-for-models models model-ids)(catch Exception exception(throw (ex-info (format "Failed to build action schemas for selected models: %s" (ex-message exception))(error-data-with-cause-messagediff --git a/src/metabase/typed_schemas/schema/table.clj b/src/metabase/typed_schemas/schema/table.cljindex a945396e2d2..579960b7aac 100644--- a/src/metabase/typed_schemas/schema/table.clj+++ b/src/metabase/typed_schemas/schema/table.clj@@ -7,8 +7,8 @@[metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.typed-schemas.common :as common]- [metabase.typed-schemas.schema.common :as schema.common]- [toucan2.core :as t2]))+ [metabase.typed-schemas.db :as typed-schemas.db]+ [metabase.typed-schemas.schema.common :as schema.common]))(set! *warn-on-reflection* true)@@ -16,7 +16,7 @@"Returns the table for a given field id."[field-id](when (integer? field-id)- (t2/select-one-fn :table_id :model/Field :id field-id)))+ (typed-schemas.db/field-table-id field-id)))(defn field-schema"Returns the schema for a table field."@@ -55,22 +55,13 @@Library and database endpoint paths both need the same active/readable tablerules; only their id filters differ."[database-ids table-ids]- (->> (t2/select :model/Table- {:where (cond-> [:and [:= :active true]]- database-ids (conj (schema.common/scope-filter-clause database-ids :db_id))- table-ids (conj (schema.common/scope-filter-clause table-ids :id)))- :order-by [[:name :asc] [:id :asc]]})+ (->> (typed-schemas.db/active-tables-in-scope database-ids table-ids)(filter-readable-tables)))(defn select-library-tables"Returns published tables from the library based on the given scope."[{:keys [data-collection-ids]}]- (->> (t2/select :model/Table- {:where [:and- [:= :active true]- [:= :is_published true]- (schema.common/scope-filter-clause data-collection-ids :collection_id)]- :order-by [[:name :asc] [:id :asc]]})+ (->> (typed-schemas.db/published-library-tables-in-collections data-collection-ids)(filter-readable-tables)))(defn segment-schema@@ -100,7 +91,7 @@measure remains usable with a fallback column."[database-id measure-id](try- (when-let [definition (t2/select-one-fn :definition :model/Measure :id measure-id)]+ (when-let [definition (typed-schemas.db/measure-definition measure-id)](schema.common/aggregation-result-column database-id definition))(catch Exception _nil)))@@ -112,7 +103,7 @@(when (seq measure-ids)(let [definition-by-measure-id (into {}(map (juxt :id :definition))- (t2/select [:model/Measure :id :definition] :id [:in measure-ids]))]+ (typed-schemas.db/measure-definitions measure-ids))](try(let [metadata-provider (lib-be/application-database-metadata-provider database-id)](into {}diff --git a/src/metabase/typed_schemas/scope.clj b/src/metabase/typed_schemas/scope.cljindex 54a4ef52115..4269b6bfead 100644--- a/src/metabase/typed_schemas/scope.clj+++ b/src/metabase/typed_schemas/scope.clj@@ -28,8 +28,8 @@[clojure.string :as str][metabase.collections.models.collection :as collection][metabase.models.interface :as mi]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.typed-schemas.db :as typed-schemas.db]+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -51,11 +51,11 @@(when database-ref(let [{:keys [id name]} database-ref](if id- (let [database (t2/select-one :model/Database :id id)]+ (let [database (typed-schemas.db/database id)](if (and database (mi/can-read? database))#{id}#{}))- (->> (t2/select :model/Database :name name)+ (->> (typed-schemas.db/databases-named name)(filter mi/can-read?)(map :id)set)))))@@ -83,12 +83,12 @@(mi/can-read? collection)))by-id (when (seq ids)(into {} (map (juxt :id identity))- (t2/select :model/Collection :id [:in ids])))+ (typed-schemas.db/collections ids)));; entity_id is a fixed-width char column; some app dbs return it;; space-padded, so key the lookup by the trimmed value.by-eid (when (seq entity-ids)(into {} (map (juxt (comp str/trimr :entity_id) identity))- (t2/select :model/Collection :entity_id [:in entity-ids])))+ (typed-schemas.db/collections-by-entity-ids entity-ids)))resolved (for [{:keys [id entity-id] :as collection-ref} collection-refs][collection-ref(let [collection (if id (get by-id id) (get by-eid entity-id))]diff --git a/src/metabase/upload/db.clj b/src/metabase/upload/db.cljindex db2638ab00e..4f3ecf1f41f 100644--- a/src/metabase/upload/db.clj+++ b/src/metabase/upload/db.clj@@ -1,8 +1,112 @@(ns metabase.upload.db+ "Application database queries for the upload module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."(:require+ [metabase.models.humanization :as humanization][toucan2.core :as t2]))(defn current-database- "The database being used for uploads."+ "The Database being used for uploads, or nil."[](t2/select-one :model/Database :uploads_enabled true))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn database-is-attached-dwh?+ "Whether the Database with `database-id` is an attached data warehouse."+ [database-id]+ (t2/select-one-fn :is_attached_dwh :model/Database database-id))++(defn disable-uploads-for-all-databases!+ "Disable uploads on every Database that has them enabled."+ []+ (t2/update! :model/Database :uploads_enabled true {:uploads_enabled false+ :uploads_schema_name nil+ :uploads_table_prefix nil}))++(defn enable-uploads-for-database!+ "Enable uploads on the Database with `database-id` into `schema-name` with `table-prefix`."+ [database-id schema-name table-prefix]+ (t2/update! :model/Database database-id {:uploads_enabled true+ :uploads_schema_name schema-name+ :uploads_table_prefix table-prefix}))++(defn active-fields-for-table+ "The active Fields of the Table with `table-id`."+ [table-id]+ (t2/select :model/Field :table_id table-id :active true))++(defn set-field-display-names!+ "Set the display name of each Field of the Table with `table-id` whose lower-cased name is a key of+ `name->display-name` to the corresponding value, unless its current display name no longer matches the+ automatic humanization of its name (i.e. it was manually edited, in which case it is left alone)."+ [table-id name->display-name]+ ;; A raw update rather than `t2/update!`, which produces an invalid query for certain versions of PostgreSQL:+ ;; SELECT * FROM "metabase_field" WHERE "id" AND ("table_id" = ?) AND ... (argument of AND must be type boolean).+ (t2/query {:update (t2/table-name :model/Field)+ :set {:display_name (into [:case]+ (mapcat identity)+ (for [[n display-name] name->display-name]+ [[:= [:lower :name] n]+ [:case+ ;; Only update the display name if it still matches the automatic humanization.+ [:= :display_name (humanization/name->human-readable-name n)] display-name+ ;; Otherwise, it could have been set manually, so leave it as is.+ true :display_name]]))}+ :where [:and+ [:= :table_id table-id]+ [:in [:lower :name] (keys name->display-name)]]}))++(defn mark-table-upload!+ "Flag the Table with `table-id` as an authoritative, writable upload table."+ [table-id]+ (t2/update! :model/Table table-id {:is_upload true+ :data_authority :authoritative+ :data_source :upload+ :is_writable true}))++(defn set-field-display-name!+ "Set the display name of the Field with `field-id`."+ [field-id display-name]+ (t2/update! :model/Field field-id {:display_name display-name}))++(defn unarchived-models-for-table+ "The id, query, and schema of the unarchived model Cards of the Table with `table-id`."+ [table-id]+ (t2/select [:model/Card :id :dataset_query :card_schema]+ :table_id table-id+ :type :model+ :archived false))++(defn card-query-and-metadata+ "The query, result metadata, and schema of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one [:model/Card :dataset_query :result_metadata :card_schema] card-id))++(defn set-card-result-metadata!+ "Set the result metadata of the Card with `card-id`."+ [card-id result-metadata]+ (t2/update! :model/Card card-id {:result_metadata result-metadata}))++(defn deactivate-table!+ "Mark the Table with `table-id` inactive."+ [table-id]+ (t2/update! :model/Table :id table-id {:active false}))++(defn archive-cards-for-table!+ "Archive the unarchived Cards of the Table with `table-id`, returning their ids."+ [table-id]+ (t2/update-returning-pks! :model/Card {:table_id table-id :archived false} {:archived true}))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))diff --git a/src/metabase/upload/impl.clj b/src/metabase/upload/impl.cljindex a88b00b4e25..37a1f545f78 100644--- a/src/metabase/upload/impl.clj+++ b/src/metabase/upload/impl.clj@@ -24,6 +24,7 @@[metabase.permissions.core :as perms][metabase.queries.core :as queries][metabase.sync.core :as sync]+ [metabase.upload.db :as upload.db][metabase.upload.parsing :as upload-parsing][metabase.upload.settings :as upload.settings][metabase.upload.types :as upload-types]@@ -123,7 +124,7 @@(defn- table-id->auto-pk-column [driver table-id](first (filter (fn [field](= (normalize-column-name driver (:name field)) auto-pk-column-name))- (t2/select :model/Field :table_id table-id :active true))))+ (upload.db/active-fields-for-table table-id))))(defn- detect-schema"Consumes the header and rows from a CSV file.@@ -459,25 +460,8 @@(defn- set-display-names![table-id field->display-name]- (let [field->display-name (update-keys field->display-name (comp u/lower-case-en name))- case-statement (into [:case]- (mapcat identity)- (for [[n display-name] field->display-name]- [[:= [:lower :name] n]- [:case- ;; Only update the display name if it still matches the automatic humanization.- [:= :display_name (humanization/name->human-readable-name n)] display-name- ;; Otherwise, it could have been set manually, so leave it as is.- true :display_name]]))]- ;; Using t2/update! results in an invalid query for certain versions of PostgreSQL- ;; SELECT * FROM \"metabase_field\" WHERE \"id\" AND (\"table_id\" = ?) AND ...- ;; ^^^^^- ;; ERROR: argument of AND must be type boolean, not type integer- (t2/query {:update (t2/table-name :model/Field)- :set {:display_name case-statement}- :where [:and- [:= :table_id table-id]- [:in [:lower :name] (keys field->display-name)]]})))+ (let [field->display-name (update-keys field->display-name (comp u/lower-case-en name))]+ (upload.db/set-field-display-names! table-id field->display-name)))(defn- uploads-enabled? [](some? (:db_id (upload.settings/uploads-settings))))@@ -570,17 +554,14 @@table (sync/create-table! db {:name table-name:schema (not-empty schema):display_name display-name})- _set_is_upload (t2/update! :model/Table (:id table) {:is_upload true- :data_authority :authoritative- :data_source :upload- :is_writable true})+ _set_is_upload (upload.db/mark-table-upload! (:id table))_sync (scan-and-sync-table! db table)_set_names (set-display-names! (:id table) columns);; Set the display_name of the auto-generated primary key column to the same as its name, so that if users;; download results from the table as a CSV and reupload, we'll recognize it as the same column_ (when (auto-pk-column? driver db)(let [auto-pk-field (table-id->auto-pk-column driver (:id table))]- (t2/update! :model/Field (:id auto-pk-field) {:display_name (:name auto-pk-field)})))]+ (upload.db/set-field-display-name! (:id auto-pk-field) (:name auto-pk-field))))]{:table table:stats stats})))@@ -628,7 +609,7 @@[:db-id ms/PositiveInt][:schema-name {:optional true} [:maybe :string]][:table-prefix {:optional true} [:maybe :string]]]]- (let [database (or (t2/select-one :model/Database :id db-id)+ (let [database (or (upload.db/database db-id)(throw (ex-info (tru "The uploads database does not exist."){:status-code 422})))](check-can-create-upload database schema-name)@@ -783,23 +764,20 @@"Invalidate the model cache and result metadata for all models where `:based_on_upload` resolves to the given table."[table];; NOTE: It is important that this logic is kept in sync with `model-hydrate-based-on-upload`- (when-let [model-ids (->> (t2/select [:model/Card :id :dataset_query :card_schema]- :table_id (:id table)- :type :model- :archived false)+ (when-let [model-ids (->> (upload.db/unarchived-models-for-table (:id table))(filter (comp #{(:id table)} only-table-id))(map :id)seq)];; Ideally we would do all the filtering in the query, but this would not allow us to leverage Lib.- (model-persistence/invalidate! {:card_id [:in model-ids]})+ (model-persistence/invalidate! model-ids);; Also refresh the metadata, so that newly added columns are visible, and types are updated.(doseq [id model-ids]- (let [card (t2/select-one [:model/Card :dataset_query :result_metadata :card_schema] id)+ (let [card (upload.db/card-query-and-metadata id);; Unclear why this is required, would expect it to get this from the field's display name, as it does for;; the initial upload.fix-name #(update % :display_name humanization/name->human-readable-name)metadata (queries/refresh-metadata card {:update-fn fix-name})]- (t2/update! :model/Card id {:result_metadata metadata})))))+ (upload.db/set-card-result-metadata! id metadata)))))(defn- translate-type-keywords [m](walk/postwalk@@ -820,7 +798,7 @@[header & rows] (cond-> (parse reader)auto-pk?without-auto-pk-columns)- name->field (m/index-by :name (t2/select :model/Field :table_id (:id table) :active true))+ name->field (m/index-by :name (upload.db/active-fields-for-table (:id table)));; Match colliding columns to existing fields by display name so reordering them between;; uploads doesn't write data to the wrong column. See [[match-column-names]] (GDGT-2233).column-names (match-column-names driver header name->field)@@ -871,7 +849,7 @@(set-display-names! (:id table) (zipmap column-names display-names))(when create-auto-pk?(let [auto-pk-field (table-id->auto-pk-column driver (:id table))]- (t2/update! :model/Field (:id auto-pk-field) {:display_name (:name auto-pk-field)})))+ (upload.db/set-field-display-name! (:id auto-pk-field) (:name auto-pk-field))))(invalidate-cached-models! table)(events/publish-event! (if replace-rows?:event/upload-replace@@ -956,7 +934,7 @@(driver.conn/with-write-connection(driver/drop-table! driver (:id database) table-name));; We mark the table as inactive synchronously, so that it will no longer shows up in the admin list.- (t2/update! :model/Table :id (:id table) {:active false})+ (upload.db/deactivate-table! (:id table));; Ideally we would immediately trigger any further clean-up associated with the table being deactivated, but at;; the time of writing this sync isn't wired up to do anything with explicitly inactive tables, and rather;; relies on their absence from the tables being described during the database sync itself.@@ -970,9 +948,7 @@;; 2. A MBQL question or model that depends on such a model as their first or only data source.;; Note that this does not include cases where we join to this table, or even native queries which depend .(when archive-cards?- (t2/update-returning-pks! :model/Card- {:table_id (:id table) :archived false}- {:archived true}))+ (upload.db/archive-cards-for-table! (:id table))):done))(def update-action-schema@@ -989,7 +965,7 @@[:filename :string][:file (ms/InstanceOfClass File)][:action update-action-schema]]]- (let [table (api/check-404 (t2/select-one :model/Table :id table-id))+ (let [table (api/check-404 (upload.db/table table-id))database (table/database table)replace? (= :metabase.upload/replace action)](check-can-update database table)@@ -1004,7 +980,7 @@"Returns the subset of table ids where the user can upload to the table."[table-ids](set (when (seq table-ids)- (->> (t2/hydrate (t2/select :model/Table :id [:in table-ids]) :db)+ (->> (t2/hydrate (upload.db/tables table-ids) :db)(filter #(can-upload-to-table? (:db %) %))(map :id)))))diff --git a/src/metabase/upload/settings.clj b/src/metabase/upload/settings.cljindex f3e7804c77e..5ca2efc0dc9 100644--- a/src/metabase/upload/settings.clj+++ b/src/metabase/upload/settings.clj@@ -3,9 +3,9 @@[metabase.api.common :as api][metabase.models.interface :as mi][metabase.settings.core :refer [defsetting]]+ [metabase.upload.db :as upload.db][metabase.util.i18n :refer [deferred-tru]]- [metabase.util.log :as log]- [toucan2.core :as t2]))+ [metabase.util.log :as log]))(defn- not-handling-api-request?[]@@ -16,7 +16,7 @@[db-id](or (not-handling-api-request?)(mi/can-write? :model/Database db-id)- (t2/select-one-fn :is_attached_dwh :model/Database db-id)+ (upload.db/database-is-attached-dwh? db-id)(api/throw-403)))(defsetting uploads-settings@@ -27,20 +27,16 @@:type :json:audit :getter:getter (fn []- (let [db (t2/select-one :model/Database :uploads_enabled true)]+ (let [db (upload.db/current-database)]{:db_id (:id db):schema_name (:uploads_schema_name db):table_prefix (:uploads_table_prefix db)})):setter (fn [{:keys [db_id schema_name table_prefix]}](if (nil? db_id)- (t2/update! :model/Database :uploads_enabled true {:uploads_enabled false- :uploads_schema_name nil- :uploads_table_prefix nil})+ (upload.db/disable-uploads-for-all-databases!)(do(check-required-perms! db_id)- (t2/update! :model/Database db_id {:uploads_enabled true- :uploads_schema_name schema_name- :uploads_table_prefix table_prefix})))))+ (upload.db/enable-uploads-for-database! db_id schema_name table_prefix)))));;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Deprecated uploads settings begindiff --git a/src/metabase/usage_metadata/batch.clj b/src/metabase/usage_metadata/batch.cljindex 8863db4f088..08bfc405b3e 100644--- a/src/metabase/usage_metadata/batch.clj+++ b/src/metabase/usage_metadata/batch.clj@@ -3,6 +3,7 @@[java-time.api :as t][metabase.app-db.core :as mdb][metabase.lib-be.core :as lib-be]+ [metabase.usage-metadata.db :as usage-metadata.db][metabase.usage-metadata.extract :as usage-metadata.extract][metabase.usage-metadata.models.source-dimension-daily][metabase.usage-metadata.models.source-dimension-profile-daily]@@ -13,7 +14,6 @@[metabase.usage-metadata.store :as usage-metadata.store][metabase.util.json :as json][metabase.util.log :as log]- [toucan2.core :as t2][toucan2.realize :as t2.realize])(:import(java.nio ByteBuffer)@@ -24,12 +24,12 @@(def ^:private utc-zone-offset(t/zone-offset "Z"))-(def ^:private rollup-models- [:model/SourceSegmentDaily- :model/SourceSegmentCompositeDaily- :model/SourceMetricDaily- :model/SourceDimensionDaily- :model/SourceDimensionProfileDaily])+(def ^:private delete-rollups-before-fns+ [usage-metadata.db/delete-segment-rollups-before!+ usage-metadata.db/delete-segment-composite-rollups-before!+ usage-metadata.db/delete-metric-rollups-before!+ usage-metadata.db/delete-dimension-rollups-before!+ usage-metadata.db/delete-dimension-profile-rollups-before!])(def ^:private low-cardinality-threshold30)@@ -90,11 +90,7 @@Identical hashes produce identical facts, so collapse at the DB and iterateunique hashes. Per-execution totals come from multiplying by `:n`."[bucket-date]- (t2/select [:model/QueryExecution :hash [:%count.* :n]]- {:where [:and- [:>= :started_at (utc-day-start bucket-date)]- [:< :started_at (utc-day-end bucket-date)]]- :group-by [:hash]}))+ (usage-metadata.db/query-execution-hash-counts (utc-day-start bucket-date) (utc-day-end bucket-date)))(defn- add-skip [stats reason n](update-in stats [:skipped-rows reason] (fnil + 0) n))@@ -217,7 +213,7 @@(defn- field-fingerprint[field-id]- (some-> (t2/select-one-fn :fingerprint :metabase_field :id field-id)+ (some-> (usage-metadata.db/raw-field-fingerprint field-id)decode-fingerprint))(defn- profile-rows-for-dimensions@@ -285,8 +281,7 @@stats(mdb/streaming-reducible(fn [conn]- (t2/reducible-select :conn conn [:model/Query :query_hash :query]- :query_hash [:in hash-chunk])))))+ (usage-metadata.db/queries-reducible conn hash-chunk)))))initial-stats(partition-all hash-chunk-size raw-hashes))seen-hashes (:seen-hashes after-stream)@@ -325,8 +320,8 @@[retention-days today](let [retention-days (max 1 (or retention-days 1))cutoff-day (t/minus today (t/days retention-days))]- (doseq [model rollup-models]- (t2/delete! model :bucket_date [:< cutoff-day]))+ (doseq [delete-before! delete-rollups-before-fns]+ (delete-before! cutoff-day))cutoff-day))(defn run-batch!diff --git a/src/metabase/usage_metadata/db.clj b/src/metabase/usage_metadata/db.cljnew file mode 100644index 00000000000..0c97025d6ba--- /dev/null+++ b/src/metabase/usage_metadata/db.clj@@ -0,0 +1,220 @@+(ns metabase.usage-metadata.db+ "Application database queries for the usage metadata module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn query-execution-hash-counts+ "The `:hash` and execution count `:n` of the QueryExecutions started at or after `started-at` and before+ `started-before`, grouped by hash."+ [started-at started-before]+ (t2/select [:model/QueryExecution :hash [:%count.* :n]]+ {:where [:and+ [:>= :started_at started-at]+ [:< :started_at started-before]]+ :group-by [:hash]}))++(defn raw-field-fingerprint+ "The stored fingerprint of the Field with `field-id`, as it sits in the table, or nil."+ [field-id]+ (t2/select-one-fn :fingerprint :metabase_field :id field-id))++(defn queries-reducible+ "A reducible over `conn` of the hash and query of the Queries with `query-hashes`."+ [conn query-hashes]+ (t2/reducible-select :conn conn [:model/Query :query_hash :query] :query_hash [:in query-hashes]))++(defn delete-segment-rollups-before!+ "Delete the SourceSegmentDaily rollup rows bucketed before `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceSegmentDaily :bucket_date [:< bucket-date]))++(defn delete-segment-rollups-for-day!+ "Delete the SourceSegmentDaily rollup rows bucketed on `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceSegmentDaily :bucket_date bucket-date))++(defn insert-segment-rollups!+ "Insert `rows` into SourceSegmentDaily."+ [rows]+ (t2/insert! :model/SourceSegmentDaily rows))++(defn delete-segment-composite-rollups-before!+ "Delete the SourceSegmentCompositeDaily rollup rows bucketed before `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceSegmentCompositeDaily :bucket_date [:< bucket-date]))++(defn delete-segment-composite-rollups-for-day!+ "Delete the SourceSegmentCompositeDaily rollup rows bucketed on `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceSegmentCompositeDaily :bucket_date bucket-date))++(defn insert-segment-composite-rollups!+ "Insert `rows` into SourceSegmentCompositeDaily."+ [rows]+ (t2/insert! :model/SourceSegmentCompositeDaily rows))++(defn delete-metric-rollups-before!+ "Delete the SourceMetricDaily rollup rows bucketed before `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceMetricDaily :bucket_date [:< bucket-date]))++(defn delete-metric-rollups-for-day!+ "Delete the SourceMetricDaily rollup rows bucketed on `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceMetricDaily :bucket_date bucket-date))++(defn insert-metric-rollups!+ "Insert `rows` into SourceMetricDaily."+ [rows]+ (t2/insert! :model/SourceMetricDaily rows))++(defn delete-dimension-rollups-before!+ "Delete the SourceDimensionDaily rollup rows bucketed before `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceDimensionDaily :bucket_date [:< bucket-date]))++(defn delete-dimension-rollups-for-day!+ "Delete the SourceDimensionDaily rollup rows bucketed on `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceDimensionDaily :bucket_date bucket-date))++(defn insert-dimension-rollups!+ "Insert `rows` into SourceDimensionDaily."+ [rows]+ (t2/insert! :model/SourceDimensionDaily rows))++(defn delete-dimension-profile-rollups-before!+ "Delete the SourceDimensionProfileDaily rollup rows bucketed before `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceDimensionProfileDaily :bucket_date [:< bucket-date]))++(defn delete-dimension-profile-rollups-for-day!+ "Delete the SourceDimensionProfileDaily rollup rows bucketed on `bucket-date`."+ [bucket-date]+ (t2/delete! :model/SourceDimensionProfileDaily :bucket_date bucket-date))++(defn insert-dimension-profile-rollups!+ "Insert `rows` into SourceDimensionProfileDaily."+ [rows]+ (t2/insert! :model/SourceDimensionProfileDaily rows))++(defn field-names+ "The id, name, and display name of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :name :display_name] :id [:in field-ids]))++(defn table-names+ "The id, name, display name, Database id, and schema of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :name :display_name :db_id :schema] :id [:in table-ids]))++(defn table-database-ids+ "The id and Database id of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Table :id :db_id] :id [:in table-ids]))++(defn card-names+ "The id and name of the Cards with `card-ids`."+ [card-ids]+ (t2/select [:model/Card :id :name] :id [:in card-ids]))++(defn- grouped-rollup-where+ [source-type source-id bucket-start bucket-end]+ (cond-> [:and [:in :ownership_mode ["direct" "projected"]]]+ source-type (conj [:= :source_type (name source-type)])+ source-id (conj [:= :source_id source-id])+ bucket-start (conj [:>= :bucket_date bucket-start])+ bucket-end (conj [:<= :bucket_date bucket-end])))++(defn grouped-segment-rows+ "The summed `source_segment_daily` counts optionally narrowed to `source-type`, `source-id`, and bucketed between+ `bucket-start` and `bucket-end`, grouped by source, field, and predicate, largest first."+ [source-type source-id bucket-start bucket-end]+ (t2/select [:model/SourceSegmentDaily+ :source_type+ :source_id+ :field_id+ :predicate+ [[:sum :count] :total_count]]+ {:where (grouped-rollup-where source-type source-id bucket-start bucket-end)+ :group-by [:source_type :source_id :field_id :predicate]+ :order-by [[:total_count :desc]]}))++(defn grouped-metric-rows+ "The summed `source_metric_daily` counts optionally narrowed to `source-type`, `source-id`, and bucketed between+ `bucket-start` and `bucket-end`, grouped by source and aggregation, largest first."+ [source-type source-id bucket-start bucket-end]+ (t2/select [:model/SourceMetricDaily+ :source_type+ :source_id+ :agg_type+ :agg_field_id+ :temporal_field_id+ :temporal_unit+ [[:sum :count] :total_count]]+ {:where (grouped-rollup-where source-type source-id bucket-start bucket-end)+ :group-by [:source_type :source_id :agg_type :agg_field_id :temporal_field_id :temporal_unit]+ :order-by [[:total_count :desc]]}))++(defn grouped-dimension-rows+ "The summed `source_dimension_daily` counts optionally narrowed to `source-type`, `source-id`, and bucketed+ between `bucket-start` and `bucket-end`, grouped by source, field, unit, and binning, largest first."+ [source-type source-id bucket-start bucket-end]+ (t2/select [:model/SourceDimensionDaily+ :source_type+ :source_id+ :field_id+ :temporal_unit+ :binning+ [[:sum :count] :total_count]]+ {:where (grouped-rollup-where source-type source-id bucket-start bucket-end)+ :group-by [:source_type :source_id :field_id :temporal_unit :binning]+ :order-by [[:total_count :desc]]}))++(defn grouped-composite-rows+ "The summed `source_segment_composite_daily` counts optionally narrowed to `source-type`, `source-id`, and+ bucketed between `bucket-start` and `bucket-end`, grouped by source and clause, largest first."+ [source-type source-id bucket-start bucket-end]+ (t2/select [:model/SourceSegmentCompositeDaily+ :source_type+ :source_id+ :clause+ :atom_fingerprints+ :atom_count+ [[:sum :count] :total_count]]+ {:where (grouped-rollup-where source-type source-id bucket-start bucket-end)+ :group-by [:source_type :source_id :clause :atom_fingerprints :atom_count]+ :order-by [[:total_count :desc]]}))++(defn grouped-profile-rows+ "The summed `source_dimension_profile_daily` counts optionally narrowed to `source-type`, `source-id`, and+ bucketed between `bucket-start` and `bucket-end`, grouped by source, field, and observation, largest first."+ [source-type source-id bucket-start bucket-end]+ (t2/select [:model/SourceDimensionProfileDaily+ :source_type+ :source_id+ :field_id+ :source_basis+ :observation_type+ :observation_value+ [[:sum :count] :total_count]]+ {:where (cond-> [:and]+ source-type (conj [:= :source_type (name source-type)])+ source-id (conj [:= :source_id source-id])+ bucket-start (conj [:>= :bucket_date bucket-start])+ bucket-end (conj [:<= :bucket_date bucket-end]))+ :group-by [:source_type :source_id :field_id :source_basis :observation_type :observation_value]+ :order-by [[:total_count :desc]]}))++(defn unarchived-segments+ "The id, Table id, and definition of the unarchived Segments, optionally narrowed to `table-id`."+ [table-id]+ (t2/select [:model/Segment :id :table_id :definition]+ {:where (cond-> [:and [:= :archived false]]+ table-id (conj [:= :table_id table-id]))}))++(defn unarchived-metric-cards+ "The id, Database id, query, and schema of the unarchived metric Cards."+ []+ (t2/select [:model/Card :id :database_id :dataset_query :card_schema] :type "metric" :archived false))diff --git a/src/metabase/usage_metadata/insights.clj b/src/metabase/usage_metadata/insights.cljindex 04f3cc85b5e..a8cde5f7e9c 100644--- a/src/metabase/usage_metadata/insights.clj+++ b/src/metabase/usage_metadata/insights.clj@@ -4,6 +4,7 @@[clojure.core.memoize :as memoize][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]+ [metabase.usage-metadata.db :as usage-metadata.db][metabase.usage-metadata.extract :as usage-metadata.extract][metabase.usage-metadata.models.source-dimension-daily][metabase.usage-metadata.models.source-dimension-profile-daily]@@ -13,8 +14,7 @@[metabase.usage-metadata.schema :as usage-metadata.schema][metabase.util.json :as json][metabase.util.log :as log]- [metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.util.malli :as mu]))(set! *warn-on-reflection* true)@@ -39,7 +39,7 @@[field-ids](let [field-ids (into #{} (filter pos-int?) field-ids)rows (when (seq field-ids)- (t2/select [:model/Field :id :name :display_name] :id [:in field-ids]))]+ (usage-metadata.db/field-names field-ids))](into {}(map (fn [{:keys [id name display_name]}][id {:id id@@ -55,10 +55,9 @@table-ids (into #{} (comp (keep second) (filter pos-int?)) (get by-type :table))card-ids (into #{} (comp (keep second) (filter pos-int?)) (get by-type :card))tables (when (seq table-ids)- (t2/select [:model/Table :id :name :display_name :db_id :schema]- :id [:in table-ids]))+ (usage-metadata.db/table-names table-ids))cards (when (seq card-ids)- (t2/select [:model/Card :id :name] :id [:in card-ids]))]+ (usage-metadata.db/card-names card-ids))](into {}cat[(map (fn [{:keys [id name display_name db_id schema]}]@@ -90,62 +89,17 @@(defn- grouped-segment-rows"Group + sum `source_segment_daily` counts for a source filter."[{:keys [source-type source-id bucket-start bucket-end]}]- (let [where (cond-> [:and- [:in :ownership_mode ["direct" "projected"]]]- source-type (conj [:= :source_type (name source-type)])- source-id (conj [:= :source_id source-id])- bucket-start (conj [:>= :bucket_date bucket-start])- bucket-end (conj [:<= :bucket_date bucket-end]))]- (t2/select [:model/SourceSegmentDaily- :source_type- :source_id- :field_id- :predicate- [[:sum :count] :total_count]]- {:where where- :group-by [:source_type :source_id :field_id :predicate]- :order-by [[:total_count :desc]]})))+ (usage-metadata.db/grouped-segment-rows source-type source-id bucket-start bucket-end))(defn- grouped-metric-rows"Group + sum `source_metric_daily` counts for a source filter."[{:keys [source-type source-id bucket-start bucket-end]}]- (let [where (cond-> [:and- [:in :ownership_mode ["direct" "projected"]]]- source-type (conj [:= :source_type (name source-type)])- source-id (conj [:= :source_id source-id])- bucket-start (conj [:>= :bucket_date bucket-start])- bucket-end (conj [:<= :bucket_date bucket-end]))]- (t2/select [:model/SourceMetricDaily- :source_type- :source_id- :agg_type- :agg_field_id- :temporal_field_id- :temporal_unit- [[:sum :count] :total_count]]- {:where where- :group-by [:source_type :source_id :agg_type :agg_field_id :temporal_field_id :temporal_unit]- :order-by [[:total_count :desc]]})))+ (usage-metadata.db/grouped-metric-rows source-type source-id bucket-start bucket-end))(defn- grouped-dimension-rows"Group + sum `source_dimension_daily` counts for a source filter."[{:keys [source-type source-id bucket-start bucket-end]}]- (let [where (cond-> [:and- [:in :ownership_mode ["direct" "projected"]]]- source-type (conj [:= :source_type (name source-type)])- source-id (conj [:= :source_id source-id])- bucket-start (conj [:>= :bucket_date bucket-start])- bucket-end (conj [:<= :bucket_date bucket-end]))]- (t2/select [:model/SourceDimensionDaily- :source_type- :source_id- :field_id- :temporal_unit- :binning- [[:sum :count] :total_count]]- {:where where- :group-by [:source_type :source_id :field_id :temporal_unit :binning]- :order-by [[:total_count :desc]]})))+ (usage-metadata.db/grouped-dimension-rows source-type source-id bucket-start bucket-end))(defn- decode-atom-fingerprints [x](cond@@ -159,44 +113,14 @@Each returned row carries the whole-clause JSON, the atom-fingerprint array, and the summed countacross the window — the input shape expected by the FIM pass."[{:keys [source-type source-id bucket-start bucket-end]}]- (let [where (cond-> [:and- [:in :ownership_mode ["direct" "projected"]]]- source-type (conj [:= :source_type (name source-type)])- source-id (conj [:= :source_id source-id])- bucket-start (conj [:>= :bucket_date bucket-start])- bucket-end (conj [:<= :bucket_date bucket-end]))]- (->> (t2/select [:model/SourceSegmentCompositeDaily- :source_type- :source_id- :clause- :atom_fingerprints- :atom_count- [[:sum :count] :total_count]]- {:where where- :group-by [:source_type :source_id :clause :atom_fingerprints :atom_count]- :order-by [[:total_count :desc]]})- (mapv (fn [row]- (update row :atom_fingerprints decode-atom-fingerprints))))))+ (->> (usage-metadata.db/grouped-composite-rows source-type source-id bucket-start bucket-end)+ (mapv (fn [row]+ (update row :atom_fingerprints decode-atom-fingerprints)))))(defn- grouped-profile-rows"Group + sum `source_dimension_profile_daily` counts for a source filter."[{:keys [source-type source-id bucket-start bucket-end]}]- (let [where (cond-> [:and]- source-type (conj [:= :source_type (name source-type)])- source-id (conj [:= :source_id source-id])- bucket-start (conj [:>= :bucket_date bucket-start])- bucket-end (conj [:<= :bucket_date bucket-end]))]- (t2/select [:model/SourceDimensionProfileDaily- :source_type- :source_id- :field_id- :source_basis- :observation_type- :observation_value- [[:sum :count] :total_count]]- {:where where- :group-by [:source_type :source_id :field_id :source_basis :observation_type :observation_value]- :order-by [[:total_count :desc]]})))+ (usage-metadata.db/grouped-profile-rows source-type source-id bucket-start bucket-end))(defn- wrap-query"Wrap a raw MBQL map in a full lib query using the app DB metadata-provider. Returns nil on failure."@@ -222,14 +146,13 @@(defn- existing-segment-predicates*[[source-type source-id]]- (let [where (cond-> [:and [:= :archived false]]- (and (= source-type :table) source-id) (conj [:= :table_id source-id]))- segments (t2/select [:model/Segment :id :table_id :definition] {:where where})+ (let [table-id (when (and (= source-type :table) source-id) source-id)+ segments (usage-metadata.db/unarchived-segments table-id)table-ids (into #{} (comp (keep :table_id) (filter pos-int?)) segments)table->db (when (seq table-ids)(into {}(map (juxt :id :db_id))- (t2/select [:model/Table :id :db_id] :id [:in table-ids])))]+ (usage-metadata.db/table-database-ids table-ids)))](lib-be/with-metadata-provider-cache(into #{}(mapcat (fn [{:keys [table_id definition]}]@@ -252,9 +175,7 @@(defn- existing-metric-signatures*[]- (let [cards (t2/select [:model/Card :id :database_id :dataset_query :card_schema]- :type "metric"- :archived false)]+ (let [cards (usage-metadata.db/unarchived-metric-cards)](lib-be/with-metadata-provider-cache(into #{}(mapcat (fn [{:keys [database_id dataset_query]}]@@ -485,14 +406,13 @@(defn- existing-composite-atomsets*[[source-type source-id]]- (let [where (cond-> [:and [:= :archived false]]- (and (= source-type :table) source-id) (conj [:= :table_id source-id]))- segments (t2/select [:model/Segment :id :table_id :definition] {:where where})+ (let [table-id (when (and (= source-type :table) source-id) source-id)+ segments (usage-metadata.db/unarchived-segments table-id)table-ids (into #{} (comp (keep :table_id) (filter pos-int?)) segments)table->db (when (seq table-ids)(into {}(map (juxt :id :db_id))- (t2/select [:model/Table :id :db_id] :id [:in table-ids])))]+ (usage-metadata.db/table-database-ids table-ids)))](lib-be/with-metadata-provider-cache(into #{}(mapcat (fn [{:keys [table_id definition]}]diff --git a/src/metabase/usage_metadata/store.clj b/src/metabase/usage_metadata/store.cljindex 42fb560a7d1..2a72549842d 100644--- a/src/metabase/usage_metadata/store.clj+++ b/src/metabase/usage_metadata/store.clj@@ -1,5 +1,6 @@(ns metabase.usage-metadata.store(:require+ [metabase.usage-metadata.db :as usage-metadata.db][metabase.usage-metadata.models.source-dimension-daily][metabase.usage-metadata.models.source-dimension-profile-daily][metabase.usage-metadata.models.source-metric-daily]@@ -13,50 +14,50 @@1000)(defn- chunked-insert!- [model rows]+ [insert-fn! rows](when (seq rows)(doseq [chunk (partition-all insert-chunk-size rows)]- (t2/insert! model chunk))))+ (insert-fn! chunk))))(defn delete-day!"Delete all rollup rows for `bucket-date` across the usage metadata daily tables."[bucket-date]- (t2/delete! :model/SourceSegmentDaily :bucket_date bucket-date)- (t2/delete! :model/SourceSegmentCompositeDaily :bucket_date bucket-date)- (t2/delete! :model/SourceMetricDaily :bucket_date bucket-date)- (t2/delete! :model/SourceDimensionDaily :bucket_date bucket-date)- (t2/delete! :model/SourceDimensionProfileDaily :bucket_date bucket-date)+ (usage-metadata.db/delete-segment-rollups-for-day! bucket-date)+ (usage-metadata.db/delete-segment-composite-rollups-for-day! bucket-date)+ (usage-metadata.db/delete-metric-rollups-for-day! bucket-date)+ (usage-metadata.db/delete-dimension-rollups-for-day! bucket-date)+ (usage-metadata.db/delete-dimension-profile-rollups-for-day! bucket-date)nil)(defn insert-segment-rollups!"Insert daily segment rollup rows."[rows]- (chunked-insert! :model/SourceSegmentDaily rows)+ (chunked-insert! usage-metadata.db/insert-segment-rollups! rows)nil)(defn insert-composite-rollups!"Insert daily composite segment (whole-:and basket) rollup rows."[rows](when (seq rows)- (t2/insert! :model/SourceSegmentCompositeDaily rows))+ (usage-metadata.db/insert-segment-composite-rollups! rows))nil)(defn insert-metric-rollups!"Insert daily metric rollup rows."[rows]- (chunked-insert! :model/SourceMetricDaily rows)+ (chunked-insert! usage-metadata.db/insert-metric-rollups! rows)nil)(defn insert-dimension-rollups!"Insert daily dimension rollup rows."[rows]- (chunked-insert! :model/SourceDimensionDaily rows)+ (chunked-insert! usage-metadata.db/insert-dimension-rollups! rows)nil)(defn insert-dimension-profile-rollups!"Insert daily dimension profile observation rows."[rows]- (chunked-insert! :model/SourceDimensionProfileDaily rows)+ (chunked-insert! usage-metadata.db/insert-dimension-profile-rollups! rows)nil)(defn replace-day!diff --git a/src/metabase/user_key_value/db.clj b/src/metabase/user_key_value/db.cljnew file mode 100644index 00000000000..c9393409438--- /dev/null+++ b/src/metabase/user_key_value/db.clj@@ -0,0 +1,52 @@+(ns metabase.user-key-value.db+ "Application database queries for the user key-value module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [toucan2.core :as t2]))++(defn user-key-value+ "The UserKeyValue of the User with `user-id` for `k` in `namespace`, or nil."+ [user-id namespace k]+ (t2/select-one :model/UserKeyValue :user_id user-id :namespace namespace :key k))++(defn update-user-key-value!+ "Set the value and expiry of the UserKeyValue of the User with `user-id` for `k` in `namespace`."+ [user-id namespace k value expires-at]+ (t2/update! :model/UserKeyValue :user_id user-id :namespace namespace :key k {:value value, :expires_at expires-at}))++(defn insert-user-key-value!+ "Insert a UserKeyValue for the User with `user-id`."+ [user-id namespace k value expires-at]+ (t2/insert! :model/UserKeyValue {:user_id user-id+ :namespace namespace+ :key k+ :value value+ :expires_at expires-at}))++(defn delete-user-key-value!+ "Delete the UserKeyValue of the User with `user-id` for `k` in `namespace`."+ [user-id namespace k]+ (t2/delete! :model/UserKeyValue :namespace namespace :user_id user-id :key k))++(defn unexpired-user-key-value+ "The unexpired UserKeyValue of the User with `user-id` for `k` in `namespace`, or nil."+ [user-id namespace k]+ (t2/select-one :model/UserKeyValue+ {:where [:and+ [:= :user_id user-id]+ [:= :namespace namespace]+ [:= :key k]+ [:or+ [:>= :expires_at :%now]+ [:= :expires_at nil]]]}))++(defn unexpired-user-key-values+ "The unexpired UserKeyValues of the User with `user-id` in `namespace`."+ [user-id namespace]+ (t2/select :model/UserKeyValue+ {:where [:and+ [:= :user_id user-id]+ [:= :namespace namespace]+ [:or+ [:>= :expires_at :%now]+ [:= :expires_at nil]]]}))diff --git a/src/metabase/user_key_value/models/user_key_value.clj b/src/metabase/user_key_value/models/user_key_value.cljindex 75e5a25e070..3196a9664f4 100644--- a/src/metabase/user_key_value/models/user_key_value.clj+++ b/src/metabase/user_key_value/models/user_key_value.clj@@ -34,6 +34,7 @@(:require[malli.core :as mc][malli.transform :as mtx]+ [metabase.user-key-value.db :as user-key-value.db][metabase.user-key-value.models.user-key-value.types :as types][metabase.util.malli :as mu][methodical.core :as methodical]@@ -58,19 +59,13 @@(mtx/default-value-transformer){:name :database}))](t2/with-transaction [_]- (if (t2/select-one :model/UserKeyValue :user_id user-id :namespace namespace :key key)- (t2/update! :model/UserKeyValue :user_id user-id :namespace namespace :key key {:value value- :expires_at expires-at})+ (if (user-key-value.db/user-key-value user-id namespace key)+ (user-key-value.db/update-user-key-value! user-id namespace key value expires-at)(try- (t2/insert! :model/UserKeyValue {:user_id user-id- :namespace namespace- :key key- :value value- :expires_at expires-at})+ (user-key-value.db/insert-user-key-value! user-id namespace key value expires-at);; in case we caught a duplicate key exception (a row was inserted between our read and write), try updating(catch Exception _- (t2/update! :model/UserKeyValue :user_id user-id :namespace namespace :key key {:value value- :expires_at expires-at})))))+ (user-key-value.db/update-user-key-value! user-id namespace key value expires-at)))))value))(mu/defn delete!@@ -78,7 +73,7 @@[user-id :- :intnamespace :- :stringk :- :string]- (t2/delete! :model/UserKeyValue :namespace namespace :user_id user-id :key k))+ (user-key-value.db/delete-user-key-value! user-id namespace k))(mu/defn retrieve"Retrieves a KV-pair"@@ -86,15 +81,7 @@namespace :- :stringk :- :string](when-let [ukv- (t2/select-one :model/UserKeyValue- {:where- [:and- [:= :user_id user-id]- [:= :namespace namespace]- [:= :key k]- [:or- [:>= :expires_at :%now]- [:= :expires_at nil]]]})]+ (user-key-value.db/unexpired-user-key-value user-id namespace k)](:value (mc/decode ::types/user-key-valueukv(mtx/transformer@@ -105,14 +92,7 @@"Retrieves all KV-pairs in a namespace"[user-id :- :intnamespace :- :string]- (when-let [kvs (seq (t2/select :model/UserKeyValue- {:where- [:and- [:= :user_id user-id]- [:= :namespace namespace]- [:or- [:>= :expires_at :%now]- [:= :expires_at nil]]]}))]+ (when-let [kvs (seq (user-key-value.db/unexpired-user-key-values user-id namespace))](let [parsed-kvs (mc/decode [:sequential ::types/user-key-value]kvs(mtx/transformerdiff --git a/src/metabase/users/db.clj b/src/metabase/users/db.cljnew file mode 100644index 00000000000..e51387eb2d9--- /dev/null+++ b/src/metabase/users/db.clj@@ -0,0 +1,214 @@+(ns metabase.users.db+ "Application database queries for the users module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [honey.sql.helpers :as sql.helpers]+ [metabase.api.common :as api]+ [metabase.permissions.core :as perms]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn- status-clause+ "Figure out what `where` clause to add to the user query when we get a fiddly status and include_deactivated+ query.++ This is to keep backwards compatibility with `include_deactivated` while adding `status."+ [status include-deactivated]+ (if include-deactivated+ nil+ (case status+ "all" nil+ "deactivated" [:= :is_active false]+ "active" [:= :is_active true]+ [:= :is_active true])))++(defn- wildcard-query [query] (h2x/like-substring query))++(defn- query-clause+ "Honeysql clause to shove into user query if there's a query"+ [query]+ [:or+ [:like :%lower.first_name (wildcard-query query)]+ [:like :%lower.last_name (wildcard-query query)]+ [:like :%lower.email (wildcard-query query)]])++(defn- table-metadata-perms-exist-clause+ "EXISTS clause, correlated to :core_user.id, testing whether the user is in a group that grants+ manage-table-metadata."+ []+ [:exists ^:allow-subquery {:select [1]+ :from [[:permissions_group_membership :pgm]]+ :join [[:data_permissions :p] [:= :p.group_id :pgm.group_id]]+ :where [:and+ [:= :pgm.user_id :core_user.id]+ [:= :p.perm_type "perms/manage-table-metadata"]+ [:= :p.perm_value "yes"]]}])++(defn- tenant-clause+ "Honeysql clause restricting `:tenant_id`: `tenant-filter` is a tenant id to restrict to, `:all` for no+ restriction, `:external` for any non-nil tenant, or nil for no tenant (internal users)."+ [tenant-filter]+ (case tenant-filter+ :all nil+ :external [:not= :tenant_id nil]+ [:= :tenant_id tenant-filter]))++(def ^:private sort-order-by+ "Fixed ORDER BYs for [[filter-clauses]]'s `:sort` option."+ {:first-name [[:%lower.first_name :asc] [:%lower.last_name :asc] [:id :asc]]+ :last-name [[:%lower.last_name :asc] [:%lower.first_name :asc]]})++(defn- add-sort+ [honeysql-map sort]+ (apply sql.helpers/order-by honeysql-map (sort-order-by sort)))++(defn filter-clauses+ "Honeysql clauses for filtering on users.++ Options:+ :status - filter by status (\"active\", \"deactivated\", \"all\")+ :query - text search on first_name, last_name, email+ :group-ids - filter by permissions group membership+ :user-ids - filter to just these user ids+ :include-deactivated - legacy alias for status=all+ :is-data-analyst? - filter by data analyst status (true/false)+ :can-access-data-studio? - filter by Data Studio access (analysts, superusers, or users with table metadata perms)+ :tenant-filter - restrict `:tenant_id`: a tenant id, `:all` (no restriction), `:external` (any+ non-nil tenant), or nil (no tenant); omit the key entirely for no restriction+ :sort - `:first-name` or `:last-name`, adds an ORDER BY; omit for none+ :limit - pagination limit+ :offset - pagination offset"+ [{:keys [status query group-ids user-ids include-deactivated is-data-analyst? can-access-data-studio? sort+ limit offset]+ :as options}]+ (cond-> {}+ true (sql.helpers/where [:= :core_user.type "personal"])+ true (sql.helpers/where (status-clause status include-deactivated))+ ;; don't send the internal user+ (perms/sandboxed-or-impersonated-user?) (sql.helpers/where [:= :core_user.id api/*current-user-id*])+ (contains? options :tenant-filter) (sql.helpers/where (tenant-clause (:tenant-filter options)))+ (some? query) (sql.helpers/where (query-clause query))+ (some? is-data-analyst?) (sql.helpers/where (if is-data-analyst?+ :core_user.is_data_analyst+ [:not :core_user.is_data_analyst]))+ (some? can-access-data-studio?) (sql.helpers/where (if can-access-data-studio?+ [:or+ :core_user.is_data_analyst+ :core_user.is_superuser+ (table-metadata-perms-exist-clause)]+ [:and+ [:not :core_user.is_data_analyst]+ [:not :core_user.is_superuser]+ [:not (table-metadata-perms-exist-clause)]]))+ (some? group-ids) (sql.helpers/right-join+ :permissions_group_membership+ [:= :core_user.id :permissions_group_membership.user_id])+ (some? group-ids) (sql.helpers/where+ [:in :permissions_group_membership.group_id group-ids])+ (seq user-ids) (sql.helpers/where [:in :core_user.id user-ids])+ (some? sort) (add-sort sort)+ (some? limit) (sql.helpers/limit limit)+ (some? offset) (sql.helpers/offset offset)))++(defn set-user-last-login-now!+ "Set `last_login` of the User with `user-id` to now."+ [user-id]+ (t2/update! :model/User user-id {:last_login :%now}))++(defn user-settings+ "The `:settings` of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one-fn :settings [:model/User :settings] :id user-id))++(defn delete-pulse-channel-recipients-for-user!+ "Delete every PulseChannelRecipient of the User with `user-id`."+ [user-id]+ (t2/delete! :model/PulseChannelRecipient :user_id user-id))++(defn group-membership-exists?+ "Whether the User with `user-id` is a member of the PermissionsGroup with `group-id`."+ [group-id user-id]+ (t2/exists? :model/PermissionsGroupMembership :group_id group-id :user_id user-id))++(defn user-group-ids+ "The ids of the PermissionsGroups the User with `user-id` belongs to."+ [user-id]+ (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id user-id))++(defn group-memberships-for-users+ "The user id, group id (as `:id`), and group manager flag of the PermissionsGroupMemberships of the Users with+ `user-ids`."+ [user-ids]+ (t2/select [:model/PermissionsGroupMembership :user_id [:group_id :id] :is_group_manager] :user_id [:in user-ids]))++(defn user-group-ids-for-users+ "The user id and group id of the PermissionsGroupMemberships of the Users with `user-ids`."+ [user-ids]+ (t2/select [:model/PermissionsGroupMembership :user_id :group_id] :user_id [:in user-ids]))++(defn user-count+ "The number of Users."+ []+ (t2/count :model/User))++(defn tenant-collection-ids+ "A map of Tenant id to tenant Collection id for the Tenants with `tenant-ids`."+ [tenant-ids]+ (t2/select-pk->fn :tenant_collection_id :model/Tenant :id [:in tenant-ids]))++(defn insert-user!+ "Insert the User `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/User row))++(defn same-groups-user-ids+ "The `:user_id`s of the Users sharing a PermissionsGroup other than the one with `all-users-group-id` with the User+ with `user-id`."+ [user-id all-users-group-id]+ (t2/query {:select-distinct [:permissions_group_membership.user_id]+ :from [:permissions_group_membership]+ :where [:in :permissions_group_membership.group_id+ ^:allow-subquery+ {:select-distinct [:permissions_group_membership.group_id]+ :from [:permissions_group_membership]+ :where [:and [:= :permissions_group_membership.user_id user-id]+ [:not= :permissions_group_membership.group_id all-users-group-id]]}]}))++(defn delete-user-parameter-values!+ "Delete the UserParameterValues identified by the `:user_id`, `:dashboard_id`, and `:parameter_id` of `parameters`."+ [parameters]+ (t2/delete! :model/UserParameterValue+ {:where (into [:or] (for [p parameters]+ [:and+ [:= :user_id (:user_id p)]+ [:= :dashboard_id (:dashboard_id p)]+ [:= :parameter_id (:parameter_id p)]]))}))++(defn insert-user-parameter-values!+ "Insert the UserParameterValue `rows`."+ [rows]+ (t2/insert! :model/UserParameterValue rows))++(defn user-parameter-values-for-dashboards+ "The UserParameterValues of the User with `user-id` for the Dashboards with `dashboard-ids`."+ [user-id dashboard-ids]+ (t2/select :model/UserParameterValue :dashboard_id [:in dashboard-ids] :user_id user-id))++(defn database-exists?+ "Whether a Database with `database-id` exists."+ [database-id]+ (t2/exists? :model/Database :id database-id))++(defn admin-or-self-visible-user+ "The User with `id`, with the given `columns`, or nil. When `type` and/or `is-active?` are given (non-nil), also+ requires `:type` and/or `:is_active` to match."+ [columns id & {:keys [type is-active?]}]+ (apply t2/select-one (into [:model/User] columns)+ :id id+ (concat (when type [:type type])+ (when (some? is-active?) [:is_active is-active?]))))++(defn user-email-exists?+ "Whether a User whose lower-cased email is `lower-case-email` exists."+ [lower-case-email]+ (t2/exists? :model/User :%lower.email lower-case-email))diff --git a/src/metabase/users/events/last_login.clj b/src/metabase/users/events/last_login.cljindex 88f5b27d3c6..9cb0c1686fc 100644--- a/src/metabase/users/events/last_login.clj+++ b/src/metabase/users/events/last_login.clj@@ -1,9 +1,9 @@(ns metabase.users.events.last-login(:require[metabase.events.core :as events]+ [metabase.users.db :as users.db][metabase.util.log :as log]- [methodical.core :as methodical]- [toucan2.core :as t2]))+ [methodical.core :as methodical]))(events/derive! ::event :metabase/event)(events/derive! :event/user-login ::event)@@ -14,7 +14,7 @@(when user-id(try;; just make a simple attempt to set the `:last_login` for the given user to now- (t2/update! :model/User user-id {:last_login :%now})+ (users.db/set-user-last-login-now! user-id)(catch Throwable e;; TODO -- huh? Terrible log message.(log/warnf "Failed to process sync-database event. %s: %s" topic (ex-message e))))))diff --git a/src/metabase/users/models/user.clj b/src/metabase/users/models/user.cljindex c316fad1074..d510d9f4441 100644--- a/src/metabase/users/models/user.clj+++ b/src/metabase/users/models/user.clj@@ -2,7 +2,6 @@(:require[clojure.data :as data][clojure.string :as str]- [honey.sql.helpers :as sql.helpers][metabase.api.common :as api][metabase.config.core :as config][metabase.events.core :as events]@@ -13,6 +12,7 @@[metabase.setup.core :as setup][metabase.system.core :as system][metabase.tenants.core :as tenants]+ [metabase.users.db :as users.db][metabase.users.schema :as users.schema][metabase.util :as u][metabase.util.honey-sql-2 :as h2x]@@ -95,7 +95,7 @@(when user-or-user-id(settings-map(if (integer? user-or-user-id)- (:settings (t2/select-one [:model/User :settings] :id user-or-user-id))+ (users.db/user-settings user-or-user-id)(:settings user-or-user-id)))));;; -------------------------------------------------- Validation Helpers --------------------------------------------------@@ -172,7 +172,7 @@"Clean up user subscriptions when user is archived."[user-id active?](when (false? active?)- (t2/delete! 'PulseChannelRecipient :user_id user-id)))+ (users.db/delete-pulse-channel-recipients-for-user! user-id)))(defn- prepare-archival-timestamp"Return a map with deactivated_at field based on is_active status.@@ -232,9 +232,7 @@{:keys [email locale]superuser? :is_superuseractive? :is_active} changes- in-admin-group? (t2/exists? :model/PermissionsGroupMembership- :group_id (:id (perms/admin-group))- :user_id id)]+ in-admin-group? (users.db/group-membership-exists? (:id (perms/admin-group)) id)](validate-last-admin-not-archived! id in-admin-group? active?)(when email (validate-user-email! email))(when locale (validate-user-locale! locale))@@ -291,7 +289,7 @@"Fetch set of IDs of PermissionsGroup a User belongs to."[user-or-id](when user-or-id- (t2/select-fn-set :group_id :model/PermissionsGroupMembership :user_id (u/the-id user-or-id))))+ (users.db/user-group-ids (u/the-id user-or-id))))(defmethod mi/exclude-internal-content-hsql :model/User[_model & {:keys [table-alias]}]@@ -305,8 +303,7 @@In which `is_group_manager` is only added when `advanced-permissions` is enabled."[users](when (seq users)- (let [user-id->memberships (group-by :user_id (t2/select [:model/PermissionsGroupMembership :user_id [:group_id :id] :is_group_manager]- :user_id [:in (set (map u/the-id users))]))+ (let [user-id->memberships (group-by :user_id (users.db/group-memberships-for-users (set (map u/the-id users))))membership->group (fn [membership](select-keys membership[:id (when (premium-features/enable-advanced-permissions?)@@ -324,8 +321,7 @@TODO: deprecate :group_ids and use :user_group_memberships instead"[users](when (seq users)- (let [user-id->memberships (group-by :user_id (t2/select [:model/PermissionsGroupMembership :user_id :group_id]- :user_id [:in (set (map u/the-id users))]))]+ (let [user-id->memberships (group-by :user_id (users.db/user-group-ids-for-users (set (map u/the-id users))))](for [user users](assoc user :group_ids (set (map :group_id (user-id->memberships (u/the-id user)))))))))@@ -336,7 +332,7 @@the wording for this user on a homepage banner that prompts them to add their database."[users](when (seq users)- (let [user-count (t2/count :model/User)]+ (let [user-count (users.db/user-count)](for [user users](assoc user :has_invited_second_user (and (= (:id user) 1)(> user-count 1)))))))@@ -361,8 +357,7 @@(let [users-with-tenant-ids (filter :tenant_id users)tenant-ids (set (map :tenant_id users-with-tenant-ids))tenant-id->collection-id (when (seq tenant-ids)- (t2/select-pk->fn :tenant_collection_id :model/Tenant- :id [:in tenant-ids]))]+ (users.db/tenant-collection-ids tenant-ids))];; now for each User, try to find the corresponding tenant collection ID(for [user users](assoc user :tenant_collection_id (when-let [tenant-id (:tenant_id user)]@@ -382,7 +377,7 @@"Creates a new user with a default password, when deserializing eg. a `:creator_id` field whose email address doesn'tmatch any existing user."[new-user]- (t2/insert-returning-instance! :model/User new-user))+ (users.db/insert-user! new-user))(mu/defn create-and-invite-user!"Convenience function for inviting a new `User` and sending them a welcome email.@@ -395,7 +390,7 @@setup? :- :booleaninvite-target :- [:maybe users.schema/InviteTarget]];; create the new user- (u/prog1 (t2/insert-returning-instance! :model/User new-user)+ (u/prog1 (users.db/insert-user! new-user)(events/publish-event! :event/user-invited{:object(cond-> (assoc <>@@ -410,7 +405,7 @@"Convenience for creating a new user via Google Auth. This account is considered active immediately; thus all activeadmins will receive an email right away."[new-user :- users.schema/NewUser]- (u/prog1 (t2/insert-returning-instance! :model/User new-user)+ (u/prog1 (users.db/insert-user! new-user);; send an email to everyone including the site admin if that's set(when (setting/get :send-new-sso-user-admin-email?)((requiring-resolve 'metabase.channel.email.messages/send-user-joined-admin-notification-email!) <>, :google-auth? true))))@@ -447,92 +442,13 @@;;; Filtering users-(defn- status-clause- "Figure out what `where` clause to add to the user query when- we get a fiddly status and include_deactivated query.-- This is to keep backwards compatibility with `include_deactivated` while adding `status."- [status include_deactivated]- (if include_deactivated- nil- (case status- "all" nil- "deactivated" [:= :is_active false]- "active" [:= :is_active true]- [:= :is_active true])))--(defn- wildcard-query [query] (h2x/like-substring query))--(defn- query-clause- "Honeysql clause to shove into user query if there's a query"- [query]- [:or- [:like :%lower.first_name (wildcard-query query)]- [:like :%lower.last_name (wildcard-query query)]- [:like :%lower.email (wildcard-query query)]])--(defn- table-metadata-perms-exist-clause- "EXISTS clause, correlated to :core_user.id, testing whether the user is in a group that grants- manage-table-metadata."- []- [:exists ^:allow-subquery {:select [1]- :from [[:permissions_group_membership :pgm]]- :join [[:data_permissions :p] [:= :p.group_id :pgm.group_id]]- :where [:and- [:= :pgm.user_id :core_user.id]- [:= :p.perm_type "perms/manage-table-metadata"]- [:= :p.perm_value "yes"]]}])-(defn same-groups-user-ids"Return a list of all user-ids in the same group with the user with id `user-id`.Ignore the All-user groups."[user-id](map :user_id- (t2/query {:select-distinct [:permissions_group_membership.user_id]- :from [:permissions_group_membership]- :where [:in :permissions_group_membership.group_id- ;; get all the groups ids that the current user is in- ^:allow-subquery- {:select-distinct [:permissions_group_membership.group_id]- :from [:permissions_group_membership]- :where [:and [:= :permissions_group_membership.user_id user-id]- [:not= :permissions_group_membership.group_id (:id (perms/all-users-group))]]}]})))--(defn filter-clauses- "Honeysql clauses for filtering on users.-- Options:- :status - filter by status (\"active\", \"deactivated\", \"all\")- :query - text search on first_name, last_name, email- :group-ids - filter by permissions group membership- :include-deactivated - legacy alias for status=all- :is-data-analyst? - filter by data analyst status (true/false)- :can-access-data-studio? - filter by Data Studio access (analysts, superusers, or users with table metadata perms)- :limit - pagination limit- :offset - pagination offset"- [{:keys [status query group-ids include-deactivated is-data-analyst? can-access-data-studio? limit offset]}]- (cond-> {}- true (sql.helpers/where [:= :core_user.type "personal"])- true (sql.helpers/where (status-clause status include-deactivated))- ;; don't send the internal user- (perms/sandboxed-or-impersonated-user?) (sql.helpers/where [:= :core_user.id api/*current-user-id*])- (some? query) (sql.helpers/where (query-clause query))- (some? is-data-analyst?) (sql.helpers/where (if is-data-analyst?- :core_user.is_data_analyst- [:not :core_user.is_data_analyst]))- (some? can-access-data-studio?) (sql.helpers/where (if can-access-data-studio?- [:or- :core_user.is_data_analyst- :core_user.is_superuser- (table-metadata-perms-exist-clause)]- [:and- [:not :core_user.is_data_analyst]- [:not :core_user.is_superuser]- [:not (table-metadata-perms-exist-clause)]]))- (some? group-ids) (sql.helpers/right-join- :permissions_group_membership- [:= :core_user.id :permissions_group_membership.user_id])- (some? group-ids) (sql.helpers/where- [:in :permissions_group_membership.group_id group-ids])- (some? limit) (sql.helpers/limit limit)- (some? offset) (sql.helpers/offset offset)))+ (users.db/same-groups-user-ids user-id (:id (perms/all-users-group)))))++(def filter-clauses+ "Honeysql clauses for filtering on users. See [[users.db/filter-clauses]] for the options."+ users.db/filter-clauses)diff --git a/src/metabase/users/models/user_parameter_value.clj b/src/metabase/users/models/user_parameter_value.cljindex 28c592f2337..62d2a87f084 100644--- a/src/metabase/users/models/user_parameter_value.clj+++ b/src/metabase/users/models/user_parameter_value.clj@@ -5,6 +5,7 @@[metabase.batch-processing.core :as grouper][metabase.models.interface :as mi][metabase.settings.core :as setting]+ [metabase.users.db :as users.db][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]@@ -40,15 +41,9 @@(let [to-insert (remove #(and (nil? (:value %)) (nil? (:default %))) parameters)](t2/with-transaction [_conn](doseq [batch (partition-all 1000 parameters)]- (t2/delete! :model/UserParameterValue- {:where (into [:or] (for [p batch]- [:and- [:= :user_id (:user_id p)]- [:= :dashboard_id (:dashboard_id p)]- [:= :parameter_id (:parameter_id p)]]))}))+ (users.db/delete-user-parameter-values! batch))(doseq [batch (partition-all 1000 to-insert)]- (t2/insert! :model/UserParameterValue- (map #(select-keys % [:user_id :dashboard_id :parameter_id :value]) batch)))))))+ (users.db/insert-user-parameter-values! (map #(select-keys % [:user_id :dashboard_id :parameter_id :value]) batch)))))))(defn- update-user-parameter-values* [inputs](try@@ -95,9 +90,7 @@dashboards:last_used_param_values(fn [] ;; return a map of {dashboard-id {parameter-id value}}- (let [upvs (t2/select :model/UserParameterValue- :dashboard_id [:in (map :id dashboards)]- :user_id user-id)]+ (let [upvs (users.db/user-parameter-values-for-dashboards user-id (map :id dashboards))](as-> upvs result(group-by :dashboard_id result)(update-vals result (fn [upvs]diff --git a/src/metabase/users/settings.clj b/src/metabase/users/settings.cljindex 6a96945f574..8baa50d9424 100644--- a/src/metabase/users/settings.clj+++ b/src/metabase/users/settings.clj@@ -1,8 +1,8 @@(ns metabase.users.settings(:require[metabase.settings.core :as setting :refer [defsetting]]- [metabase.util.i18n :refer [deferred-tru]]- [toucan2.core :as t2]))+ [metabase.users.db :as users.db]+ [metabase.util.i18n :refer [deferred-tru]]));; NB: Settings are also defined where they're used@@ -19,7 +19,7 @@:type :integer:getter (fn [](when-let [id (setting/get-value-of-type :integer :last-used-native-database-id)]- (when (t2/exists? :model/Database :id id) id))))+ (when (users.db/database-exists? id) id))))(defsetting dismissed-excel-pivot-exports-banner(deferred-tru "Toggle which is true after a user has dismissed the excel pivot exports banner.")diff --git a/src/metabase/users/util.clj b/src/metabase/users/util.cljindex 1a3b94fd6fd..5694dd7c022 100644--- a/src/metabase/users/util.clj+++ b/src/metabase/users/util.clj@@ -9,6 +9,7 @@[metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features][metabase.settings.core :as setting]+ [metabase.users.db :as users.db][metabase.users.models.user :as user][metabase.users.schema :as users.schema][metabase.util :as u]@@ -51,9 +52,10 @@(maybe-set-user-permissions-groups! user-or-id (map :id new-user-group-memberships)))))(defn fetch-user- "Implementation for `/api/user` endpoints; fetch a User from the app DB."- [& query-criteria]- (apply t2/select-one (vec (cons :model/User user/admin-or-self-visible-columns)) query-criteria))+ "Implementation for `/api/user` endpoints; fetch a User from the app DB by `:id`, optionally requiring `:type`+ and/or `:is_active` to match."+ [& {:keys [id type is_active]}]+ (users.db/admin-or-self-visible-user user/admin-or-self-visible-columns id :type type :is-active? is_active))(mu/defn invite-user!"Implementation for `POST /api/user`, invites a user to Metabase."@@ -65,7 +67,7 @@:as attributes} :- [:map[:source {:optional true, :default :admin} [:enum :setup :admin]]]](api/check-superuser)- (api/check-400 (not (t2/exists? :model/User :%lower.email (u/lower-case-en email)))+ (api/check-400 (not (users.db/user-email-exists? (u/lower-case-en email))){:errors {:email (tru "Email address already in use.")}:error_code "email-already-in-use"})(api/checkp (not (and tenant-iddiff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.cljindex 179eccf2f72..a2ae956a455 100644--- a/src/metabase/users_rest/api.clj+++ b/src/metabase/users_rest/api.clj@@ -2,7 +2,6 @@"/api/user endpoints"(:require[clojure.set :as set]- [honey.sql.helpers :as sql.helpers][java-time.api :as t][metabase.api.common :as api][metabase.api.macros :as api.macros]@@ -18,6 +17,7 @@[metabase.sso.core :as sso][metabase.system.core :as system][metabase.tenants.core :as tenants]+ [metabase.users-rest.db :as users-rest.db][metabase.users.core :as users][metabase.users.models.user :as user][metabase.users.schema :as users.schema]@@ -52,7 +52,7 @@(let [{email :email} user-before-updatenew-collection-name (collection/format-personal-collection-name first_name last_name email :site)](when-not (= new-collection-name (:name collection))- (t2/update! :model/Collection (:id collection) {:name new-collection-name}))))))+ (users-rest.db/rename-collection! (:id collection) new-collection-name))))));;; ------------ Serialize User Attribute Provenance ------------------@@ -194,26 +194,25 @@(do(api/check-400 (not (every? #(contains? params %) [:tenant_id :tenancy]))(tru "You cannot specify both `tenancy` and `tenant_id`"))- (let [clauses (let [clauses (user/filter-clauses {:status status- :query query- :group-ids (when group_id [group_id])- :include-deactivated include_deactivated- :is-data-analyst? is_data_analyst- :can-access-data-studio? can_access_data_studio- :limit (request/limit)- :offset (request/offset)})]- (cond- (not api/*is-superuser?*) (sql.helpers/where clauses [:= :tenant_id (:tenant_id @api/*current-user*)])- (contains? params :tenant_id) (sql.helpers/where clauses [:= :tenant_id tenant_id])- (= tenancy :all) clauses- (= tenancy :external) (sql.helpers/where clauses [:not= :tenant_id nil])- :else (sql.helpers/where clauses [:= :tenant_id nil])))]- {:data (cond-> (t2/select- (vec (cons :model/User (user-visible-columns)))- (sql.helpers/order-by clauses- [:%lower.first_name :asc]- [:%lower.last_name :asc]- [:id :asc]))+ (let [tenant-filter (cond+ (not api/*is-superuser?*) (:tenant_id @api/*current-user*)+ (contains? params :tenant_id) tenant_id+ (= tenancy :all) :all+ (= tenancy :external) :external+ :else nil)+ clauses (user/filter-clauses {:status status+ :query query+ :group-ids (when group_id [group_id])+ :include-deactivated include_deactivated+ :is-data-analyst? is_data_analyst+ :can-access-data-studio? can_access_data_studio+ :tenant-filter tenant-filter+ :sort :first-name+ :limit (request/limit)+ :offset (request/offset)})]+ {:data (cond-> (users-rest.db/users-with-columns+ (user-visible-columns)+ clauses);; For admins also include the IDs of Users' Personal Collectionsapi/*is-superuser?*(t2/hydrate :personal_collection_id :tenant_collection_id)@@ -225,10 +224,7 @@;; multiple groupsgroup_iddistinct)- :total (-> (t2/query- (merge {:select [[[:count [:distinct :core_user.id]] :count]]- :from :core_user}- (users/filter-clauses-without-paging clauses)))+ :total (-> (users-rest.db/distinct-user-count (users/filter-clauses-without-paging clauses))first:count):limit (request/limit)@@ -246,23 +242,22 @@- If user-visibility is :none or the user is sandboxed, include only themselves."[];; defining these functions so the branching logic below can be as clear as possible- (letfn [(all [] (let [clauses (cond-> (user/filter-clauses {})- (not api/*is-superuser?*) (sql.helpers/where- [:= :tenant_id (:tenant_id @api/*current-user*)])- (not (perms/use-tenants)) (sql.helpers/where [:= :tenant_id nil])- true (sql.helpers/order-by [:%lower.last_name :asc] [:%lower.first_name :asc]))]- {:data (t2/select (vec (cons :model/User (user-visible-columns))) clauses)- :total (t2/count :model/User (users/filter-clauses-without-paging clauses))+ (letfn [(recipient-tenant-filter [] (cond+ (not api/*is-superuser?*) (:tenant_id @api/*current-user*)+ (not (perms/use-tenants)) nil+ :else :all))+ (all [] (let [clauses (user/filter-clauses {:tenant-filter (recipient-tenant-filter)+ :sort :last-name})]+ {:data (users-rest.db/users-with-columns (user-visible-columns) clauses)+ :total (users-rest.db/user-count (users/filter-clauses-without-paging clauses)):limit (request/limit):offset (request/offset)}))(within-group [] (let [user-ids (user/same-groups-user-ids api/*current-user-id*)- clauses (cond-> (user/filter-clauses {})- (not api/*is-superuser?*) (sql.helpers/where [:= :tenant_id (:tenant_id @api/*current-user*)])- (not (perms/use-tenants)) (sql.helpers/where [:= :tenant_id nil])- (seq user-ids) (sql.helpers/where [:in :core_user.id user-ids])- true (sql.helpers/order-by [:%lower.last_name :asc] [:%lower.first_name :asc]))]- {:data (t2/select (vec (cons :model/User (user-visible-columns))) clauses)- :total (t2/count :model/User (users/filter-clauses-without-paging clauses))+ clauses (user/filter-clauses {:tenant-filter (recipient-tenant-filter)+ :user-ids user-ids+ :sort :last-name})]+ {:data (users-rest.db/users-with-columns (user-visible-columns) clauses)+ :total (users-rest.db/user-count (users/filter-clauses-without-paging clauses)):limit (request/limit):offset (request/offset)}))](cond@@ -305,32 +300,24 @@"Adds `sso_source` key to the `User`, so FE could determine if the user is logged in via SSO."[{:keys [id] :as user}](if (premium-features/enable-any-sso?)- (assoc user :sso_source (t2/select-one-fn :sso_source :model/User :id id))+ (assoc user :sso_source (users-rest.db/user-sso-source id))user))(defn- add-has-question-and-dashboard"True when the user has permissions for at least one un-archived question and one un-archived dashboard, excludinginternal/automatically-loaded content."[user]- (let [collection-filter (collection/visible-collection-filter-clause)- entity-exists? (fn [model & additional-clauses] (t2/exists? model- {:where (into [:and- [:= :archived false]- collection-filter- (mi/exclude-internal-content-hsql model)]- additional-clauses)}))]- (-> user- (assoc :has_question_and_dashboard- (and (entity-exists? :model/Card)- (entity-exists? :model/Dashboard)))- (assoc :has_model (entity-exists? :model/Card [:= :type "model"])))))+ (-> user+ (assoc :has_question_and_dashboard+ (and (users-rest.db/has-visible-card? nil)+ (users-rest.db/has-visible-dashboard?)))+ (assoc :has_model (users-rest.db/has-visible-card? "model"))))(defn- add-first-login"Adds `first_login` key to the `User` with the oldest timestamp from that user's login history. Otherwise give the current time, as it's the user's first login."[{:keys [id] :as user}](let [ts (or- (:timestamp (t2/select-one [:model/LoginHistory :timestamp] :user_id id- {:order-by [[:timestamp :asc]]}))+ (:timestamp (users-rest.db/first-login id))(t/offset-date-time))](assoc user :first_login ts)))@@ -339,7 +326,7 @@[user](let [enabled? (appearance/custom-homepage)id (appearance/custom-homepage-dashboard)- dash (t2/select-one :model/Dashboard :id id)+ dash (users-rest.db/dashboard id)valid? (and enabled? id (some? dash) (not (:archived dash)) (mi/can-read? dash))](assoc user:custom_homepage (when valid? {:dashboard_id id}))))@@ -351,11 +338,7 @@[user](assoc user :can_write_any_collection(or (:is_superuser user)- (t2/exists? :model/Collection {:where (collection/visible-collection-filter-clause- :id- {:include-trash-collection? false- :include-archived-items :exclude- :permission-level :write})}))))+ (users-rest.db/writable-collection-exists?))))(mr/def ::user-permissions"Permission flags for the current user, used by the FE to decide which UI elements to show. The `can_access_*`,@@ -549,7 +532,7 @@"last_name" (tru "Editing last name is not allowed for SSO users.")));; can't change email if it's already taken BY ANOTHER ACCOUNT(when email- (api/checkp (not (t2/exists? :model/User, :%lower.email (u/lower-case-en email), :id [:not= id]))+ (api/checkp (not (users-rest.db/other-user-with-email-exists? email id))"email" (tru "Email address already associated to another user.")))(t2/with-transaction [_conn];; only superuser or self can update user info@@ -562,12 +545,12 @@api/*is-superuser?* (conj :login_attributes :tenant_id)):non-nil (cond-> #{:email}api/*is-superuser?* (conj :is_superuser))))]- (t2/update! :model/User id changes)+ (users-rest.db/update-user! id changes)(when (contains? changes :tenant_id)(api/check-400 (not (and (:tenant_id changes) (:is_superuser changes)))"Superusers cannot be tenant users")(reset-magic-group-membership! id (:tenant_id changes)))- (events/publish-event! :event/user-update {:object (t2/select-one :model/User :id id)+ (events/publish-event! :event/user-update {:object (users-rest.db/user id):previous-object user-before-update:user-id api/*current-user-id*}))(maybe-update-user-personal-collection-name! user-before-update body)@@ -586,15 +569,15 @@;;; +----------------------------------------------------------------------------------------------------------------+(defn- reactivate-user! [existing-user]- (t2/update! :model/User (u/the-id existing-user)- {:is_active true- :is_superuser false- ;; if the user originally logged in via Google Auth/LDAP and it's no longer enabled, convert them into a regular user- ;; (see metabase#3323)- :sso_source (case (:sso_source existing-user)- :google (when (sso/google-auth-enabled) :google)- :ldap (when (sso/ldap-enabled) :ldap)- (:sso_source existing-user))})+ (users-rest.db/update-user! (u/the-id existing-user)+ {:is_active true+ :is_superuser false+ ;; if the user originally logged in via Google Auth/LDAP and it's no longer enabled, convert them into a regular user+ ;; (see metabase#3323)+ :sso_source (case (:sso_source existing-user)+ :google (when (sso/google-auth-enabled) :google)+ :ldap (when (sso/ldap-enabled) :ldap)+ (:sso_source existing-user))});; now return the existing user whether they were originally active or not(users/fetch-user :id (u/the-id existing-user)))@@ -608,9 +591,7 @@[:id ms/PositiveInt]]](api/check-superuser)(check-not-internal-user id)- (let [user (t2/select-one [:model/User :id :email :first_name :last_name :is_active :sso_source :tenant_id]- :type :personal- :id id)]+ (let [user (users-rest.db/personal-user-columns id)](api/check-404 user);; Can only reactivate inactive users(api/check (not (:is_active user))@@ -641,10 +622,7 @@[:old_password {:optional true} [:maybe :string]]]request](users/check-self-or-superuser id)- (api/let-404 [user (t2/select-one [:model/User :id :email :last_login],- :id id,- :type :personal,- :is_active true)]+ (api/let-404 [user (users-rest.db/active-personal-user-login-columns id)];; admins are allowed to reset anyone's password (in the admin people list) so no need to check the value of;; `old_password` for them regular users have to know their password, however(when-not api/*is-superuser?*@@ -673,7 +651,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](api/check-superuser)- (let [user (api/check-404 (t2/select-one [:model/User :id :is_active :type] :id id))]+ (let [user (api/check-404 (users-rest.db/user-active-and-type id))](api/check-404 (:is_active user))(api/check-404 (= :personal (:type user)))(let [reset-token (auth-identity/create-password-reset! id)@@ -697,9 +675,9 @@(api/check-superuser);; don't technically need to because the internal user is already 'deleted' (deactivated), but keeps the warnings consistent(check-not-internal-user id)- (api/check-404 (t2/exists? :model/User :id id))- (t2/update! :model/User id {:type :personal} {:is_active false})- (events/publish-event! :event/user-deactivated {:object (t2/select-one :model/User :id id) :user-id api/*current-user-id*})+ (api/check-404 (users-rest.db/user-exists? id))+ (users-rest.db/update-personal-user! id {:is_active false})+ (events/publish-event! :event/user-deactivated {:object (users-rest.db/user id) :user-id api/*current-user-id*}){:success true});;; +----------------------------------------------------------------------------------------------------------------+@@ -725,5 +703,5 @@(throw (ex-info (tru "Unrecognized modal: {0}" modal){:modal modal:allowable-modals #{"qbnewb" "datasetnewb"}})))]- (api/check-500 (pos? (t2/update! :model/User id {:type :personal} {k false}))))+ (api/check-500 (pos? (users-rest.db/update-personal-user! id {k false})))){:success true})diff --git a/src/metabase/users_rest/db.clj b/src/metabase/users_rest/db.cljnew file mode 100644index 00000000000..4a1fbbe159b--- /dev/null+++ b/src/metabase/users_rest/db.clj@@ -0,0 +1,117 @@+(ns metabase.users-rest.db+ "Application database queries for the users REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [metabase.collections.models.collection :as collection]+ [metabase.models.interface :as mi]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(defn rename-collection!+ "Set the name of the Collection with `collection-id`."+ [collection-id collection-name]+ (t2/update! :model/Collection collection-id {:name collection-name}))++(defn users-with-columns+ "The `columns` of the Users selected by the Honey SQL `query`."+ [columns query]+ (t2/select (into [:model/User] columns) query))++(defn user-count+ "The number of Users matching the Honey SQL `query`."+ [query]+ (t2/count :model/User query))++(defn distinct-user-count+ "The `:count` of distinct Users matching the Honey SQL `clauses`."+ [clauses]+ (t2/query (merge {:select [[[:count [:distinct :core_user.id]] :count]]+ :from :core_user}+ clauses)))++(defn user-sso-source+ "The SSO source of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one-fn :sso_source :model/User :id user-id))++(defn has-visible-card?+ "Whether an unarchived, non-internal Card visible to the current user exists, optionally narrowed to `card-type`+ (nil for any type)."+ [card-type]+ (t2/exists? :model/Card+ {:where (into [:and+ [:= :archived false]+ (collection/visible-collection-filter-clause)+ (mi/exclude-internal-content-hsql :model/Card)]+ (when card-type [[:= :type card-type]]))}))++(defn has-visible-dashboard?+ "Whether an unarchived, non-internal Dashboard visible to the current user exists."+ []+ (t2/exists? :model/Dashboard+ {:where [:and+ [:= :archived false]+ (collection/visible-collection-filter-clause)+ (mi/exclude-internal-content-hsql :model/Dashboard)]}))++(defn first-login+ "The timestamp of the earliest LoginHistory of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/LoginHistory :timestamp] :user_id user-id {:order-by [[:timestamp :asc]]}))++(defn dashboard+ "The Dashboard with `dashboard-id`, or nil."+ [dashboard-id]+ (t2/select-one :model/Dashboard :id dashboard-id))++(defn writable-collection-exists?+ "Whether the current user can write to at least one Collection (excluding the Trash and archived items)."+ []+ (t2/exists? :model/Collection+ {:where (collection/visible-collection-filter-clause+ :id+ {:include-trash-collection? false+ :include-archived-items :exclude+ :permission-level :write})}))++(defn other-user-with-email-exists?+ "Whether a User other than `user-id` has an email matching `email` case-insensitively."+ [email user-id]+ (t2/exists? :model/User, :%lower.email (u/lower-case-en email), :id [:not= user-id]))++(defn update-user!+ "Apply `changes` to the User with `user-id`."+ [user-id changes]+ (t2/update! :model/User user-id changes))++(defn user+ "The User with `user-id`, or nil."+ [user-id]+ (t2/select-one :model/User :id user-id))++(defn personal-user-columns+ "The id, email, name, active flag, SSO source, and tenant id of the personal User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :id :email :first_name :last_name :is_active :sso_source :tenant_id]+ :type :personal+ :id user-id))++(defn active-personal-user-login-columns+ "The id, email, and last login of the active personal User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :id :email :last_login], :id user-id, :type :personal, :is_active true))++(defn user-active-and-type+ "The id, active flag, and type of the User with `user-id`, or nil."+ [user-id]+ (t2/select-one [:model/User :id :is_active :type] :id user-id))++(defn user-exists?+ "Whether a User with `user-id` exists."+ [user-id]+ (t2/exists? :model/User :id user-id))++(defn update-personal-user!+ "Apply `changes` to the personal User with `user-id`, returning the number of rows updated."+ [user-id changes]+ (t2/update! :model/User user-id {:type :personal} changes))diff --git a/src/metabase/view_log/db.clj b/src/metabase/view_log/db.cljnew file mode 100644index 00000000000..444f7eb0ea8--- /dev/null+++ b/src/metabase/view_log/db.clj@@ -0,0 +1,61 @@+(ns metabase.view-log.db+ "Application database queries for the view log module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module never talks to `toucan2.core` itself."+ (:require+ [java-time.api :as t]+ [toucan2.core :as t2]))++(defn- increment-view-counts-of-model!+ "Increments `model`'s `view_count` per `count->ids`, via a raw update that bypasses Toucan 2 model hooks+ (specifically the search-index enqueue on after-update)."+ [model count->ids]+ (t2/query {:update (t2/table-name model)+ :set {:view_count [:+ :view_count (into [:case]+ (mapcat (fn [[cnt ids]]+ [[:in :id ids] cnt])+ count->ids))]}+ :where [:in :id (apply concat (vals count->ids))]}))++(defn increment-card-view-counts!+ "Add, for each `[count ids]` entry of `count->ids`, `count` to the `view_count` of the Cards with `ids`."+ [count->ids]+ (increment-view-counts-of-model! :model/Card count->ids))++(defn increment-dashboard-view-counts!+ "Add, for each `[count ids]` entry of `count->ids`, `count` to the `view_count` of the Dashboards with `ids`."+ [count->ids]+ (increment-view-counts-of-model! :model/Dashboard count->ids))++(defn increment-table-view-counts!+ "Add, for each `[count ids]` entry of `count->ids`, `count` to the `view_count` of the Tables with `ids`."+ [count->ids]+ (increment-view-counts-of-model! :model/Table count->ids))++(defn increment-document-view-counts!+ "Add, for each `[count ids]` entry of `count->ids`, `count` to the `view_count` of the Documents with `ids`."+ [count->ids]+ (increment-view-counts-of-model! :model/Document count->ids))++(defn insert-view-logs!+ "Insert the ViewLog rows `views`."+ [views]+ (t2/insert! :model/ViewLog views))++(defn card-type+ "The `:type` of the Card with `card-id`, or nil."+ [card-id]+ (t2/select-one-fn :type :model/Card :id card-id))++(defn update-dashboards-last-viewed-at!+ "Move `last_viewed_at` of each Dashboard in `dashboard-id->timestamp` forward to its timestamp, without touching+ `updated_at`, via a raw update that bypasses Toucan 2 model hooks (specifically the :hook/search-index+ after-update; the search index can tolerate staleness on this field, catching up on the next re-index cycle or+ when the dashboard is edited)."+ [dashboard-id->timestamp]+ (t2/query {:update (t2/table-name :model/Dashboard)+ :set {:last_viewed_at (into [:case]+ (mapcat (fn [[id timestamp]]+ [[:= :id id] [:greatest [:coalesce :last_viewed_at (t/offset-date-time 0)] timestamp]])+ dashboard-id->timestamp))+ :updated_at :updated_at}+ :where [:in :id (keys dashboard-id->timestamp)]}))diff --git a/src/metabase/view_log/events/view_log.clj b/src/metabase/view_log/events/view_log.cljindex 0d0b4cab5c3..22b05ad5a25 100644--- a/src/metabase/view_log/events/view_log.clj+++ b/src/metabase/view_log/events/view_log.clj@@ -13,6 +13,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]+ [metabase.view-log.db :as view-log.db][methodical.core :as m][steffan-westcott.clj-otel.api.trace.span :as span][toucan2.core :as t2]))@@ -54,14 +55,11 @@;; :retry-transient? — the body is a single idempotent statement, safe to re-run on a;; multi-master deadlock (e.g. MariaDB Galera, where the cluster lock can't serialize writers).(cluster-lock/with-cluster-lock {:lock lock-name :retry-transient? true}- ;; Using t2/query instead of t2/update! avoids triggering Toucan2 model hooks,- ;; specifically search-index enqueues on after-update.- (t2/query {:update (t2/table-name model)- :set {:view_count [:+ :view_count (into [:case]- (mapcat (fn [[cnt ids]]- [[:in :id ids] cnt])- cnt->ids))]}- :where [:in :id (apply concat (vals cnt->ids))]})))))+ (case model+ :model/Card (view-log.db/increment-card-view-counts! cnt->ids)+ :model/Dashboard (view-log.db/increment-dashboard-view-counts! cnt->ids)+ :model/Table (view-log.db/increment-table-view-counts! cnt->ids)+ :model/Document (view-log.db/increment-document-view-counts! cnt->ids))))))(catch Exception e(log/errorf "Failed to increment view counts: %s" (ex-message e)))))@@ -88,7 +86,7 @@(defn- record-views!* [views](log/debugf "Recording %d views" (count views))(try- (t2/insert! :model/ViewLog views)+ (view-log.db/insert-view-logs! views)(catch Exception e(log/errorf "Failed to record views: %s" (ex-message e)))))@@ -152,7 +150,7 @@:user-id user-id}(try(when (and (= context :ad-hoc)- (= :model (t2/select-one-fn :type :model/Card :id card-id)))+ (= :model (view-log.db/card-type card-id)))(increment-view-counts! :model/Card card-id)(record-views! (generate-view :model :model/Card:object-id card-id@@ -172,20 +170,10 @@(let [dashboard-id->timestamp (update-vals (group-by :id dashboard-id-timestamps)(fn [xs] (apply t/max (map :timestamp xs))))](try- ;; Use t2/query (raw SQL) instead of t2/update! to avoid triggering Toucan2 model hooks- ;; (specifically :hook/search-index after-update). The search index can tolerate staleness on this field: the- ;; index will catch up on the next re-index cycle or when the dashboard is edited. This matches the pattern used- ;; in increment-view-counts!*;; :retry-transient? — the body is a single idempotent statement, safe to re-run on a;; multi-master deadlock (e.g. MariaDB Galera, where the cluster lock can't serialize writers).(cluster-lock/with-cluster-lock {:lock dashboard-statistics-lock :retry-transient? true}- (t2/query {:update (t2/table-name :model/Dashboard)- :set {:last_viewed_at (into [:case]- (mapcat (fn [[id timestamp]]- [[:= :id id] [:greatest [:coalesce :last_viewed_at (t/offset-date-time 0)] timestamp]])- dashboard-id->timestamp))- :updated_at :updated_at}- :where [:in :id (keys dashboard-id->timestamp)]}))+ (view-log.db/update-dashboards-last-viewed-at! dashboard-id->timestamp))(catch Exception e(log/errorf "Failed to update dashboard last_viewed_at: %s" (ex-message e))))))diff --git a/src/metabase/warehouse_schema/db.clj b/src/metabase/warehouse_schema/db.cljnew file mode 100644index 00000000000..dc0f6395471--- /dev/null+++ b/src/metabase/warehouse_schema/db.clj@@ -0,0 +1,376 @@+(ns metabase.warehouse-schema.db+ "Application database queries for the warehouse-schema module. Every function here is a direct Toucan 2 call with+ no additional logic, so the rest of the module only touches `toucan2.core` for model definitions, hydration+ methods, and transactions."+ (:require+ [metabase.app-db.core :as app-db]+ [toucan2.core :as t2]))++(def field-order-rule+ "How should we order fields."+ [[:position :asc] [:%lower.name :asc]])++;;; ------------------------------------------------- Field -------------------------------------------------++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field :id field-id))++(defn- field-in-path-query+ [table-id [field & rest]]+ (when field+ ^:allow-subquery {:from [:metabase_field]+ :select [:id]+ :where [:and+ [:= :table_id table-id]+ [:= :name field]+ [:= :parent_id (field-in-path-query table-id rest)]]}))++(defn field-in-path+ "The Field named by the last of `field-names` (each nested inside the previous, bottom-most first) under+ `table-id`, or nil."+ [table-id field-names]+ (when (seq field-names)+ (t2/select-one :model/Field (field-in-path-query table-id field-names))))++(defn fields+ "The Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Field :id [:in field-ids]))++(defn fields-by-id+ "A map of ID to Field for `field-ids`."+ [field-ids]+ (t2/select-fn->fn :id identity :model/Field :id [:in field-ids]))++(defn field-table-id-rows+ "The ID and Table ID of the Fields with `field-ids`."+ [field-ids]+ (t2/select [:model/Field :id :table_id] :id [:in field-ids]))++(defn field-table-id+ "The Table ID of the Field with `field-id`."+ [field-id]+ (t2/select-one-fn :table_id :model/Field :id field-id))++(defn field-id-by-name+ "The ID of the Field named `field-name` under `parent-id` in the Table with `table-id`, or nil."+ [table-id parent-id field-name]+ (t2/select-one-pk :model/Field :name field-name :parent_id parent-id :table_id table-id))++(defn field-values-eligibility+ "The columns deciding whether the Field with `field-id` should have FieldValues, or nil."+ [field-id]+ (t2/select-one [:model/Field :base_type :visibility_type :has_field_values :preview_display] :id field-id))++(defn field-ids-for-table+ "The IDs of the Fields of the Table with `table-id`."+ [table-id]+ (t2/select-pks-set :model/Field {:where [:= :table_id table-id]}))++(defn active-field-ids-for-table+ "The IDs of the active Fields of the Table with `table-id`."+ [table-id]+ (t2/select-pks-set :model/Field :table_id table-id :active true))++(defn- field-order-order-by+ [field-order]+ (case field-order+ :custom [[:custom_position :asc]]+ :smart [[[:case+ (app-db/isa :semantic_type :type/PK) 0+ (app-db/isa :semantic_type :type/Name) 1+ (app-db/isa :semantic_type :type/Temporal) 2+ :else 3]+ :asc]+ [:%lower.name :asc]]+ :database [[:database_position :asc]]+ :alphabetical [[:%lower.name :asc]]))++(defn field-ids-for-table-ordered+ "The ids of the Fields of the Table with `table-id`, ordered per `field-order` (`:custom`, `:smart`, `:database`,+ or `:alphabetical`)."+ [table-id field-order]+ (t2/select [:model/Field :id] :table_id table-id {:order-by (field-order-order-by field-order)}))++(defn active-fields-for-tables+ "The active, unretired Fields of the Tables with `table-ids`, in field order."+ [table-ids]+ (t2/select :model/Field+ :active true+ :table_id [:in table-ids]+ :visibility_type [:not= "retired"]+ {:order-by field-order-rule}))++(defn pk-field-ids-by-table+ "A map of Table ID to the ID of its visible primary key Field for `table-ids`."+ [table-ids]+ (t2/select-fn->fn :table_id :id :model/Field+ :table_id [:in table-ids]+ :semantic_type (app-db/isa :type/PK)+ :visibility_type [:not-in ["sensitive" "retired"]]))++(defn fk-source-field-ids-without-user-settings+ "The `:id` rows of the Fields targeting the Field with `field-id` that have no FieldUserSettings row."+ [field-id]+ (t2/query {:select [:id]+ :from [:metabase_field]+ :where [:and+ [:= :fk_target_field_id field-id]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [:metabase_field_user_settings]+ :where [:= :metabase_field_user_settings.field_id :metabase_field.id]}]]]}))++(defn update-field!+ "Apply `changes` to the Field with `field-id`."+ [field-id changes]+ (t2/update! :model/Field field-id changes))++(defn clear-fk-targets-to-field!+ "Clear the FK semantic type and target of every Field targeting the Field with `field-id`."+ [field-id]+ (t2/update! :model/Field {:fk_target_field_id field-id} {:semantic_type nil, :fk_target_field_id nil}))++(defn delete-child-fields!+ "Delete the Fields nested under the Field with `parent-id`."+ [parent-id]+ (t2/delete! :model/Field :parent_id parent-id))++(defn delete-fields-for-table!+ "Delete the Fields of the Table with `table-id`."+ [table-id]+ (t2/delete! :model/Field :table_id table-id))++;;; -------------------------------------------- FieldUserSettings --------------------------------------------++(defn field-user-settings+ "The FieldUserSettings of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/FieldUserSettings :field_id field-id))++(defn field-user-settings-exist?+ "Whether the Field with `field-id` has a FieldUserSettings row."+ [field-id]+ (t2/exists? :model/FieldUserSettings field-id))++(defn user-edited-field-ids-for-table+ "The IDs of the Fields of the Table with `table-id` that have a FieldUserSettings row."+ [table-id]+ (t2/select-fn-set :field_id :model/FieldUserSettings+ {:join [[:metabase_field :f] [:= :f.id :field_id]]+ :where [:= :f.table_id table-id]}))++(defn insert-field-user-settings!+ "Insert one FieldUserSettings map or a sequence of them."+ [rows]+ (t2/insert! :model/FieldUserSettings rows))++(defn update-field-user-settings!+ "Apply `changes` to the FieldUserSettings of the Field with `field-id`."+ [field-id changes]+ (t2/update! :model/FieldUserSettings field-id changes))++(defn clear-user-settings-fk-targets-to-field!+ "Clear the user-set FK semantic type and target of every Field targeting the Field with `field-id`."+ [field-id]+ (t2/update! :model/FieldUserSettings {:fk_target_field_id field-id} {:semantic_type nil, :fk_target_field_id nil}))++;;; ---------------------------------------------- FieldValues ----------------------------------------------++(defn field-values-of-type+ "The FieldValues of `type` with `hash-key` for the Field with `field-id`."+ [field-id type hash-key]+ (t2/select :model/FieldValues :field_id field-id :type type :hash_key hash-key))++(defn full-field-values-for-fields+ "The full FieldValues of the Fields with `field-ids`."+ [field-ids]+ (t2/select :model/FieldValues :field_id [:in field-ids] :type :full :hash_key nil))++(defn full-field-values-rows+ "The Field ID and values of the full FieldValues of the Field with `field-id`."+ [field-id]+ (t2/select [:model/FieldValues :field_id :values] :field_id field-id :type :full))++(defn full-field-values-for-tables+ "The Field ID, values, and Table ID of the full FieldValues of the normal Fields of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/FieldValues :field_id :values :field.table_id]+ {:join [[:metabase_field :field] [:= :metabase_fieldvalues.field_id :field.id]]+ :where [:and+ [:in :field.table_id table-ids]+ [:= :field.visibility_type "normal"]+ [:= :metabase_fieldvalues.type "full"]]}))++(defn full-field-values-with-human-readable-values+ "The values and human-readable values of the full FieldValues of the Field with `field-id` if it has+ human-readable values, or nil."+ [field-id]+ (t2/select-one [:model/FieldValues :values :human_readable_values]+ {:where [:and+ [:= :type "full"]+ [:= :field_id field-id]+ [:not= :human_readable_values nil]+ [:not= :human_readable_values "{}"]]}))++(defn field-values-last-used-at+ "The latest `last_used_at` of any FieldValues of the Field with `field-id`."+ [field-id]+ (t2/select-one-fn :max-last-used-at [:model/FieldValues [[:max :last_used_at] :max-last-used-at]]+ {:where [:= :field_id field-id]}))++(defn full-field-values-by-field+ "The `columns` of the full FieldValues of the Fields with `field-ids`."+ [columns field-ids]+ (t2/select columns :field_id [:in field-ids] :type :full))++(defn dimensions-for-fields+ "The Dimensions of the Fields with `field-ids`."+ [field-ids]+ (t2/select :model/Dimension :field_id [:in field-ids]))++(defn update-field-values!+ "Apply `changes` to the FieldValues with `field-values-id`."+ [field-values-id changes]+ (t2/update! :model/FieldValues field-values-id changes))++(defn touch-field-values!+ "Stamp `last_used_at` on the FieldValues with `field-values-id`."+ [field-values-id]+ (t2/update! :model/FieldValues field-values-id {:last_used_at :%now}))++(defn delete-field-values!+ "Delete the FieldValues with `field-values-ids`."+ [field-values-ids]+ (t2/delete! :model/FieldValues :id [:in field-values-ids]))++(defn delete-field-values-for-field!+ "Delete every FieldValues of the Field with `field-id`."+ [field-id]+ (t2/delete! :model/FieldValues :field_id field-id))++(defn delete-field-values-of-types!+ "Delete the FieldValues of `types` of the Field with `field-id`."+ [field-id types]+ (t2/delete! :model/FieldValues :field_id field-id :type [:in types]))++;;; ------------------------------------------------- Table -------------------------------------------------++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn table-by-name+ "The Table named `table-name` in `schema` of the Database with `database-id`, or nil."+ [database-id schema table-name]+ (t2/select-one :model/Table :name table-name :db_id database-id :schema schema))++(defn table-name-and-schema+ "The name and schema of the Table with `table-id`."+ [table-id]+ (t2/select-one [:model/Table :name :schema] :id table-id))++(defn table-database-id+ "The Database ID of the Table with `table-id`."+ [table-id]+ (t2/select-one-fn :db_id :model/Table table-id))++(defn update-table!+ "Apply `changes` to the Table with `table-id`."+ [table-id changes]+ (t2/update! :model/Table table-id changes))++(defn unarchived-segments-for-tables+ "The unarchived Segments of the Tables with `table-ids`, ordered by name."+ [table-ids]+ (t2/select :model/Segment :table_id [:in table-ids] :archived false {:order-by [[:name :asc]]}))++(defn segment-ids-for-table+ "The IDs of the Segments of the Table with `table-id`, excluding archived ones when `skip-archived?`."+ [table-id skip-archived?]+ (t2/select-pks-set :model/Segment {:where [:and [:= :table_id table-id] (when skip-archived? [:not :archived])]}))++(defn unarchived-measures-for-tables+ "The unarchived Measures of the Tables with `table-ids`, ordered by name."+ [table-ids]+ (t2/select :model/Measure :table_id [:in table-ids] :archived false {:order-by [[:name :asc]]}))++(defn measure-ids-for-table+ "The IDs of the Measures of the Table with `table-id`, excluding archived ones when `skip-archived?`."+ [table-id skip-archived?]+ (t2/select-pks-set :model/Measure {:where [:and [:= :table_id table-id] (when skip-archived? [:not :archived])]}))++(defn unarchived-metric-cards-for-tables+ "The unarchived metric Cards of the Tables with `table-ids`, ordered by name."+ [table-ids]+ (t2/select :model/Card :table_id [:in table-ids] :archived false :type :metric {:order-by [[:name :asc]]}))++(defn transforms-by-id+ "A map of ID to Transform for `transform-ids`."+ [transform-ids]+ (t2/select-fn->fn :id identity :model/Transform :id [:in transform-ids]))++;;; ------------------------------------------------ Database ------------------------------------------------++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn databases-by-id+ "A map of ID to Database for `database-ids`."+ [database-ids]+ (t2/select-pk->fn identity :model/Database :id [:in database-ids]))++(defn database-engine+ "The engine of the Database with `database-id`."+ [database-id]+ (t2/select-one-fn :engine :model/Database :id database-id))++(defn database-name+ "The name of the Database with `database-id`."+ [database-id]+ (t2/select-one-fn :name :model/Database :id database-id))++(defn database-id-by-name+ "The ID of the Database named `database-name`, or nil."+ [database-name]+ (t2/select-one-pk :model/Database :name database-name))++;;; ---------------------------------------------- Other models ----------------------------------------------++(defn collections+ "The Collections with `collection-ids`."+ [collection-ids]+ (t2/select :model/Collection :id [:in collection-ids]))++(defn user-summaries-by-id+ "A map of ID to the ID, email, and names of the Users with `user-ids`."+ [user-ids]+ (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name] :id [:in user-ids]))++(defn cards-with-moderated-status+ "The query-metadata columns of the Cards with `card-ids`, with their latest moderation status."+ [card-ids]+ (t2/select :model/Card+ {:select [:c.id :c.dataset_query :c.result_metadata :c.name+ :c.description :c.collection_id :c.database_id :c.type+ :c.source_card_id :c.created_at :c.entity_id :c.card_schema+ [:r.status :moderated_status]]+ :from [[:report_card :c]]+ :left-join [[^:allow-subquery {:select [:moderated_item_id :status]+ :from [:moderation_review]+ :where [:and+ [:= :moderated_item_type "card"]+ [:= :most_recent true]]+ :order-by [[:id :desc]]+ :limit 1} :r]+ [:= :r.moderated_item_id :c.id]]+ :where [:in :c.id card-ids]}))diff --git a/src/metabase/warehouse_schema/field.clj b/src/metabase/warehouse_schema/field.cljindex f4c743be7ab..b3e3539ade4 100644--- a/src/metabase/warehouse_schema/field.clj+++ b/src/metabase/warehouse_schema/field.clj@@ -4,13 +4,14 @@[metabase.models.interface :as mi][metabase.permissions.core :as perms][metabase.util :as u]+ [metabase.warehouse-schema.db :as warehouse-schema.db][metabase.warehouse-schema.models.field :as field][toucan2.core :as t2]))(defn get-field"Get `Field` with ID."[id {:keys [include-editable-data-model?]}]- (let [field (-> (api/check-404 (t2/select-one :model/Field :id id))+ (let [field (-> (api/check-404 (warehouse-schema.db/field id))(t2/hydrate [:table :db] :has_field_values :dimensions :name_field))field (if include-editable-data-model?(field/hydrate-target-with-write-perms field)@@ -39,7 +40,7 @@"Get `Field`s with IDs in `ids`."[ids](when (seq ids)- (let [fields (t2/select :model/Field :id [:in ids])]+ (let [fields (warehouse-schema.db/fields ids)](prime-table-perms-for-fields! fields)(-> (filter mi/can-read? fields)(t2/hydrate :has_field_values [:dimensions :human_readable_field] :name_field)))))@@ -48,8 +49,7 @@"Get sorted unique table IDs for readable Fields with IDs in `ids`."[ids](->> (when (seq ids)- (u/prog1 (t2/hydrate (t2/select [:model/Field :id :table_id] :id [:in ids])- :table)+ (u/prog1 (t2/hydrate (warehouse-schema.db/field-table-id-rows ids) :table)(prime-table-perms-for-fields! <>)))(filter mi/can-read?)(keep :table_id)diff --git a/src/metabase/warehouse_schema/field_values/distinct_batch.clj b/src/metabase/warehouse_schema/field_values/distinct_batch.cljindex 24535281d48..8b4f2190a23 100644--- a/src/metabase/warehouse_schema/field_values/distinct_batch.clj+++ b/src/metabase/warehouse_schema/field_values/distinct_batch.clj@@ -37,8 +37,8 @@[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]))+ [metabase.warehouse-schema.db :as warehouse-schema.db]+ [metabase.warehouse-schema.models.field-values :as field-values]))(set! *warn-on-reflection* true)@@ -137,7 +137,7 @@(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))+ driver (:engine (warehouse-schema.db/database db-id))fields (vec fields)hsql (build-union driver table fields)[sql & params] (sql.qp/format-honeysql driver hsql)diff --git a/src/metabase/warehouse_schema/metadata_from_qp.clj b/src/metabase/warehouse_schema/metadata_from_qp.cljindex 2012c28c226..e6f8891b109 100644--- a/src/metabase/warehouse_schema/metadata_from_qp.clj+++ b/src/metabase/warehouse_schema/metadata_from_qp.clj@@ -12,6 +12,7 @@[metabase.query-processor.schema :as qp.schema][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]+ [metabase.warehouse-schema.db :as warehouse-schema.db][metabase.warehouse-schema.metadata-queries :as schema.metadata-queries][toucan2.core :as t2]))@@ -27,7 +28,7 @@query-xform :- [:=> [:cat ::lib.schema/query] ::lib.schema/query]rff :- [:maybe ::qp.schema/rff]]{:pre [(pos-int? table-id)]}- (let [database-id (t2/select-one-fn :db_id :model/Table table-id)+ (let [database-id (warehouse-schema.db/table-database-id table-id)mp (lib-be/application-database-metadata-provider database-id)query (-> (lib/query mp (lib.metadata/table mp table-id))query-xformdiff --git a/src/metabase/warehouse_schema/metadata_queries.clj b/src/metabase/warehouse_schema/metadata_queries.cljindex f218912c9e3..326f782ef11 100644--- a/src/metabase/warehouse_schema/metadata_queries.clj+++ b/src/metabase/warehouse_schema/metadata_queries.clj@@ -9,7 +9,7 @@[metabase.lib.schema.metadata :as lib.schema.metadata][metabase.parameters.schema :as parameters.schema][metabase.util.malli :as mu]- [toucan2.core :as t2]))+ [metabase.warehouse-schema.db :as warehouse-schema.db]))(mu/defn- partition-field->filter-form :- :mbql.clause/>"Given a partition field, returns the default value can be used to query."@@ -51,10 +51,5 @@"Get the human readable (internally mapped) values of the field specified by `field-id`."[field-id :- pos-int?](let [{orig :values, remapped :human_readable_values}- (t2/select-one [:model/FieldValues :values :human_readable_values]- {:where [:and- [:= :type "full"]- [:= :field_id field-id]- [:not= :human_readable_values nil]- [:not= :human_readable_values "{}"]]})]+ (warehouse-schema.db/full-field-values-with-human-readable-values field-id)](some->> (seq remapped) (zipmap orig))))diff --git a/src/metabase/warehouse_schema/models/field.clj b/src/metabase/warehouse_schema/models/field.cljindex d3ecf82ebe8..38f4d2a0f11 100644--- a/src/metabase/warehouse_schema/models/field.clj+++ b/src/metabase/warehouse_schema/models/field.clj@@ -1,7 +1,6 @@(ns metabase.warehouse-schema.models.field(:require[clojure.string :as str]- [honey.sql :as sql][medley.core :as m][metabase.app-db.core :as mdb][metabase.lib.core :as lib]@@ -17,6 +16,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]+ [metabase.warehouse-schema.db :as warehouse-schema.db][metabase.warehouse-schema.models.field-values :as field-values][metabase.warehouses.models.database :as database][methodical.core :as methodical]@@ -162,21 +162,13 @@:caveats :points_of_interest :nfc_path :json_unfolding :settings})(defn- ensure-field-user-settings-exist-for-fk-target-field [field]- (let [q {:select [:id]- :from [:metabase_field]- :where [:and- [:= :fk_target_field_id (:id field)]- [:not [:exists ^:allow-subquery {:select [1]- :from [:metabase_field_user_settings]- :where [:= :metabase_field_user_settings.field_id :metabase_field.id]}]]]}- sql (sql/format q :dialect (mdb/quoting-style (mdb/db-type)))]- (t2/insert! :model/FieldUserSettings- (map (fn [{:keys [id]}] {:field_id id})- (t2/query sql)))))+ (warehouse-schema.db/insert-field-user-settings!+ (map (fn [{:keys [id]}] {:field_id id})+ (warehouse-schema.db/fk-source-field-ids-without-user-settings (:id field)))))(defn- sync-user-settings [field];; we transparently prevent updates that would override user-set values- (let [user-settings (t2/select-one :model/FieldUserSettings (:id field))+ (let [user-settings (warehouse-schema.db/field-user-settings (:id field))updated-field (-> (merge field (u/select-keys-when user-settings :non-nil field-user-settings));; GHY-3388 invariant: enforce coercion_strategy=nil ⇒ effective_type=base_type;; AFTER the user-settings merge, since the overlay can introduce stale effective_type@@ -187,12 +179,9 @@[field](when (false? (:active (t2/changes field)))(ensure-field-user-settings-exist-for-fk-target-field field)- (let [k {:fk_target_field_id (:id field)}- upds {:semantic_type nil- :fk_target_field_id nil}]- (t2/update! :model/Field k upds)- ;; we must explicitly clear user-set fks in this case- (t2/update! :model/FieldUserSettings k upds)))+ (warehouse-schema.db/clear-fk-targets-to-field! (:id field))+ ;; we must explicitly clear user-set fks in this case+ (warehouse-schema.db/clear-user-settings-fk-targets-to-field! (:id field)))(sync-user-settings field))(t2/define-before-delete :model/Field@@ -200,27 +189,27 @@;; Cascading deletes through parent_id cannot be done with foreign key constraints in the database;; because parent_id contributes to a generated column, and MySQL doesn't support columns with cascade delete;; foreign key constraints in generated columns. #44866- (t2/delete! :model/Field :parent_id (:id field)))+ (warehouse-schema.db/delete-child-fields! (:id field)))(defn- field->table"Get the Table for a Field, either from hydration or by fetching."[instance](or (:table instance)- (t2/select-one :model/Table :id (:table_id instance))))+ (warehouse-schema.db/table (:table_id instance))))(defmethod mi/can-read? :model/Field;; Field permissions delegate to the parent Table. User can read this field if they can read its table.([instance](mi/can-read? (field->table instance)))- ([model pk]- (mi/can-read? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-read? (warehouse-schema.db/field pk))))(defmethod mi/can-query? :model/Field;; Field permissions delegate to the parent Table. User can query this field if they can query its table.([instance](mi/can-query? (field->table instance)))- ([model pk]- (mi/can-query? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-query? (warehouse-schema.db/field pk))))(defenterprise current-user-can-write-field?"OSS implementation. Returns a boolean whether the current user can write the given field.@@ -229,15 +218,15 @@metabase-enterprise.advanced-permissions.common[instance](let [table (or (:table instance)- (t2/select-one :model/Table :id (:table_id instance)))]+ (warehouse-schema.db/table (:table_id instance)))](and (remote-sync/table-editable? table)(mi/superuser?))))(defmethod mi/can-write? :model/Field([instance](current-user-can-write-field? instance))- ([model pk]- (mi/can-write? (t2/select-one model pk))))+ ([_model pk]+ (mi/can-write? (warehouse-schema.db/field pk))))(methodical/defmethod t2/batched-hydrate [:model/Field :can_write]"Batched hydration for :can_write on fields. First hydrates :table for all fields,@@ -253,7 +242,7 @@collection-synced-map (if (seq collection-ids)(into {}(map (juxt :id :is_remote_synced))- (t2/select :model/Collection :id [:in collection-ids]))+ (warehouse-schema.db/collections collection-ids)){});; Associate collection info with each field's tablefields-with-collection (for [field fields-with-tables@@ -275,7 +264,7 @@(defn values"Return the `FieldValues` associated with this `field`."[{:keys [id]}]- (t2/select [:model/FieldValues :field_id :values], :field_id id :type :full))+ (warehouse-schema.db/full-field-values-rows id))(mu/defn nested-field-names->field-id :- [:maybe ms/PositiveInt]"Recursively find the field id for a nested field name, return nil if not found.@@ -288,25 +277,22 @@field-id nil](if (seq field-names)(let [field-name (first field-names)- field-id (t2/select-one-pk :model/Field :name field-name :parent_id field-id :table_id table-id)]+ field-id (warehouse-schema.db/field-id-by-name table-id field-id field-name)](if field-id(recur (rest field-names) field-id)nil))field-id)))-(defn- select-field-id->instance- "Select instances of `model` related by `field_id` FK to a Field in `fields`, and return a map of Field ID -> model- instance. This only returns a single instance for each Field! Duplicates are discarded!+(defn- index-by-field-id+ "Call `fetch-fn` with the IDs of `fields` and return a map of Field ID -> the fetched instance related to it by its+ `field_id` FK. This only returns a single instance for each Field! Duplicates are discarded!- (select-field-id->instance [(Field 1) (Field 2)] FieldValues)- ;; -> {1 #FieldValues{...}, 2 #FieldValues{...}}-- (select-field-id->instance [(Field 1) (Field 2)] FieldValues :type :full)- -> returns Fieldvalues of type :full for fields: [(Field 1) (Field 2)] "- [fields model & conditions]+ (index-by-field-id [(Field 1) (Field 2)] warehouse-schema.db/dimensions-for-fields)+ ;; -> {1 #Dimension{...}, 2 #Dimension{...}}"+ [fields fetch-fn](let [field-ids (set (map :id fields))](m/index-by :field_id (when (seq field-ids)- (apply t2/select model :field_id [:in field-ids] conditions)))))+ (fetch-fn field-ids)))))(mi/define-batched-hydration-method with-values:values@@ -316,7 +302,7 @@;; with Field. See the doc in [[metabase.warehouse-schema.models.field-values]] for more.;; We filter down to only :type =:full values, as they contain configured labels which must be preserved. The Advanced;; FieldValues can then be regenerated without loss given these Full entities.- (let [id->field-values (select-field-id->instance fields :model/FieldValues :type :full)]+ (let [id->field-values (index-by-field-id fields #(warehouse-schema.db/full-field-values-by-field :model/FieldValues %))](for [field fields](assoc field :values (get id->field-values (:id field) [])))))@@ -324,9 +310,10 @@:normal_values"Efficiently hydrate the `FieldValues` for visibility_type normal `fields`."[fields]- (let [id->field-values (select-field-id->instance (filter field-values/field-should-have-field-values? fields)- [:model/FieldValues :id :human_readable_values :values :field_id]- :type :full)]+ (let [id->field-values (index-by-field-id (filter field-values/field-should-have-field-values? fields)+ #(warehouse-schema.db/full-field-values-by-field+ [:model/FieldValues :id :human_readable_values :values :field_id]+ %))](for [field fields](assoc field :values (get id->field-values (:id field) [])))))@@ -342,7 +329,7 @@vector with the matching Dimension, or an empty vector. At least the response shape is consistent now. Maybe in thefuture we can change this key to `:dimension` and return it that way. -- Cam"[fields]- (let [id->dimensions (select-field-id->instance fields :model/Dimension)]+ (let [id->dimensions (index-by-field-id fields warehouse-schema.db/dimensions-for-fields)](for [field fields:let [dimension (get id->dimensions (:id field))]](assoc field :dimensions (if dimension [dimension] [])))))@@ -401,7 +388,7 @@(:fk_target_field_id field))](:fk_target_field_id field)))id->target-field (m/index-by :id (when (seq target-field-ids)- (readable-fields-only (t2/select :model/Field :id [:in target-field-ids]))))]+ (readable-fields-only (warehouse-schema.db/fields target-field-ids))))](for [field fields:let [target-id (:fk_target_field_id field)]](assoc field :target (id->target-field target-id)))))@@ -411,7 +398,7 @@[field](let [target-field-id (when (isa? (:semantic_type field) :type/FK)(:fk_target_field_id field))- target-field (when-let [target-field (and target-field-id (t2/select-one :model/Field :id target-field-id))]+ target-field (when-let [target-field (and target-field-id (warehouse-schema.db/field target-field-id))](when (mi/can-write? (t2/hydrate target-field :table))target-field))](assoc field :target target-field)))@@ -419,9 +406,9 @@(defn qualified-name-components"Return the pieces that represent a path to `field`, of the form `[table-name parent-fields-name* field-name]`."[{field-name :name, table-id :table_id, parent-id :parent_id}]- (conj (vec (if-let [parent (t2/select-one :model/Field :id parent-id)]+ (conj (vec (if-let [parent (warehouse-schema.db/field parent-id)](qualified-name-components parent)- (let [{table-name :name, schema :schema} (t2/select-one ['Table :name :schema], :id table-id)]+ (let [{table-name :name, schema :schema} (warehouse-schema.db/table-name-and-schema table-id)](conj (when schema[schema])table-name))))@@ -437,7 +424,7 @@(mdb/memoize-for-application-db(fn [field-id]{:pre [(integer? field-id)]}- (t2/select-one-fn :table_id :model/Field, :id field-id))))+ (warehouse-schema.db/field-table-id field-id))))(defn field-id->database-id"Return the ID of the Database this Field belongs to."@@ -450,15 +437,13 @@"Return the `Table` associated with this `Field`."{:arglists '([field])}[{:keys [table_id]}]- (t2/select-one 'Table, :id table_id))+ (warehouse-schema.db/table table_id))(methodical/defmethod t2/batched-hydrate [:model/Field :parent][_model k fields](mi/instances-with-hydrated-datafields k- #(t2/select-fn->fn :id identity- :model/Field- :id [:in (map :parent_id fields)])+ #(warehouse-schema.db/fields-by-id (map :parent_id fields)):parent_id));;; ------------------------------------------------- Serialization -------------------------------------------------@@ -477,9 +462,8 @@(defmethod serdes/load-find-local "Field"[path](let [[table-path fields] (split-with #(not= "Field" (:model %)) path)- table (serdes/load-find-local table-path)- field-q (serdes/recursively-find-field-q (:id table) (map :id (reverse fields)))]- (t2/select-one :model/Field field-q)))+ table (serdes/load-find-local table-path)]+ (warehouse-schema.db/field-in-path (:id table) (map :id (reverse fields)))))(defmethod serdes/deserialization-dependencies "Field" [field](let [db-path (first (serdes/path field))]diff --git a/src/metabase/warehouse_schema/models/field_user_settings.clj b/src/metabase/warehouse_schema/models/field_user_settings.cljindex c1d7c7533ae..14ecd4aa091 100644--- a/src/metabase/warehouse_schema/models/field_user_settings.clj+++ b/src/metabase/warehouse_schema/models/field_user_settings.clj@@ -3,6 +3,7 @@[metabase.models.interface :as mi][metabase.models.serialization :as serdes][metabase.util :as u]+ [metabase.warehouse-schema.db :as warehouse-schema.db][metabase.warehouse-schema.models.field :as field][methodical.core :as methodical][toucan2.core :as t2]))@@ -30,9 +31,9 @@"Upsert FieldUserSettings"[{:keys [id]} settings](let [filtered-settings (u/select-keys-when settings :present field/field-user-settings)]- (when-not (t2/exists? :model/FieldUserSettings id)- (t2/insert! :model/FieldUserSettings {:field_id id}))- (t2/update! :model/FieldUserSettings id filtered-settings)))+ (when-not (warehouse-schema.db/field-user-settings-exist? id)+ (warehouse-schema.db/insert-field-user-settings! {:field_id id}))+ (warehouse-schema.db/update-field-user-settings! id filtered-settings)))(defmethod serdes/entity-id "FieldUserSettings" [_ _] nil)@@ -47,7 +48,7 @@(defmethod serdes/load-find-local "FieldUserSettings" [path];; Delegate to finding the parent Field, then look up its corresponding FieldUserSettings.(let [field (serdes/load-find-local (pop path))]- (t2/select-one :model/FieldUserSettings :field_id (:id field))))+ (warehouse-schema.db/field-user-settings (:id field))))(defn- field-path->field-ref [field-values-path](let [[db schema table field :as field-ref] (map :id (pop field-values-path))]diff --git a/src/metabase/warehouse_schema/models/field_values.clj b/src/metabase/warehouse_schema/models/field_values.cljindex 41b2ca386b5..ae2375a7539 100644--- a/src/metabase/warehouse_schema/models/field_values.clj+++ b/src/metabase/warehouse_schema/models/field_values.clj@@ -42,6 +42,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]+ [metabase.warehouse-schema.db :as warehouse-schema.db][methodical.core :as methodical][toucan2.core :as t2]))@@ -146,13 +147,12 @@(defn clear-advanced-field-values-for-field!"Remove all advanced FieldValues for a `field-or-id`."[field-or-id]- (t2/delete! :model/FieldValues :field_id (u/the-id field-or-id)- :type [:in advanced-field-values-types]))+ (warehouse-schema.db/delete-field-values-of-types! (u/the-id field-or-id) advanced-field-values-types))(defn clear-field-values-for-field!"Remove all FieldValues for a `field-or-id`, including the advanced fieldvalues."[field-or-id]- (t2/delete! :model/FieldValues :field_id (u/the-id field-or-id)))+ (warehouse-schema.db/delete-field-values-for-field! (u/the-id field-or-id)))(t2/define-before-insert :model/FieldValues[{:keys [field_id] :as field-values}]@@ -237,8 +237,7 @@(t/after? (:last_used_at field-values)cutoff);; Double check that there are no other variants of Fieldvalues (e.g. advanced) that have not been used more recently- (t/after? (t2/select-one-fn :max-last-used-at [:model/FieldValues [[:max :last_used_at] :max-last-used-at]]- {:where [:= :field_id (:field_id field-values)]})+ (t/after? (warehouse-schema.db/field-values-last-used-at (:field_id field-values))cutoff))))))(defn field-should-have-field-values?@@ -246,7 +245,7 @@[field-or-field-id](if-not (map? field-or-field-id)(let [field-id (u/the-id field-or-field-id)]- (recur (or (t2/select-one ['Field :base_type :visibility_type :has_field_values :preview_display] :id field-id)+ (recur (or (warehouse-schema.db/field-values-eligibility field-id)(throw (ex-info (tru "Field {0} does not exist." field-id){:field-id field-id, :status-code 404})))))(let [{base-type :base_type@@ -415,7 +414,7 @@(mapcat rest)(map :id))](when (seq to-delete-fv-ids)- (t2/delete! :model/FieldValues :id [:in to-delete-fv-ids]))+ (warehouse-schema.db/delete-field-values! to-delete-fv-ids))(update-vals fvs-grouped-by-field-id first)))(defn- get-latest-field-values@@ -423,7 +422,7 @@This may implicitly delete shadowed entries in the database, see [[delete-duplicates-and-return-latest!]]"[field-id type hash](assert (= (nil? hash) (= type :full)) ":hash_key must be nil iff :type is :full")- (-> (t2/select :model/FieldValues :field_id field-id :type type :hash_key hash)+ (-> (warehouse-schema.db/field-values-of-type field-id type hash)delete-duplicates-and-return-latest!(get field-id)))@@ -447,7 +446,7 @@(delete-duplicates-and-return-latest!(when (seq field-ids)(mapcat (fn [batch]- (t2/select :model/FieldValues :field_id [:in batch] :type :full :hash_key nil))+ (warehouse-schema.db/full-field-values-for-fields batch))(partition-all *fv-select-batch-size* field-ids)))))(defn persist-field-values!@@ -496,11 +495,11 @@: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)}))+ (warehouse-schema.db/update-field-values! (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!@@ -539,10 +538,10 @@(do(when existing- (t2/update! :model/FieldValues (:id existing) {:last_used_at :%now}))+ (warehouse-schema.db/touch-field-values! (:id existing)))(get-latest-full-field-values field-id)))(do- (t2/update! :model/FieldValues (:id existing) {:last_used_at :%now})+ (warehouse-schema.db/touch-field-values! (:id existing))existing)))));;; +----------------------------------------------------------------------------------------------------------------+diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.cljindex b42516e8d2e..06d5ca76496 100644--- a/src/metabase/warehouse_schema/models/table.clj+++ b/src/metabase/warehouse_schema/models/table.clj@@ -1,7 +1,6 @@(ns metabase.warehouse-schema.models.table(:require[metabase.api.common :as api]- [metabase.app-db.core :as app-db][metabase.audit-app.core :as audit][metabase.collections.models.collection :as collection][metabase.driver :as driver]@@ -15,6 +14,7 @@[metabase.util :as u][metabase.util.log :as log][metabase.util.malli :as mu]+ [metabase.warehouse-schema.db :as warehouse-schema.db][methodical.core :as methodical][toucan2.core :as t2]))@@ -176,7 +176,7 @@;; reasserts matching DB-level defaults for non-model insert paths.(let [defaults {:display_name (humanization/name->human-readable-name (:name table)):field_order (or (:field_order table)- (driver/default-field-order (t2/select-one-fn :engine :model/Database :id (:db_id table))))+ (driver/default-field-order (warehouse-schema.db/database-engine (:db_id table)))):data_layer :internal:data_authority :unconfigured}](collection/check-allowed-content :table (:collection_id table))@@ -186,7 +186,7 @@[table];; We need to use toucan to delete the fields instead of cascading deletes because MySQL doesn't support columns with cascade delete;; foreign key constraints in generated columns. #44866- (t2/delete! :model/Field :table_id (:id table)))+ (warehouse-schema.db/delete-fields-for-table! (:id table)))(t2/define-before-update :model/Table[table]@@ -318,7 +318,7 @@(:db_id instance)(:id instance))))([_ pk]- (mi/can-read? (t2/select-one :model/Table pk))))+ (mi/can-read? (warehouse-schema.db/table pk))))(defmethod mi/can-query? :model/Table;; Check if user can execute queries against this table.@@ -343,7 +343,7 @@;; Can access via published collection (EE feature)(perms/can-access-via-collection? instance)))))([_ pk]- (mi/can-query? (t2/select-one :model/Table pk))))+ (mi/can-query? (warehouse-schema.db/table pk))))(defenterprise current-user-can-write-table?"OSS implementation. Returns a boolean whether the current user can write the given table.@@ -360,7 +360,7 @@([instance](current-user-can-write-table? instance))([_ pk]- (mi/can-write? (t2/select-one :model/Table pk))))+ (mi/can-write? (warehouse-schema.db/table pk))))(methodical/defmethod t2/batched-hydrate [:model/Table :can_write]"Batched hydration for :can_write on tables. Pre-fetches collection is_remote_synced values@@ -374,7 +374,7 @@collection-synced-map (if (seq collection-ids)(into {}(map (juxt :id :is_remote_synced))- (t2/select :model/Collection :id [:in collection-ids]))+ (warehouse-schema.db/collections collection-ids)){});; Associate collection info with each table so table-editable? doesn't need to querytables-with-collection (for [table tables]@@ -396,8 +396,7 @@tables(let [owner-user-ids (into #{} (keep :owner_user_id) tables)id->owner (when (seq owner-user-ids)- (t2/select-pk->fn identity [:model/User :id :email :first_name :last_name]- :id [:in owner-user-ids]))]+ (warehouse-schema.db/user-summaries-by-id owner-user-ids))](for [table tables](assoc table :owner(cond@@ -427,35 +426,23 @@(def field-order-rule"How should we order fields."- [[:position :asc] [:%lower.name :asc]])+ warehouse-schema.db/field-order-rule)(defn update-field-positions!"Update `:position` of field belonging to table `table` accordingly to `:field_order`"[table](doall(map-indexed (fn [new-position field]- (t2/update! :model/Field (u/the-id field) {:position new-position}))+ (warehouse-schema.db/update-field! (u/the-id field) {:position new-position}));; Can't use `select-field` as that returns a set while we need an ordered list- (t2/select [:model/Field :id]- :table_id (u/the-id table)- {:order-by (case (:field_order table)- :custom [[:custom_position :asc]]- :smart [[[:case- (app-db/isa :semantic_type :type/PK) 0- (app-db/isa :semantic_type :type/Name) 1- (app-db/isa :semantic_type :type/Temporal) 2- :else 3]- :asc]- [:%lower.name :asc]]- :database [[:database_position :asc]]- :alphabetical [[:%lower.name :asc]])}))))+ (warehouse-schema.db/field-ids-for-table-ordered+ (u/the-id table)+ (:field_order table)))))(defn- valid-field-order?"Field ordering is valid if all the fields from a given table are present and only from that table."[table field-ordering]- (= (t2/select-pks-set :model/Field- :table_id (u/the-id table)- :active true)+ (= (warehouse-schema.db/active-field-ids-for-table (u/the-id table))(set field-ordering)))(defn custom-order-fields!@@ -463,11 +450,11 @@[table field-order]{:pre [(valid-field-order? table field-order)]}(t2/with-transaction [_]- (t2/update! :model/Table (u/the-id table) {:field_order :custom})+ (warehouse-schema.db/update-table! (u/the-id table) {:field_order :custom})(dorun(map-indexed (fn [position field-id]- (t2/update! :model/Field field-id {:position position- :custom_position position}))+ (warehouse-schema.db/update-field! field-id {:position position+ :custom_position position}))field-order))));;; --------------------------------------------------- Hydration ----------------------------------------------------@@ -477,12 +464,7 @@[_model k tables](mi/instances-with-hydrated-datatables k- #(-> (group-by :table_id (t2/select [:model/FieldValues :field_id :values :field.table_id]- {:join [[:metabase_field :field] [:= :metabase_fieldvalues.field_id :field.id]]- :where [:and- [:in :field.table_id [(map :id tables)]]- [:= :field.visibility_type "normal"]- [:= :metabase_fieldvalues.type "full"]]}))+ #(-> (group-by :table_id (warehouse-schema.db/full-field-values-for-tables (map :id tables)))(update-vals (fn [fvs] (->> fvs (map (juxt :field_id :values)) (into {}))))):id))@@ -493,8 +475,7 @@tables k#(let [transform-ids (->> tables (keep :transform_id) distinct)id->transform (when (seq transform-ids)- (t2/select-fn->fn :id identity :model/Transform- :id [:in transform-ids]))]+ (warehouse-schema.db/transforms-by-id transform-ids))](into {}(keep (fn [{:keys [id transform_id]}](when transform_id@@ -507,11 +488,7 @@[_model k tables](mi/instances-with-hydrated-datatables k- #(t2/select-fn->fn :table_id :id- :model/Field- :table_id [:in (map :id tables)]- :semantic_type (app-db/isa :type/PK)- :visibility_type [:not-in ["sensitive" "retired"]])+ #(warehouse-schema.db/pk-field-ids-by-table (map :id tables)):id))(defn- with-objects [hydration-key fetch-objects-fn tables]@@ -527,7 +504,7 @@[tables](with-objects :segments(fn [table-ids]- (t2/select :model/Segment :table_id [:in table-ids], :archived false, {:order-by [[:name :asc]]}))+ (warehouse-schema.db/unarchived-segments-for-tables table-ids))tables))(mi/define-batched-hydration-method with-measures@@ -536,7 +513,7 @@[tables](with-objects :measures(fn [table-ids]- (t2/select :model/Measure :table_id [:in table-ids], :archived false, {:order-by [[:name :asc]]}))+ (warehouse-schema.db/unarchived-measures-for-tables table-ids))tables))(mi/define-batched-hydration-method with-metrics@@ -545,11 +522,7 @@[tables](with-objects :metrics(fn [table-ids]- (->> (t2/select :model/Card- :table_id [:in table-ids],- :archived false,- :type :metric,- {:order-by [[:name :asc]]})+ (->> (warehouse-schema.db/unarchived-metric-cards-for-tables table-ids)(filter mi/can-read?)))tables))@@ -558,11 +531,7 @@[tables](with-objects :fields(fn [table-ids]- (t2/select :model/Field- :active true- :table_id [:in table-ids]- :visibility_type [:not= "retired"]- {:order-by field-order-rule}))+ (warehouse-schema.db/active-fields-for-tables table-ids))tables))(mi/define-batched-hydration-method fields@@ -576,7 +545,7 @@(defn database"Return the `Database` associated with this `Table`."[table]- (t2/select-one :model/Database :id (:db_id table)))+ (warehouse-schema.db/database (:db_id table)));;; ------------------------------------------------- Serialization -------------------------------------------------(defmethod serdes/deserialization-dependencies "Table" [{:keys [db_id collection_id transform_id]}]@@ -589,26 +558,18 @@;; On import the parent Field row is synthesized if missing, so FieldUserSettings is self-sufficient.;; Otherwise emit all Field ids for a full serdes backup/restore.fields (if user-edits-only- (into {} (for [fus-field-id (t2/select-fn-set :field_id :model/FieldUserSettings- {:join [[:metabase_field :f] [:= :f.id :field_id]]- :where [:= :f.table_id id]})]+ (into {} (for [fus-field-id (warehouse-schema.db/user-edited-field-ids-for-table id)][["FieldUserSettings" fus-field-id] {"Table" id}]))- (into {} (for [field-id (t2/select-pks-set :model/Field {:where [:= :table_id id]})]+ (into {} (for [field-id (warehouse-schema.db/field-ids-for-table id)][["Field" field-id] {"Table" id}])))- segments (into {} (for [segment-id (t2/select-pks-set :model/Segment- {:where [:and- [:= :table_id id]- (when skip-archived [:not :archived])]})]+ segments (into {} (for [segment-id (warehouse-schema.db/segment-ids-for-table id skip-archived)][["Segment" segment-id] {"Table" id}]))- measures (into {} (for [measure-id (t2/select-pks-set :model/Measure- {:where [:and- [:= :table_id id]- (when skip-archived [:not :archived])]})]+ measures (into {} (for [measure-id (warehouse-schema.db/measure-ids-for-table id skip-archived)][["Measure" measure-id] {"Table" id}]))](merge fields segments measures)))(defmethod serdes/generate-path "Table" [_ table]- (let [db-name (t2/select-one-fn :name :model/Database :id (:db_id table))]+ (let [db-name (warehouse-schema.db/database-name (:db_id table))](filterv some? [{:model "Database" :id db-name}(when (:schema table){:model "Schema" :id (:schema table)})@@ -623,8 +584,8 @@schema-name (when (= 3 (count path))(-> path second :id))table-name (-> path last :id)- db-id (t2/select-one-pk :model/Database :name db-name)]- (t2/select-one :model/Table :name table-name :db_id db-id :schema schema-name)))+ db-id (warehouse-schema.db/database-id-by-name db-name)]+ (warehouse-schema.db/table-by-name db-id schema-name table-name)))(defmethod serdes/make-spec "Table" [_model-name _opts]{:copy [:name :description :entity_type :active :display_name :visibility_type :schemadiff --git a/src/metabase/warehouse_schema/table.clj b/src/metabase/warehouse_schema/table.cljindex ea7406fc238..418a6517514 100644--- a/src/metabase/warehouse_schema/table.clj+++ b/src/metabase/warehouse_schema/table.clj@@ -6,6 +6,7 @@[metabase.permissions.core :as perms][metabase.premium-features.core :as premium-features :refer [defenterprise]][metabase.util :as u]+ [metabase.warehouse-schema.db :as warehouse-schema.db][metabase.warehouse-schema.models.field-values :as field-values][toucan2.core :as t2]))@@ -70,15 +71,11 @@(batch-fetch-query-metadatas* ids nil))([ids {:keys [include-sensitive-fields?]}](when (seq ids)- (let [tables (t2/select :model/Table :id [:in ids])+ (let [tables (warehouse-schema.db/tables ids)_ (perms/prime-table-perms-cache {:db-ids (into #{} (keep :db_id) tables):table-ids (into #{} (map :id) tables)})tables (filter can-access-table-for-query-metadata? tables)- tables (t2/hydrate tables- [:fields [:target :has_field_values] :has_field_values :dimensions :name_field]- :segments- :measures- :metrics)+ tables (t2/hydrate tables [:fields [:target :has_field_values] :has_field_values :dimensions :name_field] :segments :measures :metrics)excluded-visibility-types (cond-> #{:hidden}(not include-sensitive-fields?) (conj :sensitive))](for [table tables]@@ -93,7 +90,7 @@`include-hidden-fields?` and `include-editable-data-model?` can be either booleans or boolean strings."metabase-enterprise.sandbox.api.table[id opts]- (fetch-query-metadata* (t2/select-one :model/Table :id id) opts))+ (fetch-query-metadata* (warehouse-schema.db/table id) opts))(defenterprise batch-fetch-table-query-metadatas"Returns the query metadatas used to power the Query Builder for the tables specified by `ids`.@@ -124,7 +121,7 @@[card-id metadata metadata-fields](let [underlying (m/index-by :id (or metadata-fields(when-let [ids (seq (keep :id metadata))]- (-> (t2/select :model/Field :id [:in ids])+ (-> (warehouse-schema.db/fields ids)(t2/hydrate [:target :has_field_values] :has_field_values :dimensions :name_field)))))fields (for [{col-id :id :as col} metadata](-> col@@ -163,7 +160,7 @@(keep :id))cards)metadata-fields (if (seq metadata-field-ids)- (-> (t2/select :model/Field :id [:in metadata-field-ids])+ (-> (warehouse-schema.db/fields metadata-field-ids)(t2/hydrate [:target :has_field_values] :has_field_values :dimensions :name_field)(->> (m/index-by :id))){})]@@ -196,7 +193,7 @@include-database?(assoc :db (when-let [database (when (int? database_id)(or (get databases database_id)- (t2/select-one :model/Database :id database_id)))]+ (warehouse-schema.db/database database_id)))](when (mi/can-read? database) database)))include-fields?@@ -236,23 +233,9 @@"Return metadata for the 'virtual' tables for a Cards. Unreadable cards are silently skipped."[ids {:keys [include-database?]}](when (seq ids)- (let [cards (t2/select :model/Card- {:select [:c.id :c.dataset_query :c.result_metadata :c.name- :c.description :c.collection_id :c.database_id :c.type- :c.source_card_id :c.created_at :c.entity_id :c.card_schema- [:r.status :moderated_status]]- :from [[:report_card :c]]- :left-join [[^:allow-subquery {:select [:moderated_item_id :status]- :from [:moderation_review]- :where [:and- [:= :moderated_item_type "card"]- [:= :most_recent true]]- :order-by [[:id :desc]]- :limit 1} :r]- [:= :r.moderated_item_id :c.id]]- :where [:in :c.id ids]})+ (let [cards (warehouse-schema.db/cards-with-moderated-status ids)dbs (if (seq cards)- (t2/select-pk->fn identity :model/Database :id [:in (into #{} (map :database_id) cards)])+ (warehouse-schema.db/databases-by-id (into #{} (map :database_id) cards)){})card-id->metadata-fields (cards->card-id->metadata-fields cards)readable-cards (t2/hydrate (filter mi/can-read? cards) :metrics)]diff --git a/src/metabase/warehouse_schema_rest/api/field.clj b/src/metabase/warehouse_schema_rest/api/field.cljindex aab539ea042..82da092fd7b 100644--- a/src/metabase/warehouse_schema_rest/api/field.clj+++ b/src/metabase/warehouse_schema_rest/api/field.clj@@ -15,6 +15,7 @@[metabase.util.i18n :as i18n][metabase.util.malli.schema :as ms][metabase.util.quick-task :as quick-task]+ [metabase.warehouse-schema-rest.db :as warehouse-schema-rest.db][metabase.warehouse-schema.field :as schema.field][metabase.warehouse-schema.metadata-from-qp :as metadata-from-qp][metabase.warehouse-schema.models.field :as field]@@ -69,13 +70,7 @@"Check that `target-field-id` is a valid field in the same database as `source-field-id`. Throws a 400 ifthe target field does not exist or belongs to a different database. Uses a single query."[source-field-id target-field-id param-name]- (let [result (first (t2/query {:select [[:source_t.db_id :source_db_id]- [:target_t.db_id :target_db_id]]- :from [[(t2/table-name :model/Field) :sf]]- :join [[(t2/table-name :model/Table) :source_t] [:= :sf.table_id :source_t.id]- [(t2/table-name :model/Field) :tf] [:= :tf.id target-field-id]- [(t2/table-name :model/Table) :target_t] [:= :tf.table_id :target_t.id]]- :where [:= :sf.id source-field-id]}))]+ (let [result (first (warehouse-schema-rest.db/field-and-target-database-ids source-field-id target-field-id))](api/checkp result param-name "Invalid target field")(api/checkp (= (:source_db_id result) (:target_db_id result))param-name "Target field must belong to the same database")))@@ -90,7 +85,7 @@(defn- clear-dimension-on-fk-change! [{:keys [dimensions], :as _field}](doseq [{dimension-id :id, dimension-type :type} dimensions](when (and dimension-id (= :external dimension-type))- (t2/delete! :model/Dimension :id dimension-id))))+ (warehouse-schema-rest.db/delete-dimension! dimension-id))))(defn- removed-fk-semantic-type? [old-semantic-type new-semantic-type](and (not= old-semantic-type new-semantic-type)@@ -113,7 +108,7 @@(when (and old-dim-id(= :internal old-dim-type)(not (internal-remapping-allowed? base-type new-semantic-type)))- (t2/delete! :model/Dimension :id old-dim-id))))+ (warehouse-schema-rest.db/delete-dimension! old-dim-id))))(defn- update-nested-fields-on-json-unfolding-change!"If JSON unfolding was enabled for a JSON field, it activates previously synced nested fields from the JSON field.@@ -122,20 +117,18 @@[old-field new-json-unfolding](when (not= new-json-unfolding (:json_unfolding old-field))(if new-json-unfolding- (let [update-result (t2/update! :model/Field- :table_id (:table_id old-field)- :nfc_path [:like (str "[\"" (:name old-field) "\",%]")]- {:active true})]+ (let [update-result (warehouse-schema-rest.db/set-nested-fields-active! (:table_id old-field)+ (str "[\"" (:name old-field) "\",%]")+ true)](when (zero? update-result);; Sync the table if no nested fields exist. This means the table hasn't previously;; been synced when JSON unfolding was enabled. This assumes the JSON field is already updated to have;; JSON unfolding enabled.(let [table (field/table old-field)](quick-task/submit-task! (fn [] (sync/sync-table! table))))))- (t2/update! :model/Field- :table_id (:table_id old-field)- :nfc_path [:like (str "[\"" (:name old-field) "\",%]")]- {:active false})))+ (warehouse-schema-rest.db/set-nested-fields-active! (:table_id old-field)+ (str "[\"" (:name old-field) "\",%]")+ false)))nil);; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -189,7 +182,7 @@(when (and display-name(not removed-fk?)(not= (:display_name field) display-name))- (t2/update! :model/Dimension :field_id id {:name display-name}))+ (warehouse-schema-rest.db/rename-dimension-for-field! id display-name));; everything checks out, now update the field(api/check-500(t2/with-transaction [_conn]@@ -201,17 +194,17 @@:effective_type effective-type:coercion_strategy coercion-strategy)](schema.field-user-settings/upsert-user-settings field body)- (t2/update! :model/Field- id- (u/select-keys-when body- {:present #{:caveats :description :fk_target_field_id :points_of_interest :semantic_type- :coercion_strategy :effective_type :has_field_values :nfc_path :json_unfolding}- :non-nil #{:display_name :visibility_type :settings}})))))+ (warehouse-schema-rest.db/update-field!+ id+ (u/select-keys-when body+ {:present #{:caveats :description :fk_target_field_id :points_of_interest :semantic_type+ :coercion_strategy :effective_type :has_field_values :nfc_path :json_unfolding}+ :non-nil #{:display_name :visibility_type :settings}})))))(when (some? json-unfolding)(update-nested-fields-on-json-unfolding-change! field json-unfolding));; return updated field. note the fingerprint on this might be out of date if the task below would replace them;; but that shouldn't matter for the datamodel page- (u/prog1 (-> (t2/select-one :model/Field :id id)+ (u/prog1 (-> (warehouse-schema-rest.db/field id)(t2/hydrate :dimensions :has_field_values)(field/hydrate-target-with-write-perms))(events/publish-event! :event/field-update {:object <> :user-id api/*current-user-id*})@@ -255,21 +248,21 @@(and (= dimension-type "external")human-readable-field-id))[400 "Foreign key based remappings require a human readable field id"])- (let [existing-dimension (t2/select-one :model/Dimension :field_id id)]+ (let [existing-dimension (warehouse-schema-rest.db/dimension-for-field id)](check-can-point-at-field! id human-readable-field-id(:human_readable_field_id existing-dimension):human_readable_field_id)(if-let [dimension existing-dimension]- (t2/update! :model/Dimension (u/the-id dimension)- {:type dimension-type- :name dimension-name- :human_readable_field_id human-readable-field-id})- (t2/insert! :model/Dimension- {:field_id id- :type dimension-type- :name dimension-name- :human_readable_field_id human-readable-field-id})))- (t2/select-one :model/Dimension :field_id id))+ (warehouse-schema-rest.db/update-dimension! (u/the-id dimension)+ {:type dimension-type+ :name dimension-name+ :human_readable_field_id human-readable-field-id})+ (warehouse-schema-rest.db/insert-dimension!+ {:field_id id+ :type dimension-type+ :name dimension-name+ :human_readable_field_id human-readable-field-id})))+ (warehouse-schema-rest.db/dimension-for-field id));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -280,7 +273,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](api/write-check :model/Field id)- (t2/delete! :model/Dimension :field_id id)+ (warehouse-schema-rest.db/delete-dimensions-for-field! id)api/generic-204-no-content);; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -293,7 +286,7 @@`:list`, checks whether we should create FieldValues for this Field; if so, creates and returns them."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (let [field (api/query-check (t2/select-one :model/Field :id id))]+ (let [field (api/query-check (warehouse-schema-rest.db/field id))](parameters.field/field->values field)))(defn- validate-human-readable-pairs@@ -345,7 +338,7 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](analytics/track-event! :snowplow/simple_event {:event "field_manual_scan" :target_id id})- (let [field (api/write-check (t2/select-one :model/Field :id id))]+ (let [field (api/write-check (warehouse-schema-rest.db/field id))];; Grant full permissions so that permission checks pass during sync. If a user has DB detail perms;; but no data perms, they should stll be able to trigger a sync of field values. This is fine because we don't;; return any actual field values from this API. (#21764)@@ -365,7 +358,7 @@Database is set up to automatically sync FieldValues, they will be recreated during the next cycle."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (field-values/clear-field-values-for-field! (api/write-check (t2/select-one :model/Field :id id)))+ (field-values/clear-field-values-for-field! (api/write-check (warehouse-schema-rest.db/field id))){:status :success});;; --------------------------------------------------- Searching ----------------------------------------------------@@ -384,8 +377,8 @@[:value {:optional true} ms/NonBlankString]]](when-not value(api/check-400 (request/limit) "Limit required if value is omitted"))- (let [field (api/check-404 (t2/select-one :model/Field :id id))- search-field (api/check-404 (t2/select-one :model/Field :id search-id))]+ (let [field (api/check-404 (warehouse-schema-rest.db/field id))+ search-field (api/check-404 (warehouse-schema-rest.db/field search-id))](api/check-403 (mi/can-read? field))(api/check-403 (mi/can-read? search-field))(parameters.field/search-values field search-field value (request/limit))))@@ -414,4 +407,4 @@"Return related entities."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (-> (t2/select-one :model/Field :id id) api/read-check xrays/related))+ (-> (warehouse-schema-rest.db/field id) api/read-check xrays/related))diff --git a/src/metabase/warehouse_schema_rest/api/table.clj b/src/metabase/warehouse_schema_rest/api/table.cljindex 12903c4eece..04c62dd08d4 100644--- a/src/metabase/warehouse_schema_rest/api/table.clj+++ b/src/metabase/warehouse_schema_rest/api/table.clj@@ -2,11 +2,9 @@"/api/table endpoints."(:require[clojure.java.io :as io]- [clojure.string :as str][malli.core :as mc][metabase.api.common :as api][metabase.api.macros :as api.macros]- [metabase.app-db.core :as app-db][metabase.collections.core :as collections][metabase.database-routing.core :as database-routing][metabase.driver.settings :as driver.settings]@@ -27,13 +25,13 @@[metabase.sync.core :as sync][metabase.upload.core :as upload][metabase.util :as u]- [metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [deferred-tru tru]][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms][metabase.util.quick-task :as quick-task]+ [metabase.warehouse-schema-rest.db :as warehouse-schema-rest.db][metabase.warehouse-schema.models.table :as table][metabase.warehouse-schema.table :as schema.table][metabase.xrays.core :as xrays]@@ -90,45 +88,20 @@[:can-query {:optional true} [:maybe ms/BooleanValue]][:can-write {:optional true} [:maybe ms/BooleanValue]][:include-transform-targets {:optional true} [:maybe ms/BooleanValue]]]]- (let [db-type (app-db/db-type)- ;; `*` is the user-facing wildcard; everything else in `term` has already been escaped to match literally- glob (fn [escaped]- (-> escaped- (str/replace "*" "%")- (cond-> (not (str/ends-with? term "*")) (str "%"))))- ci-pattern (fn [pattern]- (case db-type- (:h2 :postgres) pattern- [::h2x/collate pattern "utf8mb4_unicode_ci"]))- like (fn [field wrap]- [(case db-type (:h2 :postgres) :ilike :like)- field- (h2x/like-pattern term (comp ci-pattern wrap glob))])- where (cond-> [:and (if include-transform-targets- [:or [:= :active true] [:= :transform_target true]]- [:= :active true])]- (not (str/blank? term)) (conj [:or- (like :name identity)- (like :display_name identity)- ;; match word starts after spaces e.g. 'ite' would match 'Order Item'- (like :display_name #(str "% " %))])- visibility-type (conj [:= :visibility_type visibility-type])- data-layer (conj [:= :data_layer (name data-layer)])- data-source (conj [:= :data_source (name data-source)])- owner-user-id (conj [:= :owner_user_id owner-user-id])- owner-email (conj [:= :owner_email owner-email])- orphan-only (conj [:and [:= :owner_email nil] [:= :owner_user_id nil]])- published-only (conj [:= :is_published true])- (and unused-only (premium-features/has-feature? :dependencies))- (conj [:not-exists ^:allow-subquery {:select [:*]- :from [[:dependency :d]]- :where [:and- [:= :d.to_entity_id :metabase_table.id]- [:= :d.to_entity_type "table"]]}]))- query {:where where, :order-by [[:name :asc]]}- hydrations (cond-> [:db]+ (let [hydrations (cond-> [:db](premium-features/any-transforms-enabled?) (conj :transform))]- (as-> (t2/select :model/Table query) tables+ (as-> (warehouse-schema-rest.db/matching-tables+ {:term term+ :visibility-type visibility-type+ :data-layer data-layer+ :data-source data-source+ :owner-user-id owner-user-id+ :owner-email owner-email+ :orphan-only? orphan-only+ :published-only? published-only+ :check-unused? (and unused-only (premium-features/has-feature? :dependencies))+ :include-transform-targets? include-transform-targets})+ tables(apply t2/hydrate tables hydrations)(do (perms/prime-table-perms-cache {:db-ids (into #{} (keep :db_id) tables):table-ids (into #{} (map :id) tables)})@@ -171,7 +144,7 @@(api.macros/defendpoint :get "/:table-id/data""Get the data for the given table"[{:keys [table-id]} :- [:map [:table-id ms/PositiveInt]]]- (let [table (t2/select-one :model/Table :id table-id)+ (let [table (warehouse-schema-rest.db/table table-id)db-id (:db_id table)](api/query-check table)(qp.store/with-metadata-provider db-id@@ -209,8 +182,8 @@(u/update-some :data_layer keyword)(u/update-some :data_source keyword)not-empty)]- (t2/update! :model/Table id changes))- (let [updated-table (t2/select-one :model/Table :id id)+ (warehouse-schema-rest.db/update-table! id changes))+ (let [updated-table (warehouse-schema-rest.db/table id)changed-field-order? (not= (:field_order updated-table) (:field_order existing-table))](if changed-field-order?(do@@ -227,7 +200,7 @@(quick-task/submit-task!(fn [](doseq [[db-id tables] (group-by :db_id newly-unhidden)]- (let [database (t2/select-one :model/Database db-id)]+ (let [database (warehouse-schema-rest.db/database db-id)];; it's okay to allow testing H2 connections during sync. We only want to disallow you from testing them for the;; purposes of creating a new H2 database.(if (binding [driver.settings/*allow-testing-h2-connections* true@@ -242,14 +215,14 @@(defn- check-can-publish-tables-to-collection- (let [collection (api/check-404 (t2/select-one :model/Collection :id collection-id))]+ (let [collection (api/check-404 (warehouse-schema-rest.db/collection collection-id))](api/check-400 (= (:type collection) collections/library-data-collection-type)(tru "Tables can only be published to Library/Data collections."))(api/check-403 (every? mi/can-query? tables))))(defn- update-tables![ids {:keys [collection_id visibility_type] :as body}]- (let [existing-tables (t2/select :model/Table :id [:in ids])]+ (let [existing-tables (warehouse-schema-rest.db/tables-by-ids ids)](api/check-404 (= (count existing-tables) (count ids)))(run! api/write-check existing-tables)(when collection_id@@ -381,8 +354,8 @@[{:keys [id]} :- [:map[:id ms/PositiveInt]]](api/read-check :model/Table id)- (when-let [field-ids (seq (t2/select-pks-set :model/Field, :table_id id, :visibility_type [:not= "retired"], :active true))]- (for [origin-field (t2/select :model/Field, :fk_target_field_id [:in field-ids], :active true)+ (when-let [field-ids (seq (warehouse-schema-rest.db/active-unretired-field-ids-for-table id))]+ (for [origin-field (warehouse-schema-rest.db/active-fields-targeting field-ids):let [origin-field (t2/hydrate origin-field [:table :db])]:when (and (-> origin-field :table :active)(mi/can-read? origin-field))@@ -392,7 +365,7 @@:origin_id (:id origin-field):origin origin-field:destination_id (:fk_target_field_id origin-field)- :destination (t2/hydrate (t2/select-one :model/Field :id (:fk_target_field_id origin-field)) :table)})))+ :destination (t2/hydrate (warehouse-schema-rest.db/field (:fk_target_field_id origin-field)) :table)})));; TODO (Cam 10/28/25) -- fix this endpoint route to use kebab-case for consistency with the rest of our REST API;;@@ -406,7 +379,7 @@are eligible for FieldValues."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (let [table (api/write-check (t2/select-one :model/Table :id id))]+ (let [table (api/write-check (warehouse-schema-rest.db/table id))](events/publish-event! :event/table-manual-scan {:object table :user-id api/*current-user-id*});; Grant full permissions so that permission checks pass during sync. If a user has DB detail perms;; but no data perms, they should stll be able to trigger a sync of field values. This is fine because we don't@@ -430,9 +403,9 @@this Table's Database is set up to automatically sync FieldValues, they will be recreated during the next cycle."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (api/write-check (t2/select-one :model/Table :id id))- (when-let [field-ids (t2/select-pks-set :model/Field :table_id id)]- (t2/delete! (t2/table-name :model/FieldValues) :field_id [:in field-ids]))+ (api/write-check (warehouse-schema-rest.db/table id))+ (when-let [field-ids (warehouse-schema-rest.db/field-ids-for-table id)]+ (warehouse-schema-rest.db/delete-field-values-for-fields! field-ids)){:status :success});; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -443,7 +416,7 @@"Return related entities."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (-> (t2/select-one :model/Table :id id) api/read-check xrays/related))+ (-> (warehouse-schema-rest.db/table id) api/read-check xrays/related))(api.macros/defendpoint :put "/:id/fields/order" :- [:map[:success [:= true]]]@@ -456,7 +429,7 @@[:sequential ms/PositiveInt][:map [:field_order [:sequential ms/PositiveInt]]]]](let [field-order (if (map? body) (:field_order body) body)]- (-> (t2/select-one :model/Table :id id) api/write-check (table/custom-order-fields! field-order)))+ (-> (warehouse-schema-rest.db/table id) api/write-check (table/custom-order-fields! field-order))){:success true})(mu/defn- update-csv!@@ -547,10 +520,8 @@"Trigger a manual update of the schema metadata for this `Table`."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (let [table (api/check-404 (t2/select-one :model/Table :id id))- database (api/check-404 (t2/select-one :model/Database- :id (:db_id table)- :router_database_id nil))]+ (let [table (api/check-404 (warehouse-schema-rest.db/table id))+ database (api/check-404 (warehouse-schema-rest.db/non-destination-database (:db_id table)))](api/check-403(perms/user-has-permission-for-table?api/*current-user-id*diff --git a/src/metabase/warehouse_schema_rest/db.clj b/src/metabase/warehouse_schema_rest/db.cljnew file mode 100644index 00000000000..1f6e6a554b0--- /dev/null+++ b/src/metabase/warehouse_schema_rest/db.clj@@ -0,0 +1,159 @@+(ns metabase.warehouse-schema-rest.db+ "Application database queries for the warehouse schema REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [clojure.string :as str]+ [metabase.app-db.core :as app-db]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn field-and-target-database-ids+ "The `:source_db_id` and `:target_db_id` of the Fields with `source-field-id` and `target-field-id`."+ [source-field-id target-field-id]+ (t2/query {:select [[:source_t.db_id :source_db_id]+ [:target_t.db_id :target_db_id]]+ :from [[(t2/table-name :model/Field) :sf]]+ :join [[(t2/table-name :model/Table) :source_t] [:= :sf.table_id :source_t.id]+ [(t2/table-name :model/Field) :tf] [:= :tf.id target-field-id]+ [(t2/table-name :model/Table) :target_t] [:= :tf.table_id :target_t.id]]+ :where [:= :sf.id source-field-id]}))++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field :id field-id))++(defn update-field!+ "Apply `changes` to the Field with `field-id`."+ [field-id changes]+ (t2/update! :model/Field field-id changes))++(defn set-nested-fields-active!+ "Set the active flag of the Fields of the Table with `table-id` whose NFC path matches the SQL LIKE+ `nfc-path-pattern`, returning the number updated."+ [table-id nfc-path-pattern active?]+ (t2/update! :model/Field :table_id table-id :nfc_path [:like nfc-path-pattern] {:active active?}))++(defn dimension-for-field+ "The Dimension of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Dimension :field_id field-id))++(defn insert-dimension!+ "Insert the Dimension `row`."+ [row]+ (t2/insert! :model/Dimension row))++(defn update-dimension!+ "Apply `changes` to the Dimension with `id`."+ [id changes]+ (t2/update! :model/Dimension id changes))++(defn rename-dimension-for-field!+ "Set the name of the Dimension of the Field with `field-id`."+ [field-id dimension-name]+ (t2/update! :model/Dimension :field_id field-id {:name dimension-name}))++(defn delete-dimension!+ "Delete the Dimension with `id`."+ [id]+ (t2/delete! :model/Dimension :id id))++(defn delete-dimensions-for-field!+ "Delete the Dimensions of the Field with `field-id`."+ [field-id]+ (t2/delete! :model/Dimension :field_id field-id))++(defn matching-tables+ "The Tables (active, or with `transform_target` when `include-transform-targets?`) matching `term` (a glob pattern+ using `*` as a wildcard, matched against `:name` and `:display_name`), optionally narrowed to `visibility-type`,+ `data-layer`, `data-source`, `owner-user-id`, and/or `owner-email`; restricted to ownerless Tables when+ `orphan-only?`, published Tables when `published-only?`, and (when `check-unused?`) Tables with no dependents,+ ordered by name."+ [{:keys [term visibility-type data-layer data-source owner-user-id owner-email orphan-only? published-only?+ check-unused? include-transform-targets?]}]+ (let [db-type (app-db/db-type)+ glob (fn [escaped]+ (-> escaped+ (str/replace "*" "%")+ (cond-> (not (str/ends-with? term "*")) (str "%"))))+ ci-pattern (fn [pattern]+ (case db-type+ (:h2 :postgres) pattern+ [::h2x/collate pattern "utf8mb4_unicode_ci"]))+ like (fn [field wrap]+ [(case db-type (:h2 :postgres) :ilike :like)+ field+ (h2x/like-pattern term (comp ci-pattern wrap glob))])+ where (cond-> [:and (if include-transform-targets?+ [:or [:= :active true] [:= :transform_target true]]+ [:= :active true])]+ (not (str/blank? term)) (conj [:or+ (like :name identity)+ (like :display_name identity)+ ;; match word starts after spaces e.g. 'ite' would match 'Order Item'+ (like :display_name #(str "% " %))])+ visibility-type (conj [:= :visibility_type visibility-type])+ data-layer (conj [:= :data_layer (name data-layer)])+ data-source (conj [:= :data_source (name data-source)])+ owner-user-id (conj [:= :owner_user_id owner-user-id])+ owner-email (conj [:= :owner_email owner-email])+ orphan-only? (conj [:and [:= :owner_email nil] [:= :owner_user_id nil]])+ published-only? (conj [:= :is_published true])+ check-unused?+ (conj [:not-exists ^:allow-subquery {:select [:*]+ :from [[:dependency :d]]+ :where [:and+ [:= :d.to_entity_id :metabase_table.id]+ [:= :d.to_entity_type "table"]]}]))]+ (t2/select :model/Table {:where where, :order-by [[:name :asc]]})))++(defn tables-by-ids+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn update-table!+ "Apply `changes` to the Table with `table-id`."+ [table-id changes]+ (t2/update! :model/Table table-id changes))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database database-id))++(defn non-destination-database+ "The Database with `database-id` if it is not a routing destination, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id :router_database_id nil))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn active-unretired-field-ids-for-table+ "The ids of the active, unretired Fields of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-pks-set :model/Field, :table_id table-id, :visibility_type [:not= "retired"], :active true))++(defn field-ids-for-table+ "The ids of the Fields of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-pks-set :model/Field :table_id table-id))++(defn active-fields-targeting+ "The active Fields whose FK target is one of `field-ids`."+ [field-ids]+ (t2/select :model/Field, :fk_target_field_id [:in field-ids], :active true))++(defn delete-field-values-for-fields!+ "Delete the FieldValues of the Fields with `field-ids`."+ [field-ids]+ (t2/delete! (t2/table-name :model/FieldValues) :field_id [:in field-ids]))diff --git a/src/metabase/warehouses/db.clj b/src/metabase/warehouses/db.cljnew file mode 100644index 00000000000..4c1a38881c3--- /dev/null+++ b/src/metabase/warehouses/db.clj@@ -0,0 +1,141 @@+(ns metabase.warehouses.db+ "Application database queries for the warehouses module. Every function here is a direct Toucan 2 call with no+ additional logic, so no other namespace in the module runs a query itself (model definitions still use `toucan2.core`)."+ (:require+ [metabase.app-db.core :as mdb]+ [toucan2.core :as t2]))++(defn router-database-id+ "The router Database id of the Database with `database-id`, or nil."+ [database-id]+ (t2/select-one-fn :router_database_id :model/Database :id database-id))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn non-destination-database+ "The Database with `database-id` if it is not a routing destination, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id :router_database_id nil))++(defn databases+ "The Databases with `database-ids`."+ [database-ids]+ (t2/select :model/Database :id [:in database-ids]))++(defn database-by-name+ "The Database named `database-name`, or nil."+ [database-name]+ (t2/select-one :model/Database :name database-name))++(defn set-database-details!+ "Set the connection details of the Database with `database-id`."+ [database-id details]+ (t2/update! :model/Database database-id {:details details}))++(defn set-database-provider-name!+ "Set the provider name of the Database with `database-id`."+ [database-id provider-name]+ (t2/update! :model/Database database-id {:provider_name provider-name}))++(defn health-check-candidate-ids+ "The `:id` of the lowest-id non-audit, non-sample, non-destination Database of each engine."+ []+ (t2/query {:select [[:%min.id :id]]+ :from [(t2/table-name :model/Database)]+ :where [:and+ [:= :is_audit false]+ [:= :is_sample false]+ [:= :router_database_id nil]]+ :group-by [:engine]}))++(defn- table-ids-of-database-query+ [database-id]+ ^:allow-subquery {:from [(t2/table-name :model/Table)], :select [:id], :where [:= :db_id database-id]})++(defn fields-exist-for-database?+ "Whether any Field belongs to a Table of the Database with `database-id`."+ [database-id]+ (t2/exists? :model/Field :table_id [:in (table-ids-of-database-query database-id)]))++(defn delete-childless-fields-for-database!+ "Delete the childless Fields of the Tables of the Database with `database-id`, returning the number deleted."+ [database-id]+ (let [table-ids-query (table-ids-of-database-query database-id)+ extra-clause (if (= (mdb/db-type) :mysql)+ ;; double-wrapped subquery to work around the MySQL restriction on selecting from the+ ;; DELETE target+ [:not-in :id ^:allow-subquery {:select [:parent_id]+ :from [[^:allow-subquery {:select [:parent_id]+ :from [(t2/table-name :model/Field)]+ :where [:and+ [:not= :parent_id nil]+ [:in :table_id table-ids-query]]}+ :parent_fields]]}]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[(t2/table-name :model/Field) :child_field]]+ :where [:= :child_field.parent_id :metabase_field.id]}]])]+ (t2/query-one {:delete-from (t2/table-name :model/Field)+ :where [:and+ [:in :table_id table-ids-query]+ extra-clause]})))++(defn delete-cards-for-database-returning-ids-reducible+ "A reducible that deletes the Cards of the Database with `database-id` and yields their `:id`s (Postgres only)."+ [database-id]+ (t2/reducible-query {:delete-from (t2/table-name :model/Card)+ :where [:= :database_id database-id]+ :returning [:id]}))++(defn card-ids-for-database-reducible+ "A reducible of the `:id`s of the Cards of the Database with `database-id`."+ [database-id]+ (t2/reducible-query {:from [(t2/table-name :model/Card)]+ :select [:id]+ :where [:= :database_id database-id]}))++(defn delete-cards-for-database!+ "Delete the Cards of the Database with `database-id`."+ [database-id]+ (t2/query {:delete-from (t2/table-name :model/Card)+ :where [:= :database_id database-id]}))++(defn disable-uploads-for-all-databases!+ "Disable uploads on every Database that has them enabled."+ []+ (t2/update! :model/Database :uploads_enabled true {:uploads_enabled false :uploads_table_prefix nil :uploads_schema_name nil}))++(defn active-tables-for-database+ "The active Tables of the Database with `database-id`, in case-insensitive display name order."+ [database-id]+ (t2/select :model/Table :db_id database-id :active true {:order-by [[:%lower.display_name :asc]]}))++(defn active-tables-for-databases+ "The active Tables of the Databases with `database-ids`, in database then display name order."+ [database-ids]+ (t2/select :model/Table+ :db_id [:in database-ids]+ :active true+ {:order-by [[:db_id :asc] [:%lower.display_name :asc]]}))++(defn active-table-ids-for-database+ "The ids of the active Tables of the Database with `database-id`, or nil."+ [database-id]+ (t2/select-pks-set :model/Table, :db_id database-id, :active true))++(defn pk-fields-for-tables+ "The primary-key Fields of the Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Field, :table_id [:in table-ids], :semantic_type (mdb/isa :type/PK)))++(defn databases-reducible+ "A reducible of the Databases matching the Honey SQL `where` clause."+ [where]+ (t2/reducible-select :model/Database {:where where}))++(defn table-database-id+ "The Database id of the Table with `table-id`, or nil."+ [table-id]+ (t2/select-one-fn :db_id :model/Table, :id table-id))diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.cljindex 2f683ff05e2..b86ea0fcdda 100644--- a/src/metabase/warehouses/models/database.clj+++ b/src/metabase/warehouses/models/database.clj@@ -27,6 +27,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.quick-task :as quick-task]+ [metabase.warehouses.db :as warehouses.db][metabase.warehouses.provider-detection :as provider-detection][metabase.warehouses.settings :as warehouses.settings][methodical.core :as methodical]@@ -99,7 +100,7 @@:private true} db-id->router-db-id(mdb/memoize-for-application-db(fn [db-id]- (t2/select-one-fn :router_database_id :model/Database :id db-id))))+ (warehouses.db/router-database-id db-id))))(defmethod mi/can-read? :model/Database;; Check if user can see this database's metadata.@@ -185,7 +186,7 @@(not is_attached_dwh)))([_model pk](and (can-write? pk)- (not (:is_attached_dwh (t2/select-one :model/Database :id pk))))))+ (not (:is_attached_dwh (warehouses.db/database pk))))))(mu/defmethod mi/visible-filter-clause :model/Database[_model column-or-exp user-info permission-mapping]@@ -256,7 +257,7 @@(let [keys-remaining (-> test-details keys set)[_ removed _] (data/diff keys-remaining (-> details keys set))](log/infof "Successfully connected, migrating to: %s" (pr-str {:keys keys-remaining :keys-removed removed}))- (t2/update! :model/Database (:id database) {:details test-details})+ (warehouses.db/set-database-details! (:id database) test-details)test-details)(recur tail));; if we go through the list and we can't fine a working detail to test, keep original value@@ -315,7 +316,7 @@(log/info (u/format-color :blue "Provider detection: updating database {:id %d} from '%s' to '%s'"(:id database)(:provider_name database) provider))- (t2/update! :model/Database (:id database) {:provider_name provider})+ (warehouses.db/set-database-provider-name! (:id database) provider)(catch Throwable provider-e(log/warnf "Error during provider detection for database {:id %d}: %s" (:id database) (ex-message provider-e)))))))(when (driver.conn/database-write-data-details lib-db)@@ -342,15 +343,9 @@instances with 3k+ databases exist in the wild, and realizing every Database row (including details decryption)just to pick one per engine would defeat the point."[]- (let [ids (map :id (t2/query {:select [[:%min.id :id]]- :from [(t2/table-name :model/Database)]- :where [:and- [:= :is_audit false]- [:= :is_sample false]- [:= :router_database_id nil]]- :group-by [:engine]}))]+ (let [ids (map :id (warehouses.db/health-check-candidate-ids))](when (seq ids)- (t2/select :model/Database :id [:in ids]))))+ (warehouses.db/databases ids))))(defn check-health!"Health checks databases connected to metabase asynchronously using a thread pool. Only one database per unique@@ -424,34 +419,14 @@{:pre [(pos-int? database-id)]};; Field has `define-before-delete` deleting children, but we'll delete them all at once because they refer same;; database - iteratively, deleting those that no one depends on first- (let [table-ids-query ^:allow-subquery {:from [(t2/table-name :model/Table)]- :select [:id]- :where [:= :db_id database-id]}]- ;; Avoid issuing the DELETE when no Fields exist. Keep this check non-locking: locking an empty range on MySQL- ;; recreates the contention this guard avoids. A concurrent sync can race this check, but the foreign keys preserve- ;; integrity by rejecting the Database deletion if it introduces nested Fields after the transaction snapshot.- (when (t2/exists? :model/Field :table_id [:in table-ids-query])- (let [no-children-clause (if (= (mdb/db-type) :mysql)- ;; double-wrapped subquery to work around the MySQL restriction on selecting from the- ;; DELETE target- [:not-in :id ^:allow-subquery {:select [:parent_id]- :from [[^:allow-subquery {:select [:parent_id]- :from [(t2/table-name :model/Field)]- :where [:and- [:not= :parent_id nil]- [:in :table_id table-ids-query]]}- :parent_fields]]}]- [:not [:exists ^:allow-subquery {:select [1]- :from [[(t2/table-name :model/Field) :child_field]]- :where [:= :child_field.parent_id :metabase_field.id]}]])]- (loop []- (let [deleted (t2/query-one- {:delete-from (t2/table-name :model/Field)- :where [:and- [:in :table_id table-ids-query]- no-children-clause]})]- (when (pos? deleted)- (recur))))))))+ ;; Avoid issuing the DELETE when no Fields exist. Keep this check non-locking: locking an empty range on MySQL+ ;; recreates the contention this guard avoids. A concurrent sync can race this check, but the foreign keys preserve+ ;; integrity by rejecting the Database deletion if it introduces nested Fields after the transaction snapshot.+ (when (warehouses.db/fields-exist-for-database? database-id)+ (loop []+ (let [deleted (warehouses.db/delete-childless-fields-for-database! database-id)]+ (when (pos? deleted)+ (recur))))))(t2/define-before-delete :model/Database[{id :id, driver :engine, :as database}]@@ -468,19 +443,14 @@(partition-all 1000);; mysql and h2 both do not support `returning`, so we do the correct thing for postgres and;; then some sad version for those two- (t2/reducible-query (if (= :postgres (mdb/db-type))- {:delete-from (t2/table-name :model/Card)- :where [:= :database_id id]- :returning [:id]}- {:from [(t2/table-name :model/Card)]- :select [:id]- :where [:= :database_id id]})))+ (if (= :postgres (mdb/db-type))+ (warehouses.db/delete-cards-for-database-returning-ids-reducible id)+ (warehouses.db/card-ids-for-database-reducible id)))(run! (fn [batch];; damn circular deps((requiring-resolve 'metabase.search.core/delete!) :model/Card (map (comp str :id) batch)))))(when (not= :postgres (mdb/db-type))- (t2/query {:delete-from (t2/table-name :model/Card)- :where [:= :database_id id]}))+ (warehouses.db/delete-cards-for-database! id))(try(driver/notify-database-updated driver database)(catch Throwable e@@ -490,7 +460,7 @@"This function maintains the invariant that only one database can have uploads_enabled=true."[db](when (:uploads_enabled db)- (t2/update! :model/Database :uploads_enabled true {:uploads_enabled false :uploads_table_prefix nil :uploads_schema_name nil}))+ (warehouses.db/disable-uploads-for-all-databases!))db)(defn- assert-router-database-id-not-mutated!@@ -634,7 +604,7 @@"Return the `Tables` associated with this `Database`."[{:keys [id]}];; TODO - do we want to include tables that should be `:hidden`?- (t2/select :model/Table :db_id id :active true {:order-by [[:%lower.display_name :asc]]}))+ (warehouses.db/active-tables-for-database id))(methodical/defmethod t2/batched-hydrate [:model/Database :tables]"Batch hydrate `Tables` for the given `Database`."@@ -643,19 +613,16 @@databases k#(group-by :db_id;; TODO - do we want to include tables that should be `:hidden`?- (t2/select :model/Table- :db_id [:in (map :id databases)]- :active true- {:order-by [[:db_id :asc] [:%lower.display_name :asc]]}))+ (warehouses.db/active-tables-for-databases (map :id databases))):id{:default []}))(defn pk-fields"Return all the primary key `Fields` associated with this `database`."[{:keys [id]}]- (let [table-ids (t2/select-pks-set 'Table, :db_id id, :active true)]+ (let [table-ids (warehouses.db/active-table-ids-for-database id)](when (seq table-ids)- (t2/select 'Field, :table_id [:in table-ids], :semantic_type (mdb/isa :type/PK)))))+ (warehouses.db/pk-fields-for-tables table-ids))));;; -------------------------------------------------- JSON Encoder --------------------------------------------------@@ -751,15 +718,14 @@false)(defmethod serdes/extract-query "Database"- [model-name {:keys [where]}]- (t2/reducible-select (keyword "model" model-name)- {:where (cond-> [:and- (or where true)- [:= :router_database_id nil]- ;; never export the sample database, regardless of its driver- [:not= :is_sample true]]- (not *include-h2-in-extract?*)- (conj [:not= :engine "h2"]))}))+ [_model-name {:keys [where]}]+ (warehouses.db/databases-reducible (cond-> [:and+ (or where true)+ [:= :router_database_id nil]+ ;; never export the sample database, regardless of its driver+ [:not= :is_sample true]]+ (not *include-h2-in-extract?*)+ (conj [:not= :engine "h2"]))))(defmethod serdes/entity-id "Database"[_ {:keys [name]}]@@ -771,7 +737,7 @@(defmethod serdes/load-find-local "Database"[[{:keys [id]}]]- (t2/select-one :model/Database :name id))+ (warehouses.db/database-by-name id))(defmethod serdes/storage-path "Database" [{:keys [name]} _];; directory for the database with same-named file inside.@@ -798,7 +764,7 @@(mdb/memoize-for-application-db(fn [table-id]{:pre [(integer? table-id)]}- (t2/select-one-fn :db_id :model/Table, :id table-id))))+ (warehouses.db/table-database-id table-id))));;;; ------------------------------------------------- Search ----------------------------------------------------------diff --git a/src/metabase/warehouses/util.clj b/src/metabase/warehouses/util.cljindex f79cadadfd9..78541d0d7bc 100644--- a/src/metabase/warehouses/util.clj+++ b/src/metabase/warehouses/util.clj@@ -8,7 +8,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.malli.schema :as ms]- [toucan2.core :as t2]))+ [metabase.warehouses.db :as warehouses.db]))(mu/defn get-database"Retrieve database respecting `include-editable-data-model?`, `exclude-uneditable-details?` and `include-mirror-databases?`"@@ -23,8 +23,8 @@[:include-destination-databases? {:optional true :default false} ms/MaybeBooleanValue]]](let [filter-by-data-access? (not (or include-editable-data-model? exclude-uneditable-details?))database (api/check-404 (if include-destination-databases?- (t2/select-one :model/Database :id id)- (t2/select-one :model/Database :id id :router_database_id nil)))+ (warehouses.db/database id)+ (warehouses.db/non-destination-database id)))router-db-id (:router_database_id database)](cond-> databasefilter-by-data-access? api/read-checkdiff --git a/src/metabase/warehouses_rest/api.clj b/src/metabase/warehouses_rest/api.cljindex 63e0fbbd6c6..f139c6a4b38 100644--- a/src/metabase/warehouses_rest/api.clj+++ b/src/metabase/warehouses_rest/api.clj@@ -45,6 +45,7 @@[metabase.util.quick-task :as quick-task][metabase.warehouse-schema.models.field :refer [readable-fields-only]][metabase.warehouse-schema.table :as schema.table]+ [metabase.warehouses-rest.db :as warehouses-rest.db][metabase.warehouses.core :as warehouses][metabase.warehouses.models.database :as database][toucan2.core :as t2]))@@ -72,12 +73,7 @@"Hydrate tables for each database. Optional `can-query?` and `can-write-metadata?` filterscan be applied to filter tables by permission level."[dbs & {:keys [can-query? can-write-metadata?]}]- (let [all-tables (t2/select :model/Table- :active true- :db_id [:in (map :id dbs)]- :visibility_type nil- {:order-by [[:%lower.schema :asc]- [:%lower.display_name :asc]]})+ (let [all-tables (warehouses-rest.db/active-visible-tables-for-databases (map :id dbs))_ (perms/prime-table-perms-cache {:db-ids (into #{} (map :id) dbs)})filtered-tables (cond->> (filter mi/can-read? all-tables)can-query? (filter mi/can-query?)@@ -96,12 +92,7 @@(if (empty? dbs)dbs(let [db-ids (map :id dbs)- rows (t2/query {:select-distinct [:db_id :schema]- :from [(t2/table-name :model/Table)]- :where [:and- [:in :db_id db-ids]- [:= :active true]- [:= :visibility_type nil]]})+ rows (warehouses-rest.db/active-visible-schemas-for-databases db-ids)schemas-by-db (reduce(fn [m {:keys [db_id schema]}](update m db_id (fnil conj []) schema))@@ -209,7 +200,7 @@(:id db))(catch Throwable e(log/errorf "Error determining whether Database supports nested queries: %s" (ex-message e)))))- (t2/select [:model/Database :id :engine]))))+ (warehouses-rest.db/database-engines))))(mu/defn- source-query-cards"Fetch the Cards that can be used as source queries (e.g. presented as virtual tables)."@@ -222,27 +213,15 @@xform)(completing conj #(t2/hydrate % :collection :metrics))[]- (t2/reducible-query {:select [:name :description :database_id :dataset_query :id :collection_id- :result_metadata :type :source_card_id :card_schema- [^:allow-subquery {:select [:status]- :from [:moderation_review]- :where [:and- [:= :moderated_item_type "card"]- [:= :moderated_item_id :report_card.id]- [:= :most_recent true]]- :order-by [[:id :desc]]- :limit 1}- :moderated_status]]- :from [:report_card]- :where (into [:and- [:not= :result_metadata nil]- [:= :archived false]- ;; always return metrics for now- [:in :type [(u/qualified-name card-type) "metric"]]- [:in :database_id ids-of-dbs-that-support-source-queries]- (collection/visible-collection-filter-clause)]- additional-constraints)- :order-by [[:%lower.name :asc]]}))))+ (warehouses-rest.db/source-query-cards-reducible+ (into [:and+ [:not= :result_metadata nil]+ [:= :archived false]+ ;; always return metrics for now+ [:in :type [(u/qualified-name card-type) "metric"]]+ [:in :database_id ids-of-dbs-that-support-source-queries]+ (collection/visible-collection-filter-clause)]+ additional-constraints)))))(mu/defn- source-query-cards-exist?"Truthy if a single Card that can be used as a source query exists."@@ -349,8 +328,7 @@(:clause (mi/visible-filter-clause :model/Database :id user-info {:perms/manage-database :yes}))(:clause (mi/visible-filter-clause :model/Database :id user-info {:perms/manage-table-metadata :yes}))]]base-where)- dbs (t2/select :model/Database {:order-by [:%lower.name :%lower.engine]- :where where-clause})+ dbs (warehouses-rest.db/databases-where where-clause);; everything below walks the list one database at a time_ (perms/prime-database-perms-cache {:db-ids (into #{} (map :id) dbs)})](cond-> (-> dbs add-native-perms-info add-transforms-perms-info)@@ -471,9 +449,9 @@[db include](if-not includedb- (-> (t2/hydrate db (case include- "tables" :tables- "tables.fields" [:tables [:fields [:target :has_field_values] :has_field_values]]))+ (-> (case include+ "tables" (t2/hydrate db :tables)+ "tables.fields" (t2/hydrate db [:tables [:fields [:target :has_field_values] :has_field_values]]))(update :tables (fn [tables](cond->> tables; filter hidden tables@@ -491,8 +469,8 @@:- [:map[:include-destination-databases? {:optional true :default false} ms/MaybeBooleanValue]]](api/check-404 (if (and include-destination-databases? api/*is-superuser?*)- (t2/exists? :model/Database :id id)- (t2/exists? :model/Database :id id :router_database_id nil)))))+ (warehouses-rest.db/database-exists? id)+ (warehouses-rest.db/non-destination-database-exists? id)))))(defn- present-database"Get a single Database with `id`."@@ -631,10 +609,9 @@(defn- db-metadata [id include-hidden? include-editable-data-model? remove_inactive? skip-fields?](let [db (-> (warehouses/get-database id {:include-editable-data-model? include-editable-data-model?})- (t2/hydrate- (if skip-fields?- [:tables :segments :metrics]- [:tables [:fields :has_field_values [:target :has_field_values]] :segments :metrics])))+ ((if skip-fields?+ #(t2/hydrate % [:tables :segments :metrics])+ #(t2/hydrate % [:tables [:fields :has_field_values [:target :has_field_values]] :segments :metrics]))))_ (perms/prime-table-perms-cache {:db-ids #{id}})db (if include-editable-data-model?;; We need to check data model perms after hydrating tables, since this will also filter out tables for@@ -703,13 +680,7 @@;;; --------------------------------- GET /api/database/:id/autocomplete_suggestions ---------------------------------(defn- autocomplete-tables [db-id like-pattern limit]- (t2/select [:model/Table :id :db_id :schema :name]- {:where [:and [:= :db_id db-id]- [:= :active true]- [:like :%lower.name like-pattern]- [:= :visibility_type nil]]- :order-by [[:%lower.name :asc]]- :limit limit}))+ (warehouses-rest.db/autocomplete-tables db-id like-pattern limit))(defn- autocomplete-cards"Returns cards that match the search string in the given database, ordered by id.@@ -720,59 +691,10 @@If the search string contains a number at the start AND text like '123-foo' we match do an exact match on card ID, and a substring match on the card name.If the search string does not start with a number, and is text like 'foo' we match that as a substring on the card name."[database-id search-card-slug include-dashboard-questions?]- (let [search-id (re-find #"\d*" search-card-slug)- search-name (-> (re-matches #"\d*-?(.*)" search-card-slug)- second- (str/replace #"-" " ")- u/lower-case-en)]- (t2/select [:model/Card :id :type :database_id :name :collection_id- [:collection.name :collection_name] :card_schema]- {:where [:and- [:= :report_card.database_id database-id]- [:= :report_card.archived false]- (when-not include-dashboard-questions?- [:= :report_card.dashboard_id nil])- (cond- ;; e.g. search-string = "123"- (and (not-empty search-id) (empty? search-name))- [:like- (h2x/cast (if (= (mdb/db-type) :mysql) :char :text) :report_card.id)- (str search-id "%")]-- ;; e.g. search-string = "123-foo"- (and (not-empty search-id) (not-empty search-name))- [:and- [:= :report_card.id (Integer/parseInt search-id)]- ;; this is a prefix match to be consistent with substring matches on the entire slug- [:like [:lower :report_card.name] (h2x/like-prefix search-name)]]-- ;; e.g. search-string = "foo"- (and (empty? search-id) (not-empty search-name))- [:like [:lower :report_card.name] (h2x/like-substring search-name)])]- :left-join [[:collection :collection] [:= :collection.id :report_card.collection_id]]- ;; prioritize models. This relies of `model` coming before `question` alphabetically, and Tamas pointed- ;; out this is a little brittle. He's right -- once we put v2 Metrics in then we can replace this with a- ;; fancy `CASE` expression or something so we can sort things exactly how we like.- :order-by [[:type :asc]- [:report_card.id :desc]] ; sort by most recently created after sorting by type- :limit 50})))+ (warehouses-rest.db/autocomplete-cards database-id search-card-slug include-dashboard-questions?))(defn- autocomplete-fields [db-id like-pattern limit]- ;; NOTE: measuring showed that this query performance is improved ~4x when adding trgm index in pgsql and ~10x when- ;; adding a index on `lower(metabase_field.name)` for ordering (trgm index having on impact on queries with index).- ;; Pgsql now has an index on that (see migration `v49.2023-01-24T12:00:00`) as other dbms do not support indexes on- ;; expressions.- (t2/select [:model/Field :name :base_type :semantic_type :id :table_id [:table.name :table_name]]- :metabase_field.active true- :%lower.metabase_field/name [:like like-pattern]- :metabase_field.visibility_type [:not-in ["sensitive" "retired"]]- :table.db_id db-id- {:order-by [[[:lower :metabase_field.name] :asc]- [[:lower :table.name] :asc]]- ;; checking for table.active in join makes query faster when there are a lot of inactive tables- :inner-join [[:metabase_table :table] [:and :table.active- [:= :table.id :metabase_field.table_id]]]- :limit limit}))+ (warehouses-rest.db/autocomplete-fields db-id like-pattern limit))(defn- autocomplete-results [tables fields limit](let [tbl-count (count tables)@@ -875,9 +797,7 @@[:id ms/PositiveInt]]](warehouses/get-database id)(perms/prime-table-perms-cache {:db-ids #{id}})- (let [fields (filter mi/can-read? (-> (t2/select [:model/Field :id :name :display_name :table_id :base_type :semantic_type]- :table_id [:in (t2/select-fn-set :id :model/Table, :db_id id)]- :visibility_type [:not-in ["sensitive" "retired"]])+ (let [fields (filter mi/can-read? (-> (warehouses-rest.db/non-sensitive-fields-for-tables (warehouses-rest.db/table-ids-for-database id))(t2/hydrate :table)))](for [{:keys [id name display_name table table_id base_type semantic_type]} fields]{:id id@@ -947,21 +867,20 @@(if valid?;; no error, proceed with creation. If record is inserted successfully, publish a `:database-create` event.;; Throw a 500 if nothing is inserted- (u/prog1 (api/check-500 (first (t2/insert-returning-instances!- :model/Database- (merge- {:name name- :engine engine- :details details-or-error- :is_full_sync is_full_sync- :is_on_demand is_on_demand- :cache_ttl cache_ttl- :provider_name provider_name- :creator_id api/*current-user-id*}- (when schedules- (sync.schedules/schedule-map->cron-strings schedules))- (when (some? auto_run_queries)- {:auto_run_queries auto_run_queries})))))+ (u/prog1 (api/check-500 (warehouses-rest.db/insert-database!+ (merge+ {:name name+ :engine engine+ :details details-or-error+ :is_full_sync is_full_sync+ :is_on_demand is_on_demand+ :cache_ttl cache_ttl+ :provider_name provider_name+ :creator_id api/*current-user-id*}+ (when schedules+ (sync.schedules/schedule-map->cron-strings schedules))+ (when (some? auto_run_queries)+ {:auto_run_queries auto_run_queries}))))(events/publish-event! :event/database-create {:object <> :user-id api/*current-user-id*})(analytics/track-event! :snowplow/database{:event :database-connection-successful@@ -1010,7 +929,7 @@[](api/check-superuser)(sample-data/extract-and-sync-sample-database!)- (t2/select-one :model/Database :is_sample true))+ (warehouses-rest.db/sample-database));;; --------------------------------------------- PUT /api/database/:id ----------------------------------------------@@ -1044,7 +963,7 @@article-noun (str article " " noun)](api/check-400 (not (:router_database_id existing-database))(tru "Cannot configure {0} connection on a destination database" article-noun))- (api/check-400 (not (t2/exists? :model/Database :router_database_id (:id existing-database)))+ (api/check-400 (not (warehouses-rest.db/destination-database-exists-for-router? (:id existing-database)))(tru "Cannot configure {0} connection on a router database" article-noun))(when-not (get overlay-details marker-key)(throw (ex-info (tru "{0} must be set in {1}" marker-name column-name)@@ -1108,7 +1027,7 @@(when (:write-data-connection details)(throw (ex-info (tru "write-data-connection must not be set in details"){:status-code 400})))- (let [existing-database (api/write-check (t2/select-one :model/Database :id id))+ (let [existing-database (api/write-check (warehouses-rest.db/database id));; e2e tests run against the H2 sample database and need to toggle its settings (actions,;; table editing), so the guard is lifted when test endpoints are enabled_ (when (and (:is_sample existing-database)@@ -1195,12 +1114,12 @@(setting/validate-settable-for-db! setting-kw pending-db driver-supports?)(catch Exception e(throw (ex-info (ex-message e) (assoc (ex-data e) :status-code 400) e))))))- (t2/update! :model/Database id updates)+ (warehouses-rest.db/update-database! id updates);; unlike the other fields, folks might want to nil out cache_ttl. it should also only be settable on EE;; with the advanced-config feature enabled.(when (premium-features/enable-cache-granular-controls?)- (t2/update! :model/Database id {:cache_ttl cache_ttl}))- (let [db (t2/select-one :model/Database :id id)]+ (warehouses-rest.db/update-database! id {:cache_ttl cache_ttl}))+ (let [db (warehouses-rest.db/database id)];; the details in db and existing-database have been normalized so they are the same here;; we need to pass through details-changed? which is calculated before detail normalization;; to ensure the pool is invalidated and [[driver-api/secret-value-as-file!]] memoization is cleared@@ -1227,11 +1146,11 @@[:id ms/PositiveInt]]](api/check-superuser)(t2/with-transaction [_conn]- (api/let-404 [db (t2/select-one :model/Database :id id)]+ (api/let-404 [db (warehouses-rest.db/database id)](api/check-403 (mi/can-write? db))- (t2/delete! :model/Database :router_database_id id)+ (warehouses-rest.db/delete-destination-databases! id)(database-routing/delete-associated-database-router! id)- (t2/delete! :model/Database :id id)+ (warehouses-rest.db/delete-database! id)(events/publish-event! :event/database-delete {:object db :user-id api/*current-user-id*})))api/generic-204-no-content)@@ -1291,7 +1210,7 @@(sync-util/set-initial-database-sync-complete! db);; avoid n+1(when-let [table-ids (seq (map :id tables))]- (t2/update! :model/Table {:id [:in table-ids]} {:initial_sync_status "complete"})))+ (warehouses-rest.db/mark-tables-sync-complete! table-ids))){:status :ok});;; ------------------------------------------ POST /api/database/:id/rescan_values -------------------------------------------@@ -1333,12 +1252,7 @@{:status :ok})(defn- delete-all-field-values-for-database! [database-or-id]- (t2/query-one {:delete-from :metabase_fieldvalues- :where [:in :field_id- ^:allow-subquery {:select [:f.id]- :from [[:metabase_field :f]]- :right-join [[:metabase_table :t] [:= :f.table_id :t.id]]- :where [:= :t.db_id (u/the-id database-or-id)]}]}))+ (warehouses-rest.db/delete-field-values-for-database! (u/the-id database-or-id)));; TODO - should this be something like DELETE /api/database/:id/field_values instead?;;@@ -1419,7 +1333,7 @@;; For can-query? and can-write-metadata?, we need to filter based on tables in each schemafilter-schemas-by-tables (fn [schemas](if (or can-query? can-write-metadata?)- (let [tables (t2/select :model/Table :db_id id :active true)+ (let [tables (warehouses-rest.db/active-tables-for-database id)_ (perms/prime-table-perms-cache {:db-ids #{id}})filtered-tables (cond->> tablescan-query? (filter mi/can-query?)@@ -1428,12 +1342,11 @@(filter #(contains? allowed-schemas %) schemas))schemas))](warehouses/get-database id {:include-editable-data-model? include-editable-data-model?})- (->> (t2/select-fn-set :schema :model/Table- :db_id id :active true- (merge- {:order-by [[:%lower.schema :asc]]}- (when clauses- {:where (into [:and] clauses)})))+ (->> (warehouses-rest.db/active-table-schemas id+ (merge+ {:order-by [[:%lower.schema :asc]]}+ (when clauses+ {:where (into [:and] clauses)})))filter-schemasfilter-schemas-by-tables;; for `nil` schemas return the empty string@@ -1504,17 +1417,8 @@(api/read-check :model/Database db-id)(api/check-403 (can-read-schema? db-id schema)))(let [candidate-tables (if include-hidden?- (t2/select :model/Table- :db_id db-id- :schema schema- :active true- {:order-by [[:display_name :asc]]})- (t2/select :model/Table- :db_id db-id- :schema schema- :active true- :visibility_type nil- {:order-by [[:display_name :asc]]}))+ (warehouses-rest.db/active-tables-in-schema db-id schema)+ (warehouses-rest.db/active-visible-tables-in-schema db-id schema))_ (perms/prime-table-perms-cache {:db-ids #{db-id}})filtered-tables (cond->> (if include-editable-data-model?(if-let [f (when config/ee-available?@@ -1618,7 +1522,7 @@:question:additional-constraints [(if (= schema (schema.table/root-collection-schema-name))[:= :collection_id nil]- [:in :collection_id (api/check-404 (not-empty (t2/select-pks-set :model/Collection :name schema)))])])+ [:in :collection_id (api/check-404 (not-empty (warehouses-rest.db/collection-ids-named schema)))])])(map schema.table/card->virtual-table))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to@@ -1630,7 +1534,7 @@[{:keys [id]} :- [:map [:id ms/PositiveInt]]{:keys [connection-type]} :- [:map [:connection-type {:optional true} ::driver.conn/connection-type]]](api/check-superuser)- (let [{:as database :keys [engine]} (api/check-404 (t2/select-one :model/Database :id id))+ (let [{:as database :keys [engine]} (api/check-404 (warehouses-rest.db/database id))connection-type (or connection-type :default)connection-details (driver.conn/details-for-exact-type database connection-type)](api/check-400 connection-details (tru "No {0} connection configured for this database" (name connection-type)))@@ -1655,7 +1559,7 @@:model:additional-constraints [(if (= schema (schema.table/root-collection-schema-name))[:= :collection_id nil]- [:in :collection_id (api/check-404 (not-empty (t2/select-pks-set :model/Collection :name schema)))])])+ [:in :collection_id (api/check-404 (not-empty (warehouses-rest.db/collection-ids-named schema)))])])(map schema.table/card->virtual-table))));;; -------------------------------- GET /api/database/:id/settings-available ------------------------------------diff --git a/src/metabase/warehouses_rest/db.clj b/src/metabase/warehouses_rest/db.cljnew file mode 100644index 00000000000..02defdc708f--- /dev/null+++ b/src/metabase/warehouses_rest/db.clj@@ -0,0 +1,251 @@+(ns metabase.warehouses-rest.db+ "Application database queries for the warehouses REST module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [clojure.string :as str]+ [metabase.app-db.core :as mdb]+ [metabase.util :as u]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2]))++(defn active-visible-tables-for-databases+ "The active, visible Tables of the Databases with `database-ids`, in schema then display name order."+ [database-ids]+ (t2/select :model/Table+ :active true+ :db_id [:in database-ids]+ :visibility_type nil+ {:order-by [[:%lower.schema :asc]+ [:%lower.display_name :asc]]}))++(defn active-visible-schemas-for-databases+ "The distinct Database id and schema of the active, visible Tables of the Databases with `database-ids`."+ [database-ids]+ (t2/query {:select-distinct [:db_id :schema]+ :from [(t2/table-name :model/Table)]+ :where [:and+ [:in :db_id database-ids]+ [:= :active true]+ [:= :visibility_type nil]]}))++(defn database-engines+ "The id and engine of every Database."+ []+ (t2/select [:model/Database :id :engine]))++(defn source-query-cards-reducible+ "A reducible of the Cards, with their moderation status, matching the Honey SQL `where` clause, in+ case-insensitive name order."+ [where]+ (t2/reducible-query {:select [:name :description :database_id :dataset_query :id :collection_id+ :result_metadata :type :source_card_id :card_schema+ [^:allow-subquery {:select [:status]+ :from [:moderation_review]+ :where [:and+ [:= :moderated_item_type "card"]+ [:= :moderated_item_id :report_card.id]+ [:= :most_recent true]]+ :order-by [[:id :desc]]+ :limit 1}+ :moderated_status]]+ :from [:report_card]+ :where where+ :order-by [[:%lower.name :asc]]}))++(defn databases-where+ "The Databases matching the Honey SQL `where` clause, in name then engine order."+ [where]+ (t2/select :model/Database {:order-by [:%lower.name :%lower.engine]+ :where where}))++(defn database-exists?+ "Whether a Database with `database-id` exists."+ [database-id]+ (t2/exists? :model/Database :id database-id))++(defn non-destination-database-exists?+ "Whether a Database with `database-id` that is not a routing destination exists."+ [database-id]+ (t2/exists? :model/Database :id database-id :router_database_id nil))++(defn destination-database-exists-for-router?+ "Whether the Database with `database-id` has routing destinations."+ [database-id]+ (t2/exists? :model/Database :router_database_id database-id))++(defn autocomplete-tables+ "Up to `limit` id, Database id, schema, and name rows of the active, visible Tables of the Database with+ `database-id` whose lower-cased name matches the SQL LIKE `like-pattern`, in name order."+ [database-id like-pattern limit]+ (t2/select [:model/Table :id :db_id :schema :name]+ {:where [:and [:= :db_id database-id]+ [:= :active true]+ [:like :%lower.name like-pattern]+ [:= :visibility_type nil]]+ :order-by [[:%lower.name :asc]]+ :limit limit}))++(defn- autocomplete-cards-search-clause+ "`search-card-slug` should be in a format like '123-foo-bar' or '123' or 'foo-bar', where 123 is the card ID+ and foo-bar is a prefix of the card name converted into a slug.++ If the search string contains a number like '123' we match that as a prefix against the card IDs.+ If the search string contains a number at the start AND text like '123-foo' we match do an exact match on card ID,+ and a substring match on the card name.+ If the search string does not start with a number, and is text like 'foo' we match that as a substring on the card+ name."+ [search-card-slug]+ (let [search-id (re-find #"\d*" search-card-slug)+ search-name (-> (re-matches #"\d*-?(.*)" search-card-slug)+ second+ (str/replace #"-" " ")+ u/lower-case-en)]+ (cond+ ;; e.g. search-string = "123"+ (and (not-empty search-id) (empty? search-name))+ [:like+ (h2x/cast (if (= (mdb/db-type) :mysql) :char :text) :report_card.id)+ (str search-id "%")]++ ;; e.g. search-string = "123-foo"+ (and (not-empty search-id) (not-empty search-name))+ [:and+ [:= :report_card.id (parse-long search-id)]+ ;; this is a prefix match to be consistent with substring matches on the entire slug+ [:like [:lower :report_card.name] (h2x/like-prefix search-name)]]++ ;; e.g. search-string = "foo"+ (and (empty? search-id) (not-empty search-name))+ [:like [:lower :report_card.name] (h2x/like-substring search-name)])))++(defn autocomplete-cards+ "Up to 50 unarchived Cards of the Database with `database-id` matching `search-card-slug` (see+ [[autocomplete-cards-search-clause]]), with their Collection name, models first then newest first. Dashboard+ questions are excluded unless `include-dashboard-questions?`."+ [database-id search-card-slug include-dashboard-questions?]+ (t2/select [:model/Card :id :type :database_id :name :collection_id+ [:collection.name :collection_name] :card_schema]+ {:where [:and+ [:= :report_card.database_id database-id]+ [:= :report_card.archived false]+ (when-not include-dashboard-questions?+ [:= :report_card.dashboard_id nil])+ (autocomplete-cards-search-clause search-card-slug)]+ :left-join [[:collection :collection] [:= :collection.id :report_card.collection_id]]+ ;; prioritize models. This relies of `model` coming before `question` alphabetically, and Tamas pointed+ ;; out this is a little brittle. He's right -- once we put v2 Metrics in then we can replace this with a+ ;; fancy `CASE` expression or something so we can sort things exactly how we like.+ :order-by [[:type :asc]+ [:report_card.id :desc]] ; sort by most recently created after sorting by type+ :limit 50}))++(defn autocomplete-fields+ "Up to `limit` name, type, id, and Table of the active, non-sensitive Fields of active Tables of the Database with+ `database-id` whose lower-cased name matches the SQL LIKE `like-pattern`, in field then table name order."+ [database-id like-pattern limit]+ ;; NOTE: measuring showed that this query performance is improved ~4x when adding trgm index in pgsql and ~10x when+ ;; adding a index on `lower(metabase_field.name)` for ordering (trgm index having on impact on queries with index).+ ;; Pgsql now has an index on that (see migration `v49.2023-01-24T12:00:00`) as other dbms do not support indexes on+ ;; expressions.+ (t2/select [:model/Field :name :base_type :semantic_type :id :table_id [:table.name :table_name]]+ :metabase_field.active true+ :%lower.metabase_field/name [:like like-pattern]+ :metabase_field.visibility_type [:not-in ["sensitive" "retired"]]+ :table.db_id database-id+ {:order-by [[[:lower :metabase_field.name] :asc]+ [[:lower :table.name] :asc]]+ ;; checking for table.active in join makes query faster when there are a lot of inactive tables+ :inner-join [[:metabase_table :table] [:and :table.active+ [:= :table.id :metabase_field.table_id]]]+ :limit limit}))++(defn table-ids-for-database+ "The ids of the Tables of the Database with `database-id`."+ [database-id]+ (t2/select-fn-set :id :model/Table, :db_id database-id))++(defn non-sensitive-fields-for-tables+ "The id, name, display name, Table id, and types of the non-sensitive Fields of the Tables with `table-ids`."+ [table-ids]+ (t2/select [:model/Field :id :name :display_name :table_id :base_type :semantic_type]+ :table_id [:in table-ids]+ :visibility_type [:not-in ["sensitive" "retired"]]))++(defn insert-database!+ "Insert the Database `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Database row))++(defn sample-database+ "The sample Database, or nil."+ []+ (t2/select-one :model/Database :is_sample true))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn update-database!+ "Apply `changes` to the Database with `database-id`."+ [database-id changes]+ (t2/update! :model/Database database-id changes))++(defn delete-destination-databases!+ "Delete the routing destination Databases of the Database with `router-database-id`."+ [router-database-id]+ (t2/delete! :model/Database :router_database_id router-database-id))++(defn delete-database!+ "Delete the Database with `database-id`."+ [database-id]+ (t2/delete! :model/Database :id database-id))++(defn mark-tables-sync-complete!+ "Mark the initial sync of the Tables with `table-ids` complete."+ [table-ids]+ (t2/update! :model/Table {:id [:in table-ids]} {:initial_sync_status "complete"}))++(defn delete-field-values-for-database!+ "Delete the FieldValues of every Field of the Database with `database-id`."+ [database-id]+ (t2/query-one {:delete-from :metabase_fieldvalues+ :where [:in :field_id+ ^:allow-subquery {:select [:f.id]+ :from [[:metabase_field :f]]+ :right-join [[:metabase_table :t] [:= :f.table_id :t.id]]+ :where [:= :t.db_id database-id]}]}))++(defn active-tables-for-database+ "The active Tables of the Database with `database-id`."+ [database-id]+ (t2/select :model/Table :db_id database-id :active true))++(defn active-table-schemas+ "The schemas of the active Tables of the Database with `database-id` also selected by the Honey SQL `query`."+ [database-id query]+ (t2/select-fn-set :schema :model/Table :db_id database-id :active true query))++(defn active-tables-in-schema+ "The active Tables in `schema` of the Database with `database-id`, in display name order."+ [database-id schema]+ (t2/select :model/Table+ :db_id database-id+ :schema schema+ :active true+ {:order-by [[:display_name :asc]]}))++(defn active-visible-tables-in-schema+ "The active, visible Tables in `schema` of the Database with `database-id`, in display name order."+ [database-id schema]+ (t2/select :model/Table+ :db_id database-id+ :schema schema+ :active true+ :visibility_type nil+ {:order-by [[:display_name :asc]]}))++(defn collection-ids-named+ "The ids of the Collections named `collection-name`, or nil."+ [collection-name]+ (t2/select-pks-set :model/Collection :name collection-name))diff --git a/src/metabase/xrays/api/automagic_dashboards.clj b/src/metabase/xrays/api/automagic_dashboards.cljindex 537ee864cfd..772ee407431 100644--- a/src/metabase/xrays/api/automagic_dashboards.clj+++ b/src/metabase/xrays/api/automagic_dashboards.clj@@ -23,6 +23,7 @@[metabase.xrays.automagic-dashboards.core :as automagic-dashboards.core][metabase.xrays.automagic-dashboards.dashboard-templates :as automagic-dashboards.dashboard-templates][metabase.xrays.automagic-dashboards.schema :as ads]+ [metabase.xrays.db :as xrays.db][metabase.xrays.transforms.dashboard :as transforms.dashboard][metabase.xrays.transforms.materialize :as transforms.materialize][ring.util.codec :as codec]@@ -93,7 +94,7 @@"Return a list of candidates for automagic dashboards ordered by interestingness."[{:keys [id]} :- [:map[:id ms/PositiveInt]]]- (-> (t2/select-one :model/Database :id id)+ (-> (xrays.db/database id)api/read-checkautomagic-dashboards.core/candidate-tables))@@ -127,21 +128,19 @@(if-let [[_ card-id-str] (when (string? table-id-str)(re-matches #"^card__(\d+$)" table-id-str))](->entity :question card-id-str)- (api/read-check (t2/select-one :model/Table :id (ensure-int table-id-str)))))+ (api/read-check (xrays.db/table (ensure-int table-id-str)))))(defmethod ->entity :segment[_entity-type segment-id-str]- (api/read-check (t2/select-one :model/Segment :id (ensure-int segment-id-str))))+ (api/read-check (xrays.db/segment (ensure-int segment-id-str))))(defmethod ->entity :model[_entity-type card-id-str]- (api/read-check (t2/select-one :model/Card- :id (ensure-int card-id-str)- :type :model)))+ (api/read-check (xrays.db/model-card (ensure-int card-id-str))))(defmethod ->entity :question[_entity-type card-id-str]- (api/read-check (t2/select-one :model/Card :id (ensure-int card-id-str))))+ (api/read-check (xrays.db/card (ensure-int card-id-str))))(mu/defn adhoc-query-instance :- [:and(ms/InstanceOf :model/Query)@@ -160,11 +159,11 @@(defmethod ->entity :field[_entity-type field-id-str]- (api/read-check (t2/select-one :model/Field :id (ensure-int field-id-str))))+ (api/read-check (xrays.db/field (ensure-int field-id-str))))(defmethod ->entity :transform[_entity-type transform-name]- (api/read-check (t2/select-one :model/Collection :id (transforms.materialize/get-collection transform-name)))+ (api/read-check (xrays.db/collection (transforms.materialize/get-collection transform-name)))transform-name)(def ^:private entities@@ -262,7 +261,7 @@"Identify the pk field of the model with `pk_ref`, and then find any fks that have that pk as a target."[{{field-ref :pk_ref} :model-index {rsmd :result_metadata} :model}](when-let [field-id (:id (some #(when ((comp #{field-ref} :field_ref) %) %) rsmd))]- (let [fields (t2/hydrate (t2/select :model/Field :fk_target_field_id field-id) :table)]+ (let [fields (t2/hydrate (xrays.db/fields-targeting field-id) :table)](perms/prime-table-perms-cache {:table-ids (into #{} (map :table_id) fields)})(for [{:keys [table_id id] :as field} fields:when (mi/can-read? field)]@@ -297,7 +296,7 @@:keys [linked-tables]}](if (seq linked-tables)(let [child-dashboards (map (fn [{:keys [linked-table-id linked-field-id]}]- (let [table (t2/select-one :model/Table :id linked-table-id)+ (let [table (xrays.db/table linked-table-id)mp (lib-be/application-database-metadata-provider (:db_id table))](automagic-dashboards.core/automagic-analysistable@@ -359,11 +358,9 @@[{:keys [model-index-id pk-id]} :- [:map[:model-index-id :int][:pk-id :int]]]- (api/let-404 [model-index (t2/select-one :model/ModelIndex model-index-id)- model (t2/select-one :model/Card (:model_id model-index))- model-index-value (t2/select-one :model/ModelIndexValue- :model_index_id model-index-id- :model_pk pk-id)]+ (api/let-404 [model-index (xrays.db/model-index model-index-id)+ model (xrays.db/card (:model_id model-index))+ model-index-value (xrays.db/model-index-value model-index-id pk-id)];; `->entity` does a read check on the model but this is here as well to be extra sure.(api/read-check :model/Card (:model_id model-index))(let [linked (linked-entities {:model modeldiff --git a/src/metabase/xrays/automagic_dashboards/core.clj b/src/metabase/xrays/automagic_dashboards/core.cljindex 63450365826..681c041bf2a 100644--- a/src/metabase/xrays/automagic_dashboards/core.clj+++ b/src/metabase/xrays/automagic_dashboards/core.clj@@ -171,6 +171,7 @@[metabase.xrays.automagic-dashboards.populate :as populate][metabase.xrays.automagic-dashboards.schema :as ads][metabase.xrays.automagic-dashboards.util :as magic.util]+ [metabase.xrays.db :as xrays.db][metabase.xrays.related :as related][toucan2.core :as t2]))@@ -198,7 +199,7 @@(mu/defmethod ->root :model/Segment :- ::ads/root[segment :- [:map [:definition ::segments.schema/definition]]]- (let [table (->> segment :table_id (t2/select-one :model/Table :id))]+ (let [table (->> segment :table_id xrays.db/table)]{:entity segment:full-name (tru "{0} in the {1} segment" (:display_name table) (:name segment)):short-name (:display_name table)@@ -211,7 +212,7 @@(mu/defmethod ->root :xrays/Metric :- ::ads/root[{:keys [table-id], :as metric} :- ::ads/metric]- (let [table (some->> table-id (t2/select-one :model/Table :id))]+ (let [table (some->> table-id xrays.db/table)]{:entity metric:full-name (if (:id metric)(trun "{0} metric" "{0} metrics" (:name metric))@@ -258,7 +259,7 @@[card-or-question :- [:map[:dataset_query ::ads/query]]](when-let [source-card-id (source-card-id card-or-question)]- (t2/select-one :model/Card :id source-card-id)))+ (xrays.db/card source-card-id)))(mu/defn- table-like?[{query :dataset_query, :as _card-or-question} :- [:map@@ -288,7 +289,7 @@source-question(assoc :entity_type :entity/GenericTable))(native-query? card) (-> card (assoc :entity_type :entity/GenericTable))- :else (->> card table-id (t2/select-one :model/Table :id))))+ :else (->> card table-id xrays.db/table)))(mu/defmethod ->root :model/Card :- ::ads/root[card :- [:map@@ -407,10 +408,7 @@be returned."[table](let [fields (field/with-targets- (t2/select :model/Field- :table_id (u/the-id table)- :fk_target_field_id [:not= nil]- :active true))]+ (xrays.db/active-fk-fields-for-table (u/the-id table)))](perms/prime-table-perms-cache {:table-ids (into #{} (keep (comp :table_id :target)) fields)})(for [{:keys [id target]} fields:when (some-> target mi/can-read?)]@@ -420,18 +418,14 @@(let [db-id (or ((some-fn :db_id :database_id) source)(throw (ex-info "Source is missing Database ID"{:source source})))]- (t2/select-one :model/Database :id db-id)))+ (xrays.db/database db-id)))(defn- relevant-fields"Source fields from tables that are applicable to the entity being x-rayed."[{:keys [source _entity] :as _root} tables](let [db (source->db source)](if (mi/instance-of? :model/Table source)- (comp (->> (-> (t2/select :model/Field- :table_id [:in (map u/the-id tables)]- :visibility_type "normal"- :preview_display true- :active true)+ (comp (->> (-> (xrays.db/visible-fields-for-tables (map u/the-id tables))(t2/hydrate :has_field_values [:dimensions :human_readable_field] :name_field))field/with-targets(map #(assoc % :db db))@@ -933,29 +927,9 @@- list-like?: Is this field 'list like'Filters out tables that are link-tables"- [clauses]+ [database-id schema](->>- (t2/select [:model/Table :id :schema :display_name :entity_type :db_id- [:ts.count :num-fields]- [[:and- [:>= :ts.count 2]- [:= :ts.count_non_pks 1]] :list-like?]]- {:inner-join [[^:allow-subquery {:select [:f.table_id- [:%count.* "count"]- [[:count [:case [:or [:not= :semantic_type "type/PK"]- [:= :f.semantic_type nil]]- [:inline 1] :else [:inline nil]]]- :count_non_pks]- [[:count [:case [:in :f.semantic_type ["type/PK" "type/FK"]]- [:inline 1] :else [:inline nil]]]- :count_pks_and_fks]]- :from [[:metabase_field :f]]- :where [:= :f.active true]- :group-by [:f.table_id]} :ts]- [:and [:= :ts.table_id :id]- [:> :ts.count 0]- [:!= :ts.count :ts.count_pks_and_fks]]]- :where (into [:and] clauses)})+ (xrays.db/candidate-tables-with-field-stats database-id schema)(map #(update % :list-like? (fn [val] (if (int? val) (= val 1) val)))))) ;; handle mysql returning the predicate value as an int(def ^:private ^:const ^Long max-candidate-tables@@ -975,11 +949,7 @@([database] (candidate-tables database nil))([database schema](let [dashboard-templates (dashboard-templates/get-dashboard-templates ["table"])- tables (load-tables-with-enhanced-table-stats- (cond-> [[:= :db_id (u/the-id database)]- [:= :visibility_type nil]- [:= :active true]]- schema (conj [:= :schema schema])))]+ tables (load-tables-with-enhanced-table-stats (u/the-id database) schema)];; the readable check below runs once per table, so load their permissions in one go(perms/prime-table-perms-cache {:db-ids (into #{} (keep :db_id) tables):table-ids (into #{} (map :id) tables)})diff --git a/src/metabase/xrays/automagic_dashboards/filters.clj b/src/metabase/xrays/automagic_dashboards/filters.cljindex fd4f8e464aa..75acdeab035 100644--- a/src/metabase/xrays/automagic_dashboards/filters.clj+++ b/src/metabase/xrays/automagic_dashboards/filters.clj@@ -9,7 +9,7 @@[metabase.warehouse-schema.models.field :as field][metabase.xrays.automagic-dashboards.schema :as ads][metabase.xrays.automagic-dashboards.util :as magic.util]- [toucan2.core :as t2]))+ [metabase.xrays.db :as xrays.db]))(defn- temporal?"Does `field` represent a temporal value, i.e. a date, time, or datetime?"@@ -125,9 +125,7 @@max-filters](let [fks (when-let [table-ids (not-empty (set (keep (comp :table_id :card)(:dashcards dashboard))))]- (field/with-targets (t2/select :model/Field- :fk_target_field_id [:not= nil]- :table_id [:in table-ids])))]+ (field/with-targets (xrays.db/fk-fields-for-tables table-ids)))](->> dimensionsremove-unqualifiedsort-by-interestingnessdiff --git a/src/metabase/xrays/automagic_dashboards/interesting.clj b/src/metabase/xrays/automagic_dashboards/interesting.cljindex 6f359eb04c5..e5def11ee97 100644--- a/src/metabase/xrays/automagic_dashboards/interesting.clj+++ b/src/metabase/xrays/automagic_dashboards/interesting.clj@@ -56,7 +56,7 @@[metabase.xrays.automagic-dashboards.dashboard-templates :as dashboard-templates][metabase.xrays.automagic-dashboards.schema :as ads][metabase.xrays.automagic-dashboards.util :as magic.util]- [toucan2.core :as t2]))+ [metabase.xrays.db :as xrays.db]));;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Code for creation of instantiated affinities@@ -97,7 +97,7 @@`:metadata/column`s directly or use Metadata Providers."[{fk-target-field-id :fk_target_field_id, base-type :base_type, :keys [id link aggregation], :as field} :- (ms/InstanceOf :model/Field)](let [col (if fk-target-field-id- (-> (t2/select-one :metadata/column :id fk-target-field-id)+ (-> (xrays.db/metadata-column fk-target-field-id)(assoc :fk-field-id id, :lib/source :source/implicitly-joinable))(lib-be/instance->metadata field :metadata/column))](cond-> col@@ -117,7 +117,7 @@(condfull-name full-namelink (format "%s → %s"- (-> (t2/select-one :model/Field :id link) :display_name (str/replace #"(?i)\sid$" ""))+ (-> (xrays.db/field link) :display_name (str/replace #"(?i)\sid$" ""))display_name):else display_name))@@ -363,7 +363,7 @@;; TODO - Deduplicate from core(mu/defn- source->db :- (ms/InstanceOf :model/Database)[source :- (ms/InstanceOf #{:model/Table :model/Card})]- (t2/select-one :model/Database :id ((some-fn :db_id :database_id) source)))+ (xrays.db/database ((some-fn :db_id :database_id) source)))(defn- enriched-field-with-sources [{:keys [tables source]} field](assoc fielddiff --git a/src/metabase/xrays/automagic_dashboards/populate.clj b/src/metabase/xrays/automagic_dashboards/populate.cljindex 2c754874700..60f89365997 100644--- a/src/metabase/xrays/automagic_dashboards/populate.clj+++ b/src/metabase/xrays/automagic_dashboards/populate.clj@@ -16,7 +16,7 @@[metabase.xrays.automagic-dashboards.filters :as filters][metabase.xrays.automagic-dashboards.schema :as ads][metabase.xrays.automagic-dashboards.util :as magic.util]- [toucan2.core :as t2]))+ [metabase.xrays.db :as xrays.db]))(set! *warn-on-reflection* true)@@ -35,14 +35,9 @@(defn get-or-create-container-collection"Get or create container collection for automagic dashboards in a given location."[location]- (or (t2/select-one :model/Collection- :name "Automatically Generated Dashboards"- :archived false- :location location)- (t2/insert-returning-instance!- :model/Collection- {:name "Automatically Generated Dashboards"- :location location})))+ (or (xrays.db/automagic-dashboards-collection location)+ (xrays.db/insert-collection! {:name "Automatically Generated Dashboards"+ :location location})))(defn colors"A vector of colors used for coloring charts. Uses [[appearance/application-colors]] for user choices."diff --git a/src/metabase/xrays/automagic_dashboards/util.clj b/src/metabase/xrays/automagic_dashboards/util.cljindex fdeb3082656..f416b61c870 100644--- a/src/metabase/xrays/automagic_dashboards/util.clj+++ b/src/metabase/xrays/automagic_dashboards/util.clj@@ -14,8 +14,8 @@[metabase.util.malli.schema :as ms][metabase.util.match :as match][metabase.xrays.automagic-dashboards.schema :as ads]- [ring.util.codec :as codec]- [toucan2.core :as t2]))+ [metabase.xrays.db :as xrays.db]+ [ring.util.codec :as codec]))(mu/defn field-isa?"`isa?` on a field, checking semantic_type and then base_type"@@ -84,7 +84,7 @@(or;; Handle integer Field IDs.(when (integer? id-or-name)- (t2/select-one :model/Field :id id-or-name))+ (xrays.db/field id-or-name));; handle field string names. Only if we have result metadata. (Not sure why)(when (string? id-or-name)(when-not result-metadatadiff --git a/src/metabase/xrays/db.clj b/src/metabase/xrays/db.cljnew file mode 100644index 00000000000..22367f4cd3b--- /dev/null+++ b/src/metabase/xrays/db.clj@@ -0,0 +1,255 @@+(ns metabase.xrays.db+ "Application database queries for the x-rays module. Every function here is a direct Toucan 2 call with no+ additional logic, so the rest of the module only touches `toucan2.core` for hydration."+ (:require+ [toucan2.core :as t2]))++(defn database+ "The Database with `database-id`, or nil."+ [database-id]+ (t2/select-one :model/Database :id database-id))++(defn table+ "The Table with `table-id`, or nil."+ [table-id]+ (t2/select-one :model/Table :id table-id))++(defn tables+ "The Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Table :id [:in table-ids]))++(defn tables-in-schema+ "The Tables in `schema` of the Database with `database-id`."+ [database-id schema]+ (t2/select :model/Table :db_id database-id :schema schema))++(defn sibling-tables+ "The active, visible Tables in `schema` of the Database with `database-id` other than `table-id`."+ [database-id schema table-id]+ (t2/select :model/Table+ :db_id database-id+ :schema schema+ :id [:not= table-id]+ :visibility_type nil+ :active true))++(defn candidate-tables-with-field-stats+ "The id, schema, name, entity type, Database, field count, and list-likeness of the active, visible Tables of the+ Database with `database-id` (optionally narrowed to `schema`) that have at least one non-key Field."+ [database-id schema]+ (t2/select [:model/Table :id :schema :display_name :entity_type :db_id+ [:ts.count :num-fields]+ [[:and+ [:>= :ts.count 2]+ [:= :ts.count_non_pks 1]] :list-like?]]+ {:inner-join [[^:allow-subquery {:select [:f.table_id+ [:%count.* "count"]+ [[:count [:case [:or [:not= :semantic_type "type/PK"]+ [:= :f.semantic_type nil]]+ [:inline 1] :else [:inline nil]]]+ :count_non_pks]+ [[:count [:case [:in :f.semantic_type ["type/PK" "type/FK"]]+ [:inline 1] :else [:inline nil]]]+ :count_pks_and_fks]]+ :from [[:metabase_field :f]]+ :where [:= :f.active true]+ :group-by [:f.table_id]} :ts]+ [:and [:= :ts.table_id :id]+ [:> :ts.count 0]+ [:!= :ts.count :ts.count_pks_and_fks]]]+ :where (cond-> [:and+ [:= :db_id database-id]+ [:= :visibility_type nil]+ [:= :active true]]+ schema (conj [:= :schema schema]))}))++(defn field+ "The Field with `field-id`, or nil."+ [field-id]+ (t2/select-one :model/Field :id field-id))++(defn field-name+ "The name of the Field with `field-id`, or nil."+ [field-id]+ (t2/select-one-fn :name :model/Field :id field-id))++(defn metadata-column+ "The `:metadata/column` with `field-id`, or nil."+ [field-id]+ (t2/select-one :metadata/column :id field-id))++(defn fields-targeting+ "The Fields whose FK target is the Field with `field-id`."+ [field-id]+ (t2/select :model/Field :fk_target_field_id field-id))++(defn fk-fields-for-tables+ "The FK Fields of the Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Field :fk_target_field_id [:not= nil] :table_id [:in table-ids]))++(defn active-fk-fields-for-table+ "The active FK Fields of the Table with `table-id`."+ [table-id]+ (t2/select :model/Field :table_id table-id :fk_target_field_id [:not= nil] :active true))++(defn fk-target-field-ids-for-table+ "The FK target Field ids of the active Fields of the Table with `table-id`."+ [table-id]+ (t2/select-fn-set :fk_target_field_id :model/Field+ :table_id table-id+ :fk_target_field_id [:not= nil]+ :active true))++(defn active-field-ids-for-table+ "The ids of the active Fields of the Table with `table-id`."+ [table-id]+ (t2/select-fn-set :id :model/Field :table_id table-id :active true))++(defn table-ids-of-fields-targeting+ "The Table ids of the active Fields whose FK target is one of `field-ids`."+ [field-ids]+ (t2/select-fn-set :table_id :model/Field :fk_target_field_id [:in field-ids] :active true))++(defn visible-fields-for-tables+ "The active, normally visible, previewable Fields of the Tables with `table-ids`."+ [table-ids]+ (t2/select :model/Field+ :table_id [:in table-ids]+ :visibility_type "normal"+ :preview_display true+ :active true))++(defn other-visible-fields-in-table+ "The active, normally visible Fields of the Table with `table-id` other than `field-id`."+ [table-id field-id]+ (t2/select :model/Field+ :table_id table-id+ :id [:not= field-id]+ :visibility_type "normal"+ :active true))++(defn card+ "The Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id))++(defn model-card+ "The model Card with `card-id`, or nil."+ [card-id]+ (t2/select-one :model/Card :id card-id :type :model))++(defn cards-in-collection+ "The Cards in the Collection with `collection-id`."+ [collection-id]+ (t2/select :model/Card :collection_id collection-id))++(defn unarchived-cards-for-table-of-types+ "The unarchived Cards of the Table with `table-id` whose type is one of `card-types`."+ [table-id card-types]+ (t2/select :model/Card :table_id table-id :type [:in card-types] :archived false))++(defn unarchived-metrics-for-table+ "The unarchived metric Cards of the Table with `table-id`."+ [table-id]+ (t2/select :model/Card :table_id table-id :type :metric :archived false))++(defn insert-card!+ "Insert the Card `card` and return the inserted instance."+ [card]+ (t2/insert-returning-instance! :model/Card card))++(defn delete-cards-in-collection!+ "Delete the Cards in the Collection with `collection-id`."+ [collection-id]+ (t2/delete! :model/Card :collection_id collection-id))++(defn segment+ "The Segment with `segment-id`, or nil."+ [segment-id]+ (t2/select-one :model/Segment :id segment-id))++(defn unarchived-segments-for-table+ "The unarchived Segments of the Table with `table-id`."+ [table-id]+ (t2/select :model/Segment :table_id table-id :archived false))++(defn collection+ "The Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one :model/Collection :id collection-id))++(defn collection-location-columns+ "The location and id of the Collection with `collection-id`, or nil."+ [collection-id]+ (t2/select-one [:model/Collection :location :id] :id collection-id))++(defn collection-id-by-name-and-location+ "The id of the Collection named `collection-name` at `location`, or nil."+ [collection-name location]+ (t2/select-one-pk :model/Collection :name collection-name :location location))++(defn automagic-dashboards-collection+ "The unarchived automatically generated dashboards Collection at `location`, or nil."+ [location]+ (t2/select-one :model/Collection+ :name "Automatically Generated Dashboards"+ :archived false+ :location location))++(defn insert-collection!+ "Insert the Collection `row` and return the inserted instance."+ [row]+ (t2/insert-returning-instance! :model/Collection row))++(defn insert-collection-returning-pk!+ "Insert the Collection `row` and return its id."+ [row]+ (t2/insert-returning-pk! :model/Collection row))++(defn dashboards+ "The Dashboards with `dashboard-ids`."+ [dashboard-ids]+ (t2/select :model/Dashboard :id [:in dashboard-ids]))++(defn recently-edited-dashboard-ids-for-user+ "The ids of the Dashboards the User with `user-id` has revised, most recent first."+ [user-id]+ (t2/select-fn-set :model_id :model/Revision+ :model "Dashboard"+ :user_id user-id+ {:order-by [[:timestamp :desc]]}))++(defn dashboard-ids-for-card+ "The Dashboard ids of the DashboardCards showing the Card with `card-id`."+ [card-id]+ (t2/select-fn-set :dashboard_id :model/DashboardCard :card_id card-id))++(defn card-ids-for-dashboard+ "The Card ids of the DashboardCards of the Dashboard with `dashboard-id`."+ [dashboard-id]+ (t2/select-fn-set :card_id :model/DashboardCard :dashboard_id dashboard-id))++(defn other-card-ids-on-dashboards+ "The Card ids other than `card-id` of the DashboardCards of the Dashboards with `dashboard-ids`."+ [dashboard-ids card-id]+ (t2/select-fn-set :card_id :model/DashboardCard :dashboard_id [:in dashboard-ids] :card_id [:not= card-id]))++(defn dashcard-card-and-dashboard-ids+ "The Card and Dashboard ids of the DashboardCards, optionally narrowed to `card-ids` and/or excluding+ `excluded-dashboard-ids`."+ [card-ids excluded-dashboard-ids]+ (apply t2/select [:model/DashboardCard :card_id :dashboard_id]+ (concat (when (seq card-ids) [:card_id [:in card-ids]])+ (when (seq excluded-dashboard-ids) [:dashboard_id [:not-in excluded-dashboard-ids]]))))++(defn model-index+ "The ModelIndex with `model-index-id`, or nil."+ [model-index-id]+ (t2/select-one :model/ModelIndex model-index-id))++(defn model-index-value+ "The ModelIndexValue of the ModelIndex with `model-index-id` for the model primary key `model-pk`, or nil."+ [model-index-id model-pk]+ (t2/select-one :model/ModelIndexValue :model_index_id model-index-id :model_pk model-pk))diff --git a/src/metabase/xrays/related.clj b/src/metabase/xrays/related.cljindex ca1d410358c..8b626696603 100644--- a/src/metabase/xrays/related.clj+++ b/src/metabase/xrays/related.clj@@ -13,7 +13,7 @@[metabase.util.malli :as mu][metabase.util.malli.registry :as mr][metabase.xrays.automagic-dashboards.schema :as ads]- [toucan2.core :as t2]))+ [metabase.xrays.db :as xrays.db]))(def ^:private ^Long max-best-matches 3)(def ^:private ^Long max-serendipity-matches 2)@@ -111,102 +111,74 @@(defn- metrics-for-table[table]- (filter-visible (t2/select :model/Card- :table_id (:id table)- :type :metric- :archived false)))+ (filter-visible (xrays.db/unarchived-metrics-for-table (:id table))))(defn- segments-for-table[table]- (filter-visible (t2/select :model/Segment- :table_id (:id table)- :archived false)))+ (filter-visible (xrays.db/unarchived-segments-for-table (:id table))))(defn- linking-to[table]- (->> (t2/select-fn-set :fk_target_field_id :model/Field- :table_id (:id table)- :fk_target_field_id [:not= nil]- :active true)- (map (comp (partial t2/select-one :model/Table :id)+ (->> (xrays.db/fk-target-field-ids-for-table (:id table))+ (map (comp xrays.db/table:table_id- (partial t2/select-one :model/Field :id)))+ xrays.db/field))distinctfilter-visible(take max-matches)))(defn- linked-from[table]- (if-let [fields (not-empty (t2/select-fn-set :id :model/Field- :table_id (:id table)- :active true))]- (->> (t2/select-fn-set :table_id :model/Field- :fk_target_field_id [:in fields]- :active true)- (map (partial t2/select-one :model/Table :id))+ (if-let [fields (not-empty (xrays.db/active-field-ids-for-table (:id table)))]+ (->> (xrays.db/table-ids-of-fields-targeting fields)+ (map xrays.db/table)filter-visible(take max-matches))[]))(defn- cards-sharing-dashboard[card]- (if-let [dashboards (not-empty (t2/select-fn-set :dashboard_id :model/DashboardCard- :card_id (:id card)))]- (->> (t2/select-fn-set :card_id :model/DashboardCard- :dashboard_id [:in dashboards]- :card_id [:not= (:id card)])- (map (partial t2/select-one :model/Card :id))+ (if-let [dashboards (not-empty (xrays.db/dashboard-ids-for-card (:id card)))]+ (->> (xrays.db/other-card-ids-on-dashboards dashboards (:id card))+ (map xrays.db/card)filter-visible(take max-matches))[]))(defn- similar-questions[card]- (->> (t2/select :model/Card- :table_id (:table_id card)- :type [:in [:model :question]]- :archived false)+ (->> (xrays.db/unarchived-cards-for-table-of-types (:table_id card) [:model :question])filter-visible(rank-by-similarity card)(filter (comp pos? :similarity))))(defn- similar-metrics[card]- (->> (t2/select :model/Card- :table_id (:table_id card)- :type :metric- :archived false)+ (->> (xrays.db/unarchived-cards-for-table-of-types (:table_id card) [:metric])filter-visible(rank-by-similarity card)(filter (comp pos? :similarity))))(defn- recently-modified-dashboards[]- (when-let [dashboard-ids (not-empty (t2/select-fn-set :model_id :model/Revision- :model "Dashboard"- :user_id api/*current-user-id*- {:order-by [[:timestamp :desc]]}))]- (->> (t2/select :model/Dashboard :id [:in dashboard-ids])+ (when-let [dashboard-ids (not-empty (xrays.db/recently-edited-dashboard-ids-for-user api/*current-user-id*))]+ (->> (xrays.db/dashboards dashboard-ids)filter-visible(take max-serendipity-matches))))(defn- recommended-dashboards[cards](let [recent (recently-modified-dashboards)- card-id->dashboard-cards (->> (apply t2/select [:model/DashboardCard :card_id :dashboard_id]- (cond-> []- (seq cards)- (concat [:card_id [:in (map :id cards)]])-- (seq recent)- (concat [:dashboard_id [:not-in (map :id recent)]])))+ card-id->dashboard-cards (->> (xrays.db/dashcard-card-and-dashboard-ids+ (map :id cards)+ (map :id recent))(group-by :card_id))dashboard-ids (->> (map :id cards)(mapcat card-id->dashboard-cards)(map :dashboard_id)distinct)best (when (seq dashboard-ids)- (->> (t2/select :model/Dashboard :id [:in dashboard-ids])+ (->> (xrays.db/dashboards dashboard-ids)filter-visible(take max-best-matches)))](concat best recent)))@@ -216,7 +188,7 @@(->> cards(m/distinct-by :collection_id)interesting-mix- (keep (comp (partial t2/select-one :model/Collection :id) :collection_id))+ (keep (comp xrays.db/collection :collection_id))filter-visible))(defmulti related@@ -226,7 +198,7 @@(defmethod related :model/Card[card]- (let [table (t2/select-one :model/Table :id (:table_id card))+ (let [table (xrays.db/table (:table_id card))similar-questions (similar-questions card)similar-metrics (similar-metrics card)]{:table table@@ -245,7 +217,7 @@(defmethod related :xrays/Metric[metric]- (let [table (t2/select-one :model/Table :id (:table_id metric))]+ (let [table (xrays.db/table (:table_id metric))]{:table table:segments (->> tablesegments-for-table@@ -254,7 +226,7 @@(defmethod related :model/Segment[segment]- (let [table (t2/select-one :model/Table :id (:table_id segment))]+ (let [table (xrays.db/table (:table_id segment))]{:table table:metrics (metrics-for-table table):segments (->> table@@ -271,19 +243,14 @@:metrics (metrics-for-table table):linking-to linking-to:linked-from linked-from- :tables (->> (t2/select :model/Table- :db_id (:db_id table)- :schema (:schema table)- :id [:not= (:id table)]- :visibility_type nil- :active true)+ :tables (->> (xrays.db/sibling-tables (:db_id table) (:schema table) (:id table))(remove (set (concat linking-to linked-from)))filter-visibleinteresting-mix)}))(defmethod related :model/Field[field]- (let [table (t2/select-one :model/Table :id (:table_id field))]+ (let [table (xrays.db/table (:table_id field))]{:table table:segments (->> tablesegments-for-table@@ -294,18 +261,13 @@(rank-by-similarity field)(filter (comp pos? :similarity))interesting-mix)- :fields (->> (t2/select :model/Field- :table_id (:id table)- :id [:not= (:id field)]- :visibility_type "normal"- :active true)+ :fields (->> (xrays.db/other-visible-fields-in-table (:id table) (:id field))filter-visibleinteresting-mix)}))(defmethod related :model/Dashboard[dashboard]- (let [cards (map (partial t2/select-one :model/Card :id) (t2/select-fn-set :card_id :model/DashboardCard- :dashboard_id (:id dashboard)))]+ (let [cards (map xrays.db/card (xrays.db/card-ids-for-dashboard (:id dashboard)))]{:cards (->> cards(mapcat similar-questions)(remove (set cards))diff --git a/src/metabase/xrays/transforms/core.clj b/src/metabase/xrays/transforms/core.cljindex 144efc70bff..71217d99e3e 100644--- a/src/metabase/xrays/transforms/core.clj+++ b/src/metabase/xrays/transforms/core.clj@@ -11,6 +11,7 @@[metabase.util.malli.schema :as ms][metabase.util.match :as match][metabase.warehouse-schema.models.table :as table]+ [metabase.xrays.db :as xrays.db][metabase.xrays.domain-entities.core :as de :refer [Bindings DimensionBindings SourceEntity SourceName]][metabase.xrays.domain-entities.specs :as domain-entities.specs :refer [*domain-entity-specs* DomainEntitySpec]][metabase.xrays.transforms.materialize :as tf.materialize]@@ -35,7 +36,7 @@field-name[:field (id :guard integer?) _]- (t2/select-one-fn :name :model/Field :id id)))+ (xrays.db/field-name id)))(mu/defn- infer-resulting-dimensions :- DimensionBindings[bindings :- Bindings@@ -189,7 +190,7 @@(mu/defn- tableset :- Tableset[db-id :- ::lib.schema.id/databaseschema :- [:maybe :string]]- (-> (t2/select :model/Table :db_id db-id :schema schema)+ (-> (xrays.db/tables-in-schema db-id schema)de/with-domain-entity(t2/hydrate :fields)))diff --git a/src/metabase/xrays/transforms/dashboard.clj b/src/metabase/xrays/transforms/dashboard.cljindex d9134add2e0..f37fe2820cf 100644--- a/src/metabase/xrays/transforms/dashboard.clj+++ b/src/metabase/xrays/transforms/dashboard.clj@@ -6,9 +6,9 @@[metabase.util :as u][metabase.util.malli :as mu][metabase.xrays.automagic-dashboards.populate :as populate]+ [metabase.xrays.db :as xrays.db][metabase.xrays.transforms.materialize :as tf.materialize][metabase.xrays.transforms.specs :refer [*transform-specs*]]- [toucan2.core :as t2][toucan2.realize :as t2.realize]))(def ^:private ^:const ^Long width 12)@@ -53,7 +53,7 @@(map (comp :source-table :query :dataset_query))(filter number?)not-empty)]- (let [table-id->table (t2/select-pk->fn t2.realize/realize :model/Table :id [:in (set table-ids)])]+ (let [table-id->table (into {} (map (juxt :id t2.realize/realize)) (xrays.db/tables (set table-ids)))](mapv (fn [table-id](let [table (get table-id->table table-id)](card-for-source-table table)))@@ -67,7 +67,7 @@{:status-code 404}))){steps false provides true} (->> transform-nametf.materialize/get-collection- (t2/select :model/Card :collection_id)+ xrays.db/cards-in-collection(group-by (comp some?(-> transform-spec :provides set):name)))diff --git a/src/metabase/xrays/transforms/materialize.clj b/src/metabase/xrays/transforms/materialize.cljindex 73e932b282d..aac8d2fabc8 100644--- a/src/metabase/xrays/transforms/materialize.clj+++ b/src/metabase/xrays/transforms/materialize.clj@@ -8,16 +8,15 @@[metabase.queries.schema :as queries.schema][metabase.query-processor.preprocess :as qp.preprocess][metabase.util.malli :as mu]- [metabase.xrays.transforms.specs :as transforms.specs]- [toucan2.core :as t2]))+ [metabase.xrays.db :as xrays.db]+ [metabase.xrays.transforms.specs :as transforms.specs]))(declare get-or-create-root-container-collection!)(defn- root-container-location[](collection/children-location- (t2/select-one [:model/Collection :location :id]- :id (get-or-create-root-container-collection!))))+ (xrays.db/collection-location-columns (get-or-create-root-container-collection!))))(mu/defn get-collection :- [:maybe ::lib.schema.id/collection]"Get collection named `collection-name`. If no location is given root collection for automatically@@ -26,18 +25,15 @@(get-collection collection-name (root-container-location)))([collection-name :- :stringlocation :- :string]- (t2/select-one-pk :model/Collection- :name collection-name- :location location)))+ (xrays.db/collection-id-by-name-and-location collection-name location)))(defn- create-collection!([collection-name description](create-collection! collection-name description (root-container-location)))([collection-name description location]- (first (t2/insert-returning-pks! :model/Collection- {:name collection-name- :description description- :location location}))))+ (xrays.db/insert-collection-returning-pk! {:name collection-name+ :description description+ :location location})))(defn- get-or-create-root-container-collection!"Get or create container collection for transforms in the root collection."@@ -52,7 +48,7 @@exists."[{:keys [name description]}](if-let [collection-id (get-collection name)]- (t2/delete! :model/Card :collection_id collection-id)+ (xrays.db/delete-cards-in-collection! collection-id)(create-collection! name description)))(mu/defn make-card-for-step! :- ::queries.schema/card@@ -69,5 +65,4 @@:visualization_settings {}:display :table}queries/populate-card-query-fields- (t2/insert-returning-instances! :model/Card)- first)))+ xrays.db/insert-card!)))diff --git a/test/metabase/dashboards/db_test.clj b/test/metabase/dashboards/db_test.cljnew file mode 100644index 00000000000..b759cd8ddca--- /dev/null+++ b/test/metabase/dashboards/db_test.clj@@ -0,0 +1,18 @@+(ns metabase.dashboards.db-test+ (:require+ [clojure.test :refer :all]+ [honey.sql :as sql]+ [metabase.dashboards.db :as dashboards.db]))++(set! *warn-on-reflection* true)++(deftest ^:parallel link-card-id-compiles-as-query-parameter-test+ (testing "a non-integer id is rejected when building the link-card query"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"must be an integer"+ (#'dashboards.db/link-card-info-query-for-model "card" {:raw "x"}))))+ (testing "single-id and collection forms both pass a legitimate id as a bind parameter"+ (doseq [ids [42 #{42} [42]]]+ (let [[query & params] (sql/format (#'dashboards.db/link-card-info-query-for-model "card" ids))]+ (is (re-find #"\?" query) "the id appears as a bind parameter")+ (is (= [42] params))))))diff --git a/test/metabase/dashboards/models/dashboard_card_test.clj b/test/metabase/dashboards/models/dashboard_card_test.cljindex 7133f243343..b7e20e9b90b 100644--- a/test/metabase/dashboards/models/dashboard_card_test.clj+++ b/test/metabase/dashboards/models/dashboard_card_test.clj@@ -1,7 +1,6 @@(ns metabase.dashboards.models.dashboard-card-test(:require[clojure.test :refer :all]- [honey.sql :as sql][metabase.dashboards.models.dashboard :as dashboard][metabase.dashboards.models.dashboard-card :as dashboard-card][metabase.queries.models.card-test :as card-test]@@ -420,14 +419,3 @@:column_settings{"[\"name\",\"abc\"]"{:click_behavior {:type "link" :linkType "question" :targetId card-id}}}}}))))))))--(deftest ^:parallel link-card-id-compiles-as-query-parameter-test- (testing "a non-integer id is rejected when building the link-card query"- (is (thrown-with-msg?- clojure.lang.ExceptionInfo #"must be an integer"- (dashboard-card/link-card-info-query-for-model "card" {:raw "x"}))))- (testing "single-id and collection forms both pass a legitimate id as a bind parameter"- (doseq [ids [42 #{42} [42]]]- (let [[query & params] (sql/format (dashboard-card/link-card-info-query-for-model "card" ids))]- (is (re-find #"\?" query) "the id appears as a bind parameter")- (is (= [42] params))))))diff --git a/test/metabase/data_studio/api/table_test.clj b/test/metabase/data_studio/api/table_test.cljindex 99079d65e41..3a21620e855 100644--- a/test/metabase/data_studio/api/table_test.clj+++ b/test/metabase/data_studio/api/table_test.clj@@ -3,6 +3,7 @@(:require[clojure.test :refer :all][metabase.data-studio.api.table :as api.table]+ [metabase.data-studio.db :as data-studio.db][metabase.permissions.models.permissions-group :as perms-group][metabase.sync.core :as sync][metabase.test :as mt]@@ -211,11 +212,10 @@(testing "Selected FieldValues should be gone"(is (= [v3] (get-field-values))))))))))-(deftest ^:parallel table-selectors->filter-test- (testing "table-selectors->filter function generates correct WHERE clauses"+(deftest ^:parallel tables-matching-selectors-test+ (testing "data-studio.db/tables-matching-selectors picks out the correct Tables"(let [selectors->table-ids (fn [selectors]- (let [where (#'api.table/table-selectors->filter selectors)]- (t2/select-pks-set :model/Table {:where where})))]+ (not-empty (set (map :id (data-studio.db/tables-matching-selectors selectors)))))](mt/with-temp [:model/Database {db-1 :id} {}:model/Database {db-2 :id} {}:model/Table {table-1 :id} {:db_id db-1}diff --git a/test/metabase/models/serialization/resolve/db_test.clj b/test/metabase/models/serialization/resolve/default_test.cljsimilarity index 99%rename from test/metabase/models/serialization/resolve/db_test.cljrename to test/metabase/models/serialization/resolve/default_test.cljindex 44bb38170cc..819ad4f9d6b 100644--- a/test/metabase/models/serialization/resolve/db_test.clj+++ b/test/metabase/models/serialization/resolve/default_test.clj@@ -1,4 +1,4 @@-(ns metabase.models.serialization.resolve.db-test+(ns metabase.models.serialization.resolve.default-test(:require[clojure.test :refer :all][metabase.models.serialization :as serdes]diff --git a/test/metabase/models/serialization/resolve/mp_test.clj b/test/metabase/models/serialization/resolve/mp_test.cljindex 5cc205bc175..df3b227a3b8 100644--- a/test/metabase/models/serialization/resolve/mp_test.clj+++ b/test/metabase/models/serialization/resolve/mp_test.clj@@ -147,7 +147,7 @@;;;; The fix in [[resolve.mp/find-table]] bypasses the metadata provider for app-DB-backed;; lookups and queries `metabase_table` directly with schema in the WHERE clause, the- ;; same shape `metabase.models.serialization.resolve.db/import-table-fk` has always+ ;; same shape `metabase.models.serialization.resolve.default/import-table-fk` has always;; used.(mt/with-temp [:model/Database db {:name (str "DW " (random-uuid)) :engine :h2}:model/Table raw-orders {:name "ORDERS" :schema "RAW" :db_id (:id db)}diff --git a/test/metabase/typed_schemas/schema/model_test.clj b/test/metabase/typed_schemas/schema/model_test.cljindex 34efbbc9efb..48d2bf09394 100644--- a/test/metabase/typed_schemas/schema/model_test.clj+++ b/test/metabase/typed_schemas/schema/model_test.clj@@ -24,7 +24,7 @@{:id 43 :name "Model 43"}])schema.model/action-rows(constantly [{:id 5 :model_id 42 :name "Create" :type :query}])- actions/select-actions+ actions/select-actions-non-http-for-models(constantly [{:id 5:model_id 42:name "Create"@@ -44,14 +44,12 @@schema.model/action-rows (fn [model-ids](swap! action-rows-calls conj model-ids)[])- actions/select-actions (fn [known-models & options]- (swap! action-details-calls conj [known-models options])- [])]+ actions/select-actions-non-http-for-models (fn [known-models model-ids]+ (swap! action-details-calls conj [known-models model-ids])+ [])](is (= [] (vec (schema.model/model-schemas #{1} nil))))(is (= [#{42 43}] @action-rows-calls))- (is (= [[models [:model_id [:in #{42 43}]- :archived false- :type [:not= "http"]]]]+ (is (= [[models #{42 43}]]@action-details-calls)))))(deftest model-schema-surfaces-action-selection-errors-testdiff --git a/test/metabase/warehouse_schema/models/table_test.clj b/test/metabase/warehouse_schema/models/table_test.cljindex ac3e92fc124..7a5777cf7fa 100644--- a/test/metabase/warehouse_schema/models/table_test.clj+++ b/test/metabase/warehouse_schema/models/table_test.clj@@ -160,7 +160,16 @@(mt/id :venues :name) (mt/malli=? [:sequential {:min 1} :any])}(-> (t2/select-one :model/Table (mt/id :venues))(t2/hydrate :field_values)- :field_values))))+ :field_values)))+ (testing "batched hydration of several tables"+ (field-values/get-or-create-full-field-values! (t2/select-one :model/Field :id (mt/id :categories :name)))+ (is (=? {(mt/id :venues) {(mt/id :venues :price) (mt/malli=? [:sequential {:min 1} :any])+ (mt/id :venues :name) (mt/malli=? [:sequential {:min 1} :any])}+ (mt/id :categories) {(mt/id :categories :name) (mt/malli=? [:sequential {:min 1} :any])}}+ (->> (t2/select :model/Table :id [:in [(mt/id :venues) (mt/id :categories)]])+ (#(t2/hydrate % :field_values))+ (map (juxt :id :field_values))+ (into {}))))))(deftest pk-field-hydration-test(is (= (mt/id :venues :id)diff --git a/test/metabase/xrays/automagic_dashboards/core_test.clj b/test/metabase/xrays/automagic_dashboards/core_test.cljindex ab194b09e00..5caf13e68cf 100644--- a/test/metabase/xrays/automagic_dashboards/core_test.clj+++ b/test/metabase/xrays/automagic_dashboards/core_test.clj@@ -1125,7 +1125,7 @@(automagic-dashboards.test/with-rollback-only-transaction(is (partial= {:list-like? true:num-fields 2}- (-> (#'magic/load-tables-with-enhanced-table-stats [[:= :id table-id]])+ (-> (#'magic/load-tables-with-enhanced-table-stats db-id nil)first)))))))(deftest enhance-table-stats-fk-test@@ -1138,7 +1138,7 @@(automagic-dashboards.test/with-rollback-only-transaction(testing "filters out link-tables"(is (empty?- (#'magic/load-tables-with-enhanced-table-stats [[:= :id table-id]]))))))))+ (#'magic/load-tables-with-enhanced-table-stats db-id nil))))))));;; ------------------- Definition overloading -------------------