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
Perms - t2/reducible-query + per-row realize + fold (#78811)
Alexander Polyankin7c58c0539f3b
diff --git a/src/metabase/permissions/models/data_permissions.clj b/src/metabase/permissions/models/data_permissions.cljindex 4584436610d..a3cd3d89f5d 100644--- a/src/metabase/permissions/models/data_permissions.clj+++ b/src/metabase/permissions/models/data_permissions.clj@@ -18,7 +18,8 @@[metabase.util.malli.schema :as ms][metabase.util.memoize :as u.memo][methodical.core :as methodical]- [toucan2.core :as t2])+ [toucan2.core :as t2]+ [toucan2.realize :as t2.realize])(:import(clojure.lang PersistentVector)))@@ -146,38 +147,45 @@;;; ---------------------------------------- Caching ------------------------------------------------------------------(defn- relevant-permissions-for-user-and-dbs- "Returns all relevant rows for permissions for the user, excluding permissions for deactivated tables for the given sequence of database ids."+ "Returns a reducible of all relevant permission rows for the user, excluding permissions for deactivated tables, for+ the given sequence of database ids. Reducing it folds rows one at a time instead of realizing the full result set+ (see [[prime-db-cache]]). Rows are raw realized maps, not model instances, so `:perm_type` and `:perm_value` are+ strings rather than keywords. The per-row [[t2.realize/realize]] is a performance requirement, not a convenience:+ key access on unrealized result-set rows goes through toucan2's deferred-row machinery on every lookup, which+ benchmarked ~15x slower than realizing each row once and reading plain map keys."[user-id db-ids]- (t2/select :model/DataPermissions- {:select [:p.group_id :p.perm_type :p.db_id :p.table_id :p.schema_name :p.perm_value]- :from [[:permissions_group_membership :pgm]]- :join [[:permissions_group :pg] [:= :pg.id :pgm.group_id]- [:data_permissions :p] [:= :p.group_id :pg.id]]- :left-join [[:metabase_table :mt] [:= :mt.id :p.table_id]]- :where [:and- [:= :pgm.user_id user-id]- [:in :p.db_id db-ids]- [:or- [:= :p.table_id nil]- [:= :mt.active true]]]}))+ (eduction+ (map t2.realize/realize)+ (t2/reducible-query+ {:select [:p.group_id :p.perm_type :p.db_id :p.table_id :p.schema_name :p.perm_value]+ :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]+ [:in :p.db_id db-ids]+ [:or+ [:= :p.table_id nil]+ [:= :mt.active true]]]})))(defn- relevant-permissions-for-user-perm-and-db"Returns all relevant rows for a given user, permission type, and db_id, excluding permissions for deactivated- tables."+ tables. Rows are raw realized maps rather than model instances -- much cheaper per row, see+ [[relevant-permissions-for-user-and-dbs]] -- so `:perm_value` is a string; [[rows->cache-entry]] normalizes it."[user-id perm-type db-id]- (t2/select :model/DataPermissions- {:select [:p.group_id :p.perm_type :p.db_id :p.table_id :p.schema_name :p.perm_value]- :from [[:permissions_group_membership :pgm]]- :join [[:permissions_group :pg] [:= :pg.id :pgm.group_id]- [:data_permissions :p] [:= :p.group_id :pg.id]]- :left-join [[:metabase_table :mt] [:= :mt.id :p.table_id]]- :where [:and- [:= :pgm.user_id user-id]- [:= :p.perm_type (u/qualified-name perm-type)]- [:= :p.db_id db-id]- [:or- [:= :p.table_id nil]- [:= :mt.active true]]]}))+ (t2/query {:select [:p.group_id :p.perm_type :p.db_id :p.table_id :p.schema_name :p.perm_value]+ :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]+ [:= :p.perm_type (u/qualified-name perm-type)]+ [:= :p.db_id db-id]+ [:or+ [:= :p.table_id nil]+ [:= :mt.active true]]]}))(def ^:dynamic *permissions-for-user*"A dynamically-bound atom containing a cache of data permissions that have been fetched so far for the current user.@@ -228,6 +236,23 @@(when (some? v)(intern! v)))))+(defn- add-row-to-cache-entry+ "Fold a single data_permissions row into an in-progress cache entry (see [[rows->cache-entry]] for the semantics).+ `perm_value` may be a raw result-set string or an already-transformed keyword depending on the fetch path;+ `keyword` normalizes both."+ [interner entry {:keys [table_id schema_name group_id perm_value]}]+ (let [perm-value (keyword perm_value)]+ (if table_id+ (update-in entry [:tables table_id group_id] (fnil conj #{})+ (interner {:schema schema_name :value perm-value}))+ (update-in entry [:groups group_id] (fnil conj #{}) perm-value))))++(defn- finalize-cache-entry+ "Intern the shareable pieces of a folded cache entry: the whole :groups map, and each table's group-id->values map."+ [interner {:keys [groups tables] :or {groups {} tables {}}}]+ {:groups (interner groups)+ :tables (update-vals tables interner)})+(defn- rows->cache-entry"Build the compact cache entry (see [[*permissions-for-user*]]) for one (perm-type, db-id) bucket ofdata_permissions rows. Returns nil when there are no rows.@@ -245,23 +270,7 @@coalescing would deny)."[interner rows](when (seq rows)- (let [groups (reduce (fn [m {:keys [table_id group_id perm_value]}]- (if table_id- m- (update m group_id (fnil conj #{}) perm_value)))- {}- rows)- tables (reduce (fn [m {:keys [table_id schema_name group_id perm_value]}]- (if table_id- (update m table_id- (fn [group-id->values]- (update group-id->values group_id (fnil conj #{})- (interner {:schema schema_name :value perm_value}))))- m))- {}- rows)]- {:groups (interner groups)- :tables (update-vals tables interner)})))+ (finalize-cache-entry interner (reduce (partial add-row-to-cache-entry interner) {} rows))))(defn prime-db-cache"Prime the permissions cache for a given user and database IDs.@@ -270,13 +279,16 @@(let [{cached-db-ids :db-ids interner :intern perms :perms} @*permissions-for-user*filtered-ids (remove cached-db-ids db-ids)](when (seq filtered-ids)- (let [user-id api/*current-user-id*- fetched-perm-rows (relevant-permissions-for-user-and-dbs user-id filtered-ids)- interner (or interner (cache-interner))- new-by-type (reduce-kv (fn [m [perm-type db-id] bucket]- (assoc-in m [perm-type db-id] (rows->cache-entry interner bucket)))- {}- (group-by (juxt :perm_type :db_id) fetched-perm-rows))]+ (let [user-id api/*current-user-id*+ interner (or interner (cache-interner))+ folded (reduce (fn [m {:keys [perm_type db_id] :as row}]+ (update-in m [(keyword perm_type) db_id]+ (fnil #(add-row-to-cache-entry interner % row) {})))+ {}+ (relevant-permissions-for-user-and-dbs user-id filtered-ids))+ new-by-type (update-vals folded+ (fn [db-id->entry]+ (update-vals db-id->entry #(finalize-cache-entry interner %))))](reset! *permissions-for-user*{:db-ids (into cached-db-ids db-ids):intern interner@@ -944,13 +956,14 @@{: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 {: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)]]]})+ (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)]]]})(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@@ -972,14 +985,16 @@(defn- handle-no-db-permission"Handles the case where there's no existing database-level permission."[group-id db-id perm-type table-ids values new-perms]- (let [existing-table-perms (t2/select :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]]]})- existing-table-values (set (map :perm_value existing-table-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]]]}))](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@@ -987,7 +1002,8 @@(build-database-permission (index-database-permissions [group-id] [db-id])group-id db-id perm-type (first values));; Otherwise, just replace the rows for the individual table perm- (let [table-perms-to-delete (t2/select :model/DataPermissions+ ;; 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]diff --git a/src/metabase/permissions_rest/data_permissions/graph.clj b/src/metabase/permissions_rest/data_permissions/graph.cljindex 84a50ad818f..49cd95f5626 100644--- a/src/metabase/permissions_rest/data_permissions/graph.clj+++ b/src/metabase/permissions_rest/data_permissions/graph.clj@@ -18,7 +18,8 @@[metabase.util.i18n :refer [tru]][metabase.util.malli :as mu][metabase.util.malli.registry :as mr]- [toucan2.core :as t2]))+ [toucan2.core :as t2]+ [toucan2.realize :as t2.realize]))(set! *warn-on-reflection* true)@@ -206,25 +207,37 @@"Reducible of the raw `data_permissions` rows for the given `opts`. Using a reducible (rather than realizing the fullresult set) keeps the row data out of memory -- we reduce each row into the graph as it streams from the app DB.Ordered by `(group_id, db_id)` so that all rows for a given (group, db) arrive contiguously, which lets- [[reduce-into-graph]] finalize and compact each (group, db) perm-map without buffering the whole graph."+ [[reduce-into-graph]] finalize and compact each (group, db) perm-map without buffering the whole graph.++ Rows are fetched with a raw query rather than a model select, and realized one at a time: key access on unrealized+ result-set rows goes through toucan2's deferred-row machinery on every lookup, which benchmarked ~15x slower than+ realizing each row once and reading plain map keys (see+ [[metabase.permissions.models.data-permissions/relevant-permissions-for-user-and-dbs]]). The raw query skips the+ model transforms, so `:type` and `:value` arrive as strings and are keywordized here."[{:keys [group-id group-ids db-id perm-type audit?]}]- (t2/reducible-select [:model/DataPermissions- [:perm_type :type]- [:group_id :group-id]- [:perm_value :value]- [:db_id :db-id]- [:schema_name :schema]- [:table_id :table-id]]- {: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-in :db_id {:select [:id]- :from [:metabase_database]- :where [:not= :router_database_id nil]}]]- :order-by [:group_id :db_id]}))+ (eduction+ (map (fn [row]+ (-> (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-in :db_id {:select [:id]+ :from [(t2/table-name :model/Database)]+ :where [:not= :router_database_id nil]}]]+ :order-by [:group_id :db_id]})))(defn- add-perm"Reducing step that accumulates one `data_permissions` row's value into its (group, db) `perm-map`, at either a@@ -241,8 +254,8 @@`reducible` MUST be ordered by `(group_id, db_id)` so each (group, db)'s rows arrive contiguously: we accumulate oneraw perm-map at a time and commit it as soon as its group ends, so the full raw table-level graph -- which can be on- the order of a gigabyte -- is never materialized. (The rows are transient, cursor-backed instances, so they can't be- buffered and grouped after the fact, e.g. via `partition-by`.)"+ the order of a gigabyte -- is never materialized. (Buffering and grouping after the fact, e.g. via `partition-by`,+ would materialize the whole result set.)"[reducible finalize](let [commit (fn [graph path perm-map](if (nil? path)