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
Actions optional model (#83435)
Alexander Polyankin5ce0b19bc0c8
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex baa037bc04a..d3bd274659f 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -96,6 +96,7 @@metabase.actions.types}:uses #{analyticsapi+ collectionsdrivereventslib@@ -117,10 +118,7 @@utilwarehouse-schema-overlaywarehouses}- :model-exports #{:model/Action- :model/HTTPAction- :model/ImplicitAction- :model/QueryAction}+ :model-exports #{:model/Action :model/ImplicitAction :model/QueryAction}:model-imports #{:model/Card:model/Collection:model/Dashboard@@ -142,11 +140,9 @@api.eid-translationcollectionsevents- liblib.schemapermissionspublic-sharing- queriesutil}:model-imports #{:model/Action :model/Card :model/Database}}@@ -639,7 +635,8 @@util.configwarehouse-schema-overlay}:model-exports #{:model/Collection}- :model-imports #{:model/Card+ :model-imports #{:model/Action+ :model/Card:model/CollectionBookmark:model/CollectionPermissionGraphRevision:model/Dashboard@@ -1733,7 +1730,6 @@:model/FieldUserSettings:model/FieldValues:model/Glossary- :model/HTTPAction:model/ImplicitAction:model/Measure:model/Metabot@@ -3291,8 +3287,10 @@warehouse-schema-overlaywarehouses.secrets}:model-exports #{:model/Database}- :model-imports #{:model/Card+ :model-imports #{:model/Action+ :model/Card:model/Field+ :model/QueryAction:model/Table:model/User}}diff --git a/bin/build/resources/overrides.edn b/bin/build/resources/overrides.ednindex 16c8429ee4d..7e1ab016f9b 100644--- a/bin/build/resources/overrides.edn+++ b/bin/build/resources/overrides.edn@@ -63,7 +63,6 @@"net.openhft" {"zero-allocation-hashing" {:resource "apache2_0.txt"}}"net.redhogs.cronparser" {"cron-parser-core" {:resource "MIT.txt"}}"net.shibboleth.utilities" {"java-support" {:resource "apache2_0.txt"}}- "net.thisptr" {"jackson-jq" {:resource "apache2_0.txt"}}"org.antlr" {"antlr-runtime" {:resource "BSD.txt"}"antlr4-runtime" {:resource "BSD.txt"}}"org.codehaus.mojo" {"animal-sniffer-annotations" {:resource "MIT.txt"}}diff --git a/deps.edn b/deps.ednindex cb2baf25ada..bf4aa6a9bb0 100644--- a/deps.edn+++ b/deps.edn@@ -110,7 +110,6 @@net.sf.cssbox/cssbox {:mvn/version "5.0.2" ; HTML / CSS rendering:exclusions [org.slf4j/slf4j-apijunit/junit]}- net.thisptr/jackson-jq {:mvn/version "1.6.0"} ; Java implementation of the JQ json query languageorg.apache.commons/commons-compress {:mvn/version "1.28.0"} ; compression utilsorg.apache.commons/commons-lang3 {:mvn/version "3.20.0"} ; helper methods for working with java.lang stufforg.apache.datasketches/datasketches-java ^:antq/exclude ; Sketching algorithms (used for fingerprinting)diff --git a/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts b/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.tsindex 314808d2bab..f3aca17eec9 100644--- a/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts+++ b/e2e/test-host-app/data-apps/sync-resources-actions.cy.spec.ts@@ -426,10 +426,10 @@ describe(// `GET /api/action/:id` filters archived actions out, so an archived source// is unreadable rather than readable-and-flagged.it("copies nothing when the action's model is in the trash", () => {- declareOneAction().then(({ modelId }) => {+ declareOneAction().then(({ modelId, action }) => {cy.request("PUT", `/api/card/${modelId}`, { archived: true });- syncExpectingRefusal(`references an action on model ${modelId}`);+ syncExpectingRefusal(`Could not read action ${action.id}`);copiedModels().should("have.length", 0);});});diff --git a/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.clj b/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.cljindex 9354409a65e..85f6074ac20 100644--- a/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.clj+++ b/enterprise/backend/src/metabase_enterprise/action_v2/execute_form.clj@@ -105,7 +105,7 @@(throw (ex-info "Must provide table-id" {:status-code 400})))(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)+ _ (actions/check-data-editing-enabled-for-database database)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 configurationdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.cljindex ba1e52453c4..e36518ea0a4 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj@@ -3,7 +3,6 @@[java-time.api :as t][medley.core :as m][metabase-enterprise.remote-sync.db :as remote-sync.db]- [metabase-enterprise.remote-sync.events :as rs-events][metabase-enterprise.remote-sync.guards :as guards][metabase-enterprise.remote-sync.settings :as settings][metabase-enterprise.remote-sync.source :as source]@@ -141,9 +140,7 @@:model_id (:id entity):status "create":status_changed_at (t/offset-date-time)}- (spec/build-sync-object-fields spec entity))))- ;; Actions live in their model's collection, not a collection_id of their own.- (rs-events/track-untracked-actions! collection-ids))+ (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 idsdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/db.cljindex 855fc93a8a1..de7ef7bb842 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/db.clj@@ -20,11 +20,10 @@[:maybe [:map-of ConditionKey [:maybe [:or :string :int :boolean :keyword sequential?]]]])(def ^:private RemovalOpts- "The `:scope-key`, `:scope-table`, `:synced-collection-ids`, `:entity-ids`, and `:removal-conditions` describing- which rows an import removes (see [[removal-exprs]])."+ "The `:scope-key`, `:synced-collection-ids`, `:entity-ids`, and `:removal-conditions` describing which rows an+ import removes (see [[removal-exprs]])."[:map {:closed true}[:scope-key [:maybe :keyword]]- [:scope-table {:optional true} [:maybe :keyword]][:synced-collection-ids [:maybe [:or [:set ::lib.schema.id/collection] [:sequential ::lib.schema.id/collection]]]][:entity-ids [:maybe [:or [:set :string] [:sequential :string]]]][:removal-conditions Conditions]])@@ -86,17 +85,12 @@(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; through the `scope-table` rows in those collections- when that is given too), excluding `entity-ids`, and matching `removal-conditions`. Returns nil for a scoped model- with no synced collections (removes nothing)."- [{:keys [scope-key scope-table synced-collection-ids entity-ids removal-conditions]}]+ 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 (if scope-table- ^:allow-subquery {:select [:id]- :from [scope-table]- :where [:in :collection_id synced-collection-ids]}- synced-collection-ids)])+ 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)))))@@ -199,16 +193,11 @@(t2/delete! model :id [:in ids]))(defn- tracking-select-parts- "The SELECT/FROM/JOIN joining a `model-key` instance to the parent that carries its collection for sync tracking- (Field, Segment, or Measure to its Table; Action to its model Card), 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]]."+ "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/Action {:alias "a"- :select [:a.name [:c.collection_id :collection_id]]- :from [[:action :a]]- :join [[:report_card :c] [:= :a.model_id :c.id]]}:model/Field {:alias "f":select [:f.name :f.table_id [:t.collection_id :collection_id] [:t.name :table_name]]:from [[:metabase_field :f]]@@ -223,16 +212,16 @@:join [(warehouse-schema-overlay/table-query {:alias :t}) [:= :s.table_id :t.id]]}))(mu/defn tracking-details-by-id- "The name, table id, collection id, and table name of the `model-key` (Field, Segment, Measure, or Action) instance- with `model-id`, or nil. An Action has no table, and its collection is its model's."+ "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 :- :keywordmodel-id :- ms/PositiveInt](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]}))))(mu/defn tracking-details-by-entity-ids- "The `:id`, name, table id, collection id, and table name of the `model-key` (Segment, Measure, or Action)- instances with `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 :- :keywordentity-ids :- [:or [:set :string] [:sequential :string]]](let [{:keys [alias select from join]} (tracking-select-parts model-key)@@ -537,48 +526,14 @@(t2/select :model/RemoteSyncObject :model_type model-type :model_id [:in model-ids]))(mu/defn active-child-rsos- "The RemoteSyncObjects of `model-type` whose `parent-rso-key` column is `parent-id`, and that are not pending removal- or deletion."- [model-type :- :string- parent-rso-key :- :keyword- parent-id :- ms/PositiveInt]+ "The RemoteSyncObjects of `model-type` under the Table with `table-id` that are not pending removal or deletion."+ [model-type :- :string+ table-id :- ::lib.schema.id/table](t2/select :model/RemoteSyncObject:model_type model-type- parent-rso-key parent-id+ :model_table_id table-id:status [:not-in ["removed" "delete"]]))-(mu/defn untracked-actions-in-collections- "The `:id`, `:name`, and model `:collection_id` of the unarchived Actions whose unarchived model Card is in the- Collections with `collection-ids`, and that have no Action RemoteSyncObject."- [collection-ids :- [:sequential ::lib.schema.id/collection]]- (t2/query {:select [:a.id :a.name [:c.collection_id :collection_id]]- :from [[:action :a]]- :join [[:report_card :c] [:= :a.model_id :c.id]]- :where [:and- [:in :c.collection_id collection-ids]- [:= :a.archived false]- [:= :c.archived false]- [:not [:exists ^:allow-subquery {:select [1]- :from [:remote_sync_object]- :where [:and- [:= :remote_sync_object.model_type "Action"]- [:= :remote_sync_object.model_id :a.id]]}]]]}))--(mu/defn active-rsos-of-children- "The RemoteSyncObjects of `child-model-type` whose `child-model-key` rows have `fk` equal to `parent-id`, and that- are not pending removal or deletion."- [child-model-key :- :keyword- child-model-type :- :string- fk :- :keyword- parent-id :- ms/PositiveInt]- (t2/select :model/RemoteSyncObject- {:where [:and- [:= :model_type child-model-type]- [:not-in :status ["removed" "delete"]]- [:in :model_id ^:allow-subquery {:select [:id]- :from [(t2/table-name child-model-key)]- :where [:= fk parent-id]}]]}))-(mu/defn content-rso-statuses"The `:id` and `:status` of the RemoteSyncObjects of the Collections with `collection-ids` and their contents."[collection-ids :- [:set ::lib.schema.id/collection]]diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/events.cljindex 7905c9bad42..983fd022aea 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj@@ -67,29 +67,26 @@(remote-sync.db/insert-rsos! rows))(count rows)))-(defn track-untracked-actions!- "Insert a 'create' ledger row for every unarchived Action with none whose model is in the Collections with- `collection-ids`. Returns the number of rows inserted."- [collection-ids]- (let [action-spec (spec/spec-for-model-key :model/Action)- timestamp (t/offset-date-time)- rows (when (seq collection-ids)- (for [action (remote-sync.db/untracked-actions-in-collections (vec collection-ids))]- (merge {:model_type "Action"- :model_id (:id action)- :status "create"- :status_changed_at timestamp}- (spec/build-sync-object-fields action-spec action))))]+(defn backfill-action-tracking!+ "Insert a 'create' ledger row for every unarchived Action in a remote-synced collection that has none, returning the+ number of rows inserted."+ []+ (let [action-spec (spec/spec-for-model-key :model/Action)+ collection-ids (remote-sync.db/remote-synced-collection-ids)+ tracked (remote-sync.db/tracked-model-ids "Action")+ timestamp (t/offset-date-time)+ rows (when (seq collection-ids)+ (for [action (remote-sync.db/instances-in-collections :model/Action collection-ids :archived)+ :when (not (contains? tracked (:id action)))]+ (merge {:model_type "Action"+ :model_id (:id action)+ :status "create"+ :status_changed_at timestamp}+ (spec/build-sync-object-fields action-spec action))))](when (seq rows)(remote-sync.db/insert-rsos! rows))(count rows)))-(defn backfill-action-tracking!- "Insert a 'create' ledger row for every untracked Action of a model in a remote-synced collection, so an instance- upgraded with synced models still pushes their actions. Returns the number of rows inserted."- []- (track-untracked-actions! (remote-sync.db/remote-synced-collection-ids)))-(defn disable-library-tracking!"Remove all snippet, snippets-namespace collection, and glossary tracking entries."[]@@ -230,7 +227,7 @@(defn- cascade-to-children!"When a parent model becomes eligible/ineligible, cascade to its children.For eligible: query child entities using :parent-fk and derived filter, check eligibility, create RSOs.- For ineligible: find the children's active RSOs and mark them as removed."+ For ineligible: query existing RSOs by model_table_id and mark as removed."[model-spec model-id status eligible?](doseq [child-spec (spec/children-specs (:model-key model-spec))](let [fk (:parent-fk child-spec)@@ -241,10 +238,7 @@(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 (if-let [rso-key (:parent-rso-key child-spec)]- (remote-sync.db/active-child-rsos (:model-type child-spec) rso-key model-id)- (remote-sync.db/active-rsos-of-children (:model-key child-spec) (:model-type child-spec)- fk model-id))]+ (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-specdiff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.cljindex 172cdbd4a86..261c67d04ad 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj@@ -63,9 +63,8 @@Takes a sequence of remote-synced collection IDs and imported-data map from spec/extract-imported-entities.For each entity-id based model, deletes entities whose entity_id is not in the imported set.- Models with :scope-key in their spec are scoped to synced collections (using :id for Collection, :model_id through- the model Card for Action, :collection_id for others). Models without :scope-key (like TransformTag) are deleted- globally by entity_id.+ Models with :scope-key in their spec are scoped to synced collections (using :id for Collection, :collection_id+ for others). Models without :scope-key (like TransformTag) are deleted globally by entity_id.Path-based models (Table, Field) are not removed here - they are controlled by published table settings.diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.cljindex c4735e9f391..6e691e9fec5 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj@@ -34,12 +34,9 @@- :model-key - Toucan2 model keyword (e.g., :model/Card)- :identity - Identity strategy: :entity-id, :path, or :hybrid- :path-keys - For :path or :hybrid identity: vector of path components [:database :schema :table :field]- - :parent-model - For :parent-table and :parent eligibility: the parent model key to check eligibility against- (e.g., :model/Table for Field, Segment, Measure; :model/Card for Action)+ - :parent-model - For :parent-table eligibility: the parent model key to check eligibility against+ (e.g., :model/Table for Field, Segment, Measure)- :parent-fk - For child models: the FK column pointing to the parent (e.g., :table_id)- - :parent-rso-key - Optional, for child models whose RemoteSyncObject rows record their parent's id: the- RemoteSyncObject column that holds it (e.g., :model_table_id for Field). A cascade from the- parent then finds the child rows by this column instead of through :parent-fk.- :cascade-filter - Optional map of additional filter conditions for cascade queries.Only needed when the filter differs from {archived-key false}.E.g., Field needs {:active true} since it has no :archived-key.@@ -61,7 +58,7 @@:select-fields - Fields to select for hydration:hydrate-query? - When true, hydrate via the model's`metabase-enterprise.remote-sync.db` tracking-join query instead of- :select-fields (Field, Segment, Measure, Action)+ :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@@ -73,8 +70,6 @@:statuses - Set of statuses to check for removal (e.g., #{\"removed\" \"delete\"}):scope-key - Optional key for scoping deletions (e.g., :collection_id, :id).If nil, deletions are global (by entity_id only).- :scope-table - Optional table that :scope-key points into; the rows are- then scoped to that table's rows in the synced collections (Action):all-on-setting-disable - Optional setting keyword; when this setting's sentinelRSO exists with 'delete' status, remove ALL entities of this type- :resources? - Optional. True when the model's YAML files carry resource files (see@@ -109,19 +104,17 @@{:model-type "Action":model-key :model/Action:identity :entity-id- :delete-after [:model/Card] ; has model_id FK- :parent-model :model/Card- :parent-fk :model_id+ :delete-after [:model/Collection] ; has collection_id FK:events {:prefix :event/action:types [:create :update :delete]}- :eligibility {:type :parent}+ :eligibility {:type :collection+ :collection :remote-synced}:archived-key :archived- :tracking {:hydrate-query? true+ :tracking {:select-fields [:name :collection_id]:field-mappings {:model_name :name:model_collection_id :collection_id}}- :removal {:statuses #{"removed" "delete"}- :scope-key :model_id- :scope-table :report_card}+ :removal {:statuses #{"removed"}+ :scope-key :collection_id}:enabled? true}:model/Dashboard@@ -249,7 +242,6 @@:path-keys [:database :schema :table :field]:parent-model :model/Table:parent-fk :table_id- :parent-rso-key :model_table_id:cascade-filter {:active true}:events {:prefix :event/field:types [:create :update :delete]}@@ -662,12 +654,11 @@category category)}))))(defn removal-opts- "The `metabase-enterprise.remote-sync.db` removal-opts (`:scope-key`, `:scope-table`, `:synced-collection-ids`,- `:entity-ids`, `:removal-conditions`) for removing the entity-id `spec`'s rows not in the import, scoped to+ "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]{:scope-key (get-in spec [:removal :scope-key])- :scope-table (get-in spec [:removal :scope-table]):synced-collection-ids synced-collection-ids:entity-ids entity-ids:removal-conditions (removal-conditions spec)})@@ -851,12 +842,6 @@(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 :parent- [{:keys [parent-model parent-fk]} object]- (when-let [parent-id (get object parent-fk)]- (when-let [parent (remote-sync.db/instance parent-model parent-id)]- (check-eligibility (spec-for-model-key parent-model) parent))))-(defmethod check-eligibility-by-type :setting[{:keys [eligibility]} _object](setting/get-value-of-type :boolean (:setting eligibility)))@@ -1120,9 +1105,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 (if (:hydrate-query? tracking)- (remote-sync.db/tracking-details-by-entity-ids model-key entity-ids)- (remote-sync.db/instances-with-columns-by-entity-ids model-key select-fields 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)diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex 0c12065c267..af9e58b74e3 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -99,7 +99,6 @@"ExplorationQueryResult""ExplorationThread""ExplorationThreadTimeline"- "HTTPAction""ImplicitAction""LoginHistory""McpFeedback"diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.cljindex a25670f1b9b..68e3b585474 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj@@ -811,7 +811,7 @@(repo-files))))))))))(deftest export-includes-model-actions-test- (testing "GHY-4722: pushing a synced model writes its actions to actions/, though the model's YAML doesn't reference them"+ (testing "GHY-4722: pushing a synced model writes its actions into the model's collection"(mt/with-temporary-setting-values [remote-sync-type :read-write](mt/with-actions-enabled(mt/with-model-cleanup [:model/Action :model/Card]@@ -850,8 +850,8 @@:native {:query "UPDATE venues SET name = 'x' WHERE id = 1"}}:parameters []})(is (remote-sync.task/successful? (push!)))- (is (= #{"actions/create_venue.yaml" "actions/rename_venue.yaml"}- (into #{} (filter #(str/starts-with? % "actions/")) (repo-files))))))))))))))+ (is (every? (repo-files) ["collections/main/synced/create_venue.yaml"+ "collections/main/synced/rename_venue.yaml"]))))))))))))(deftest push-tracks-action-changes-on-pushed-model-test(testing "GHY-4722: creating, editing, and deleting an action on an already-pushed model each reach the repo on the next push"@@ -878,7 +878,7 @@:visualization_settings {}:dataset_query (mt/mbql-query venues)})](is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/create_venue.yaml")))+ (is (nil? (repo-file "collections/main/synced/create_venue.yaml")))(let [action (mt/user-http-request :crowberto :post 200 "action"{:name "Create Venue":type "implicit"@@ -886,16 +886,16 @@:model_id (:id model)})](testing "a new action"(is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "actions/create_venue.yaml"))))+ (is (some? (repo-file "collections/main/synced/create_venue.yaml"))))(testing "an edited action"(mt/user-http-request :crowberto :put 200 (str "action/" (:id action)){:description "Adds a venue"})(is (remote-sync.task/successful? (push!)))- (is (str/includes? (str (repo-file "actions/create_venue.yaml")) "Adds a venue")))+ (is (str/includes? (str (repo-file "collections/main/synced/create_venue.yaml")) "Adds a venue")))(testing "a deleted action"(mt/user-http-request :crowberto :delete 204 (str "action/" (:id action)))(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/create_venue.yaml")))))))))))))))+ (is (nil? (repo-file "collections/main/synced/create_venue.yaml")))))))))))))))(defn- do-with-pushed-model!"Pushes a model \"Venues Model\" in a synced collection through the API, then calls `f` with a map of:@@ -946,8 +946,8 @@:commit-remote! commit-remote!}))))))))))(defn- do-with-pushed-model-actions!- "Pushes a synced model with an implicit action (`actions/create_venue.yaml`) and a query action- (`actions/rename_venue.yaml`) through the API, then calls `f` with the map from [[do-with-pushed-model!]]."+ "Pushes a synced model with an implicit action (`collections/main/synced/create_venue.yaml`) and a query action+ (`collections/main/synced/rename_venue.yaml`) through the API, then calls `f` with the map from [[do-with-pushed-model!]]."[f](do-with-pushed-model!(fn [{:keys [model push! repo-file] :as ctx}]@@ -963,18 +963,18 @@:native {:query "UPDATE venues SET name = 'x' WHERE id = 1"}}:parameters []})(is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "actions/create_venue.yaml")))- (is (some? (repo-file "actions/rename_venue.yaml")))+ (is (some? (repo-file "collections/main/synced/create_venue.yaml")))+ (is (some? (repo-file "collections/main/synced/rename_venue.yaml")))(f ctx))))(deftest push-after-model-becomes-question-removes-actions-test- (testing "GHY-4722: turning a pushed model into a question removes its actions from the repo on the next push"+ (testing "turning a pushed model into a question removes its actions from the repo on the next push"(do-with-pushed-model-actions!(fn [{:keys [model push! repo-file]}](mt/user-http-request :crowberto :put 200 (str "card/" (:id model)) {:type "question"})(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/create_venue.yaml")))- (is (nil? (repo-file "actions/rename_venue.yaml")))))))+ (is (nil? (repo-file "collections/main/synced/create_venue.yaml")))+ (is (nil? (repo-file "collections/main/synced/rename_venue.yaml")))))))(deftest push-after-model-query-drops-implicit-actions-test(testing "GHY-4722: a model query that no longer supports implicit actions removes them from the repo on the next push"@@ -983,8 +983,8 @@(mt/user-http-request :crowberto :put 200 (str "card/" (:id model)){:dataset_query (mt/mbql-query venues {:filter [:> $price 1]})})(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/create_venue.yaml")))- (is (some? (repo-file "actions/rename_venue.yaml")) "the query action stays")))))+ (is (nil? (repo-file "collections/main/synced/create_venue.yaml")))+ (is (some? (repo-file "collections/main/synced/rename_venue.yaml")) "the query action stays")))))(deftest push-after-model-deleted-removes-actions-test(testing "GHY-4722: deleting a pushed model removes its actions from the repo on the next push"@@ -992,11 +992,11 @@(fn [{:keys [model push! repo-file]}](mt/user-http-request :crowberto :delete 204 (str "card/" (:id model)))(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/create_venue.yaml")))- (is (nil? (repo-file "actions/rename_venue.yaml")))))))+ (is (nil? (repo-file "collections/main/synced/create_venue.yaml")))+ (is (nil? (repo-file "collections/main/synced/rename_venue.yaml")))))))(defn- insert-untracked-action!- "Inserts an implicit action \"Local Action\" (`actions/local_action.yaml`) on the model with `model-id` straight+ "Inserts an implicit action \"Local Action\" (`collections/main/synced/local_action.yaml`) on the model with `model-id` straightinto the app DB, so no event records it in the remote sync ledger. Returns its id."[model-id](let [action-id (t2/insert-returning-pk! :model/Action {:name "Local Action"@@ -1045,10 +1045,10 @@(let [action-id (t2/select-one-pk :model/Action :model_id (:id model) :name "Rename Venue")](mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived true})(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/rename_venue.yaml")))+ (is (nil? (repo-file "collections/main/synced/rename_venue.yaml")))(mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived false})(is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "actions/rename_venue.yaml"))))))))+ (is (some? (repo-file "collections/main/synced/rename_venue.yaml"))))))))(deftest push-tracks-moving-an-action-between-models-test(testing "GHY-4722: moving an action to a model outside the synced collections removes its file on the next push, and moving it back writes the file again"@@ -1065,10 +1065,10 @@:dataset_query (mt/mbql-query venues)})](mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:model_id (:id other)})(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/rename_venue.yaml")))+ (is (nil? (repo-file "collections/main/synced/rename_venue.yaml")))(mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:model_id (:id model)})(is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "actions/rename_venue.yaml")))))))))+ (is (some? (repo-file "collections/main/synced/rename_venue.yaml")))))))))(deftest turning-sync-on-again-tracks-untracked-actions-test(testing "GHY-4722: turning sync on again for a collection tracks an action created while sync was off, and the next push writes it"@@ -1079,7 +1079,7 @@(mt/user-http-request :crowberto :put 200 "ee/remote-sync/settings" {:collections {coll-id true}})(is (= "create" (action-rso-status action-id)))(is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "actions/local_action.yaml"))))))))+ (is (some? (repo-file "collections/main/synced/local_action.yaml"))))))))(deftest archiving-a-collection-marks-its-actions-for-deletion-test(testing "GHY-4722: archiving the synced collection that holds a model marks its actions for deletion, and the next push removes their files"@@ -1089,8 +1089,8 @@(mt/user-http-request :crowberto :put 200 (str "collection/" coll-id) {:archived true})(is (= "delete" (action-rso-status action-id)))(is (remote-sync.task/successful? (push!)))- (is (nil? (repo-file "actions/rename_venue.yaml")))- (is (nil? (repo-file "actions/create_venue.yaml"))))))))+ (is (nil? (repo-file "collections/main/synced/rename_venue.yaml")))+ (is (nil? (repo-file "collections/main/synced/create_venue.yaml"))))))))(deftest upgrade-backfill-requires-a-push-before-a-pull-test(testing "GHY-4722: after the upgrade backfill tracks an existing action, a pull is refused until a push writes the action to the repo"@@ -1104,7 +1104,7 @@(:message (mt/user-http-request :crowberto :post 400 "ee/remote-sync/import" {:expected_branch "main"})))))(testing "a push writes the action to the repo"(is (remote-sync.task/successful? (push!)))- (is (some? (repo-file "actions/local_action.yaml"))))+ (is (some? (repo-file "collections/main/synced/local_action.yaml"))))(testing "a normal pull after another instance's change keeps the action"(commit-remote! {:upsert {model-path (str/replace (repo-file model-path) "name: Venues Model" "name: Renamed Model")}})(is (remote-sync.task/successful? (pull!)))@@ -2436,3 +2436,30 @@"no new branch should be pushed to the source when the guard fires")(is (= tasks-before (t2/count :model/RemoteSyncTask))"no NEW RemoteSyncTask row should be created when the guard fires")))))))++(deftest moving-an-action-out-from-under-a-synced-dashboard-test+ (testing "an action a synced dashboard uses cannot move out of the synced collections"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :is_remote_synced true :location "/"}+ :model/Collection {plain-id :id} {:name "Plain" :location "/"}+ :model/Action {action-id :id} {:type :query :name "No model" :model_id nil+ :collection_id synced-id}+ :model/QueryAction _ {:action_id action-id+ :dataset_query (mt/native-query {:query "select 1"})}+ :model/Dashboard {dashboard-id :id} {:collection_id synced-id}+ :model/DashboardCard _ {:dashboard_id dashboard-id :action_id action-id}]+ (is (= "Used by remote synced content."+ (:message (mt/user-http-request :crowberto :put 400 (str "action/" action-id)+ {:collection_id plain-id}))))+ (is (= synced-id (t2/select-one-fn :collection_id :model/Action :id action-id))))))))++(deftest archiving-a-synced-model-with-actions-test+ (testing "a model in a synced collection can be archived although it has actions, which are archived with it"+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :is_remote_synced true :location "/"}+ :model/Card {model-id :id} {:type :model :collection_id synced-id+ :dataset_query (mt/mbql-query venues)}+ :model/Action {action-id :id} {:type :query :name "Rename" :model_id model-id}]+ (mt/user-http-request :crowberto :put 200 (str "card/" model-id) {:archived true})+ (is (true? (t2/select-one-fn :archived :model/Action :id action-id)))))))diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.cljindex 9b9512936e1..51d61a43639 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj@@ -141,7 +141,7 @@(t2/select-one :model/RemoteSyncObject :model_type "Action" :model_id action-id))(deftest action-create-event-creates-entry-test- (testing "GHY-4722: action-create on a synced model tracks the action under its model's collection"+ (testing "action-create on a synced model tracks the action under its model's collection";; remote-sync-type defaults to :read-only, where synced items are not tracked(mt/with-temporary-setting-values [remote-sync-type :read-write](mt/with-temp [:model/Collection {coll-id :id} {:is_remote_synced true :name "Remote-Sync"}@@ -162,33 +162,21 @@(events/publish-event! :event/action-create {:object action :user-id (mt/user->id :rasta)})(is (nil? (action-rso (:id action))))))))-(deftest model-events-cascade-to-actions-test- (testing "GHY-4722: a model's events carry to its actions"+(deftest action-moved-with-its-model-test+ (testing "an action that moves out of synced collections with its model is marked removed"(mt/with-temporary-setting-values [remote-sync-type :read-write](mt/with-temp [:model/Collection {synced-id :id} {:is_remote_synced true :name "Remote-Sync"}:model/Collection {plain-id :id} {:name "Normal"}- :model/Card model {:type :model :collection_id synced-id}- :model/Action {action-id :id} {:type :implicit :name "Create Venue" :model_id (:id model)}]- (let [seed! (fn []- (t2/delete! :model/RemoteSyncObject)- (t2/insert! :model/RemoteSyncObject- [{:model_type "Card" :model_id (:id model) :model_name "M" :status "synced"- :status_changed_at (t/offset-date-time)}- {:model_type "Action" :model_id action-id :model_name "Create Venue" :status "synced"- :status_changed_at (t/offset-date-time)}]))]- (testing "archiving the model marks its actions for deletion"- (seed!)- (events/publish-event! :event/card-update {:object (assoc model :archived true)- :previous-object model- :user-id (mt/user->id :rasta)})- (is (=? {:status "delete"} (action-rso action-id))))- (testing "moving the model out of synced collections marks its actions removed"- (seed!)- (t2/update! :model/Card (:id model) {:collection_id plain-id})- (events/publish-event! :event/card-update {:object (assoc model :collection_id plain-id)- :previous-object model- :user-id (mt/user->id :rasta)})- (is (=? {:status "removed"} (action-rso action-id)))))))))+ :model/Card {model-id :id} {:type :model :collection_id synced-id}+ :model/Action {action-id :id} {:type :implicit :name "Create Venue" :model_id model-id}]+ (t2/delete! :model/RemoteSyncObject)+ (t2/insert! :model/RemoteSyncObject {:model_type "Action" :model_id action-id :model_name "Create Venue"+ :model_collection_id synced-id :status "synced"+ :status_changed_at (t/offset-date-time)})+ (t2/update! :model/Card model-id {:collection_id plain-id})+ (events/publish-event! :event/action-update {:object (t2/select-one :model/Action :id action-id)+ :user-id (mt/user->id :rasta)})+ (is (=? {:status "removed"} (action-rso action-id)))))))(deftest dashboard-create-event-creates-entry-test(testing "dashboard-create event creates remote sync object entry with create status"diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.cljindex 5afdf0d3589..8b85d0da96f 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj@@ -100,10 +100,8 @@(is (= 1 (count children)))(is (= #{:model/Field}(into #{} (map :model-key) children)))))- (testing "GHY-4722: children-specs derives Action as a child of Card"- (is (= [:model/Action] (map :model-key (spec/children-specs :model/Card)))))(testing "children-specs returns empty for models with no children"- (is (empty? (spec/children-specs :model/Dashboard)))))+ (is (empty? (spec/children-specs :model/Card)))));;; ------------------------------------------------ Helper Function Tests ---------------------------------------------@@ -344,7 +342,7 @@(f {:synced-coll synced-coll :synced-action synced-action :plain-action plain-action})))(deftest action-eligibility-follows-model-test- (testing "GHY-4722: an action is eligible for remote sync exactly when its model is"+ (testing "an action takes its model's collection, so it is eligible for remote sync exactly when its model is"(do-with-synced-and-plain-actions!(fn [{:keys [synced-action plain-action]}](let [action-spec (spec/spec-for-model-key :model/Action)]@@ -352,7 +350,7 @@(is (false? (spec/check-eligibility action-spec (t2/select-one :model/Action :id plain-action)))))))))(deftest action-removal-scoped-to-synced-models-test- (testing "GHY-4722: a pull removes absent actions only when their model is in a synced collection"+ (testing "a pull removes absent actions only when they are in a synced collection"(do-with-synced-and-plain-actions!(fn [{:keys [synced-coll synced-action plain-action]}](remote-sync.db/delete-removed-instances!diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex 5131b320585..b9d5276befd 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -42,7 +42,6 @@:model/AnalysisFindingError:model/ApiKey:model/AuthIdentity- :model/HTTPAction:model/ImplicitAction:model/QueryAction:model/ApplicationPermissionsRevisiondiff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.cljindex 5820ea4f0a1..f11e3815a13 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj@@ -122,11 +122,11 @@(ts/with-db source-db(testing "insert"(test-gen/insert!- {;; Actions are special case where there is a 1:1 relationship between an action and an action subtype (query, implicit, or http)+ {;; Actions are special case where there is a 1:1 relationship between an action and an action subtype (query or implicit);; We generate 10 actions for each subtype, and 10 of each subtype.- ;; actions 0-9 are query actions, 10-19 are implicit actions, and 20-29 are http actions.+ ;; actions 0-9 are query actions, and 10-19 are implicit actions.:action (apply concat- (for [type [:query :implicit :http]]+ (for [type [:query :implicit]](many-random-fks 10{:spec-gen {:type type}}{:model_id [:sm 10]@@ -141,12 +141,6 @@(fn [refs](assoc refs :action_id (keyword (str "action" (+ 10 idx)))))))(many-random-fks 10 {} {}))- :http-action (map-indexed- (fn [idx x]- (update-in x [1 :refs]- (fn [refs]- (assoc refs :action_id (keyword (str "action" (+ 20 idx)))))))- (many-random-fks 10 {} {})):collection [[100 {:refs {:personal_owner_id ::rs/omit}}][10 {:refs {:personal_owner_id ::rs/omit}:spec-gen {:namespace :snippets}}]]@@ -223,7 +217,10 @@(testing "storage"(storage/store! (seq @extraction) (storage.files/file-writer dump-dir))(testing "for Actions"- (is (= 30 (count (dir->file-set (io/file dump-dir "actions"))))))+ (let [main-dir (io/file dump-dir "collections" "main")]+ (is (= 20 (count (for [f (file-set main-dir)+ :when (= "Action" (yaml-model-at main-dir f))]+ f))))))(testing "for Collections";; +1 for the Trash collection(let [colls-dir (io/file dump-dir "collections")@@ -258,7 +255,7 @@;; exact count may vary by 1 depending on naming collisions with collection names(let [main-dir (io/file dump-dir "collections" "main")](is (<= 269 (count (for [f (file-set main-dir)- :when (not= "Collection" (yaml-model-at main-dir f))]+ :when (not (#{"Collection" "Action"} (yaml-model-at main-dir f)))]f)) 271))))(testing "for segments"(is (= 30 (reduce + (for [db (dir->dir-set (io/file dump-dir "databases"))diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.cljindex b22944da34f..0ec6adc4335 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj@@ -115,6 +115,41 @@(is (some (partial re-find #"Invalid input.*:template-tags") messages))(is (not (ours? messages)))))))))))+(deftest http-action-dashcards-are-dropped-test+ (testing "an older export's HTTP action does not load, and only the dashboard buttons that ran it are dropped"+ (let [serialized (atom nil)]+ (ts/with-dbs [source-db dest-db]+ (ts/with-db source-db+ (let [db (ts/create! :model/Database :name "my-db")+ coll (ts/create! :model/Collection :name "Actions")+ model (ts/create! :model/Card+ :name "A model"+ :type :model+ :collection_id (:id coll)+ :database_id (:id db)+ :dataset_query {:database (:id db)+ :type :native+ :native {:query "SELECT 1"}})+ action (ts/create! :model/Action :name "Old HTTP" :type :query :model_id (:id model))+ _ (ts/create! :model/QueryAction+ :action_id (:id action)+ :dataset_query {:database (:id db) :type :native :native {:query "UPDATE t SET x = 1"}})+ dashboard (ts/create! :model/Dashboard :name "Buttons" :collection_id (:id coll))]+ (ts/create! :model/DashboardCard :dashboard_id (:id dashboard) :action_id (:id action))+ (ts/create! :model/DashboardCard :dashboard_id (:id dashboard) :card_id (:id model))+ (reset! serialized (into [] (serdes.extract/extract {})))))+ (ts/with-db dest-db+ (serdes.load/load-metabase! (ingestion-in-memory+ (for [entity @serialized]+ (cond-> entity+ (= "Action" (-> entity :serdes/meta last :model))+ (-> (assoc :type "http") (dissoc :query))))))+ (let [dashboard-id (t2/select-one-pk :model/Dashboard :name "Buttons")]+ (is (not (t2/exists? :model/Action :name "Old HTTP")))+ (is (some? dashboard-id))+ (is (=? [{:card_id pos-int? :action_id nil}]+ (t2/select :model/DashboardCard :dashboard_id dashboard-id)))))))))+(deftest load-basics-test(testing "a simple, fresh collection is imported"(let [serialized (atom nil)diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.cljindex d8f8930c6a0..224024de760 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/models_test.clj@@ -159,7 +159,7 @@;; check applies to the parent's `dependencies`, not theirs. Skipped either;; via the explicit list in `serdes.models/inlined-models` or by detecting a;; nil `generate-path` (the convention for nested-only models like- ;; QueryAction / HTTPAction / ImplicitAction).+ ;; QueryAction / ImplicitAction).:when (not (or (inlined? m) (inlined-via-nested? m))):let [fks (->> (:transform (serdes/make-spec m nil))direct-fksdiff --git a/frontend/src/metabase-types/analytics/action.ts b/frontend/src/metabase-types/analytics/action.tsindex c64157dad97..b2dfebc317e 100644--- a/frontend/src/metabase-types/analytics/action.ts+++ b/frontend/src/metabase-types/analytics/action.ts@@ -11,7 +11,7 @@ type ValidateEvent<Record<Exclude<keyof T, keyof ActionEventSchema>, never>,> = T;-type ActionType = "http" | "query" | "implicit";+type ActionType = "query" | "implicit";export type ActionCreatedEvent = ValidateEvent<{event: "action_created";diff --git a/frontend/src/metabase-types/api/actions.ts b/frontend/src/metabase-types/api/actions.tsindex a0a3066ca29..ea164f2ee79 100644--- a/frontend/src/metabase-types/api/actions.ts+++ b/frontend/src/metabase-types/api/actions.ts@@ -14,15 +14,12 @@ export interface CreateActionRequest {database_id?: DatabaseId;dataset_query?: NativeDatasetQuery;description?: string | null;- error_handle?: string | null;kind?: "row/create" | "row/update" | "row/delete";model_id: CardId;name: string;parameter_mappings?: Record<ParameterId, ParameterTarget>;parameters?: WritebackParameter[];- response_handle?: string | null;- template?: HttpActionTemplate;- type?: "query" | "implicit" | "http";+ type?: "query" | "implicit";visualization_settings?: ActionFormSettings;}@@ -32,17 +29,11 @@ export interface UpdateActionRequest {database_id?: DatabaseId;dataset_query?: NativeDatasetQuery;description?: string | null;- error_handle?: string | null;kind?: "row/create" | "row/update" | "row/delete";model_id?: CardId;name?: string;parameter_mappings?: Record<ParameterId, ParameterTarget>;parameters?: WritebackParameter[];- response_handle?: string | null;- template?: HttpActionTemplate;- url?: string;- body?: string;- headers?: string;visualization_settings?: ActionFormSettings;}@@ -50,7 +41,7 @@ export interface WritebackParameter extends Parameter {target: ParameterTarget;}-export type WritebackActionType = "http" | "query" | "implicit";+export type WritebackActionType = "query" | "implicit";export type WritebackActionId = number;@@ -87,31 +78,11 @@ export interface ImplicitQueryAction {kind: "row/create" | "row/update" | "row/delete";}-export interface HttpAction {- type: "http";- template: HttpActionTemplate;- response_handle: string | null;- error_handle: string | null;-}--export type HttpActionResponseHandle = any;-export type HttpActionErrorHandle = any;--export interface HttpActionTemplate {- method: string;- url: string;- body: string;- headers: string;- parameters: Record<ParameterId, Parameter>;- parameter_mappings: Record<ParameterId, ParameterTarget>;-}-export type WritebackQueryAction = WritebackActionBase & QueryAction;export type WritebackImplicitQueryAction = WritebackActionBase &ImplicitQueryAction;-export type WritebackHttpAction = WritebackActionBase & HttpAction;export type WritebackAction = WritebackActionBase &- (QueryAction | ImplicitQueryAction | HttpAction);+ (QueryAction | ImplicitQueryAction);export type ParameterMappings = Record<ParameterId, ParameterTarget>;diff --git a/frontend/src/metabase/api/action.ts b/frontend/src/metabase/api/action.tsindex 7061d4b4b40..e11309fc0eb 100644--- a/frontend/src/metabase/api/action.ts+++ b/frontend/src/metabase/api/action.ts@@ -59,27 +59,21 @@ export const actionApi = Api.injectEndpoints({// (including server-managed fields like `creator`, `created_at`,// `database_enabled_actions`, ...). The backend routes anything// outside the Action columns to the type-specific update table- // (query_action / implicit_action / http_action), where those+ // (query_action / implicit_action), where those// columns don't exist and the request 500s. Whitelist only the// fields that the API endpoint actually accepts.body: _.pick(body, ["id","archived",- "body","database_id","dataset_query","description",- "error_handle",- "headers","kind","model_id","name","parameter_mappings","parameters","public_uuid",- "response_handle",- "template",- "url","visualization_settings",]),}),diff --git a/resources/migrations/065/20261002_action_collection_id.yaml b/resources/migrations/065/20261002_action_collection_id.yamlnew file mode 100644index 00000000000..38da0e6bfa4--- /dev/null+++ b/resources/migrations/065/20261002_action_collection_id.yaml@@ -0,0 +1,114 @@+## Actions become collection items: an action no longer needs a model, and carries its own collection_id. An action+## attached to a model keeps the model's collection (Toucan hooks keep the two in sync).++databaseChangeLog:+ - changeSet:+ id: v65.2026-10-02T00:00:00+ author: ranquild+ comment: Make action.model_id nullable+ changes:+ - dropNotNullConstraint:+ tableName: action+ columnName: model_id+ columnDataType: int+ rollback:+ - sql:+ sql: DELETE FROM action WHERE model_id IS NULL+ - addNotNullConstraint:+ tableName: action+ columnName: model_id+ columnDataType: int++ - changeSet:+ id: v65.2026-10-02T00:00:01+ author: ranquild+ comment: Add action.collection_id+ changes:+ - addColumn:+ tableName: action+ columns:+ - column:+ name: collection_id+ type: int+ remarks: The Collection this Action is in; the model's Collection when the Action has a model+ constraints:+ nullable: true+ rollback:+ - dropColumn:+ tableName: action+ columnName: collection_id++ - changeSet:+ id: v65.2026-10-02T00:00:02+ author: ranquild+ comment: Index action.collection_id+ changes:+ - createIndex:+ tableName: action+ indexName: idx_action_collection_id+ columns:+ - column:+ name: collection_id++ - changeSet:+ id: v65.2026-10-02T00:00:03+ author: ranquild+ comment: Add FK constraint on action.collection_id+ changes:+ - addForeignKeyConstraint:+ baseTableName: action+ baseColumnNames: collection_id+ referencedTableName: collection+ referencedColumnNames: id+ constraintName: fk_action_collection_id+ onDelete: SET NULL++ - changeSet:+ id: v65.2026-10-02T00:00:04+ author: ranquild+ comment: Backfill action.collection_id from the model's collection+ changes:+ - sql:+ sql: >-+ UPDATE action+ SET collection_id = (SELECT report_card.collection_id FROM report_card WHERE report_card.id = action.model_id)+ WHERE model_id IS NOT NULL;+ rollback: # nothing to do; rolling back the preceding changesets drops the column++ - changeSet:+ id: v65.2026-10-02T00:00:05+ author: ranquild+ comment: Add action.archived_directly+ changes:+ - addColumn:+ tableName: action+ columns:+ - column:+ name: archived_directly+ type: ${boolean.type}+ remarks: Whether the Action was archived directly, rather than along with its model or collection+ defaultValueBoolean: false+ constraints:+ nullable: false++ - changeSet:+ id: v65.2026-10-02T00:00:06+ author: ranquild+ comment: Mark already-archived actions as archived directly+ changes:+ - sql:+ sql: UPDATE action SET archived_directly = TRUE WHERE archived = TRUE;+ rollback: # nothing to do; rolling back the preceding changeset drops the column++ - changeSet:+ id: v65.2026-10-02T00:00:07+ author: ranquild+ comment: Archive the actions of models that are already archived, as archiving a model now does+ changes:+ - sql:+ sql: >-+ UPDATE action+ SET archived = TRUE, archived_directly = FALSE+ WHERE archived = FALSE+ AND EXISTS (SELECT 1 FROM report_card WHERE report_card.id = action.model_id AND report_card.archived = TRUE);+ rollback: # nothing to do; rolling back the preceding changesets drops the columndiff --git a/resources/migrations/065/20261003_drop_http_actions.yaml b/resources/migrations/065/20261003_drop_http_actions.yamlnew file mode 100644index 00000000000..a5ea0d5472f--- /dev/null+++ b/resources/migrations/065/20261003_drop_http_actions.yaml@@ -0,0 +1,50 @@+## HTTP actions are removed: their rows go (dashboard cards and http_action rows cascade) and so does their table.++databaseChangeLog:+ - changeSet:+ id: v65.2026-10-03T00:00:00+ author: ranquild+ comment: Delete HTTP actions+ changes:+ - sql:+ sql: DELETE FROM action WHERE type = 'http';+ rollback: # nothing to do; the deleted actions cannot be restored++ - changeSet:+ id: v65.2026-10-03T00:00:01+ author: ranquild+ comment: Drop http_action+ changes:+ - dropTable:+ tableName: http_action+ rollback:+ - createTable:+ tableName: http_action+ remarks: An http api call type of action+ columns:+ - column:+ name: action_id+ type: int+ remarks: The related action+ constraints:+ nullable: false+ primaryKey: true+ primaryKeyName: pk_http_action+ referencedTableName: action+ referencedColumnNames: id+ foreignKeyName: fk_http_action_ref_action_id+ deleteCascade: true+ - column:+ name: template+ type: ${text.type}+ remarks: A template that defines method,url,body,headers required to make an api call+ constraints:+ nullable: false+ - column:+ name: response_handle+ type: ${text.type}+ remarks: A program to take an api response and transform to an appropriate response for emitters+ - column:+ name: error_handle+ type: ${text.type}+ remarks: A program to take an api response to determine if an error occurreddiff --git a/src/metabase/actions/actions.clj b/src/metabase/actions/actions.cljindex 8bcb88c702d..7f8afb5aaf1 100644--- a/src/metabase/actions/actions.clj+++ b/src/metabase/actions/actions.clj@@ -120,7 +120,7 @@(swap! *misc-value-cache* assoc unique-key value))value)))-(defn check-actions-enabled-for-database!+(defn check-actions-enabled-for-database"Throws an appropriate error if actions are unsupported or disabled for a database, otherwise returns nil."[{db-id :id driver :engine db-name :name :as db}](when-not (driver.u/supports? driver :actions db)@@ -136,7 +136,7 @@nil)-(defn check-data-editing-enabled-for-database!+(defn check-data-editing-enabled-for-database"Throws an appropriate error if editing is unsupported or disabled for a database, otherwise returns nil."[{db-id :id driver :engine db-name :name :as db}](when-not (driver.u/supports? driver :actions/data-editing db)@@ -155,11 +155,11 @@(defn- database-for-action [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,- otherwise returns nil."+(defn check-actions-enabled+ "Throws an appropriate error if actions are unsupported or disabled for the database the action runs against,+ otherwise returns nil."[action-or-id]- (check-actions-enabled-for-database! (api/check-404 (database-for-action action-or-id))))+ (check-actions-enabled-for-database (api/check-404 (database-for-action action-or-id))))(defmulti handle-effects!*"Trigger bulk side effects in response to individual effects within actions, e.g. table row modified system events."@@ -331,15 +331,15 @@(when db(case policy:ad-hoc-invocation- (check-actions-enabled-for-database! db)+ (check-actions-enabled-for-database db):model-action- (check-actions-enabled-for-database! db)+ (check-actions-enabled-for-database db):data-editing(do;; TODO more granular controls(when-not (api/check-superuser)(throw (ex-info (tru "You don''t have permissions to do that.") {:status-code 403})))- (check-data-editing-enabled-for-database! db))))+ (check-data-editing-enabled-for-database db))))(log/with-context {:db-id (:id db)}(binding [*misc-value-cache* (atom {:databases (zipmap (map :id dbs) dbs)})](let [context (-> existing-contextdiff --git a/src/metabase/actions/core.clj b/src/metabase/actions/core.cljindex bd19fdf9aa1..1bf6cf053e1 100644--- a/src/metabase/actions/core.clj+++ b/src/metabase/actions/core.clj@@ -7,7 +7,6 @@[metabase.actions.events][metabase.actions.execution][metabase.actions.hierarchy]- [metabase.actions.http-action][metabase.actions.models][metabase.actions.scope][potemkin :as p]))@@ -17,16 +16,15 @@metabase.actions.error/keep-memetabase.actions.execution/keep-memetabase.actions.hierarchy/keep-me- metabase.actions.http-action/keep-memetabase.actions.models/keep-memetabase.actions.scope/keep-me)(p/import-vars[metabase.actions.actionscached-value- check-actions-enabled!- check-actions-enabled-for-database!- check-data-editing-enabled-for-database!+ check-actions-enabled+ check-actions-enabled-for-database+ check-data-editing-enabled-for-databasecached-databasecached-database-via-table-idcached-table@@ -54,16 +52,15 @@execute-action!execute-dashcard!fetch-values]- [metabase.actions.http-action- apply-json-query][metabase.actions.models+ check-action-databases-enabled+ check-implicit-actions-supporteddashcard->actioninsert!select-actionselect-actionsselect-actions-for-idsselect-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.cljindex b197c03b3ef..58273033f19 100644--- a/src/metabase/actions/db.clj+++ b/src/metabase/actions/db.clj@@ -11,14 +11,20 @@[metabase.warehouse-schema-overlay.core :as warehouse-schema-overlay][toucan2.core :as t2]))+(defn- action-database-joins+ "The joins from `action` to the Database `db` of its query, or of its model Card for an implicit action."+ []+ [[(t2/table-name :model/QueryAction) :qa] [:= :qa.action_id :action.id]+ [(t2/table-name :model/Card) :card] [:and [:= :card.id :action.model_id] [:= :action.type "implicit"]]+ [(t2/table-name :model/Database) :db] [:= :db.id [:coalesce :qa.database_id :card.database_id]]])+(mu/defn database-for-action- "The Database of the model Card of the Action with `action-id`, or nil."+ "The Database the Action with `action-id` runs against: its query's, or its model's for an implicit action, or nil."[action-id :- ::lib.schema.id/action]- (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]}))+ (t2/select-one :model/Database {:select [:db.*]+ :from [[(t2/table-name :model/Action) :action]]+ :left-join (action-database-joins)+ :where [:and [:= :action.id action-id] [:not= :db.id nil]]}))(mu/defn table-database-id"The Database id of the Table with `table-id`, or nil."@@ -50,6 +56,26 @@[card-id :- ::lib.schema.id/card](t2/select-one-fn :type [:model/Card :type] :id card-id))+(mu/defn card-collection-id+ "The Collection id of the Card with `card-id`, or nil."+ [card-id :- ::lib.schema.id/card]+ (t2/select-one-fn :collection_id [:model/Card :collection_id] :id card-id))++(mu/defn collection-exists?+ "Whether the Collection with `collection-id` exists."+ [collection-id :- ::lib.schema.id/collection]+ (t2/exists? :model/Collection :id collection-id))++(mu/defn unarchived-collection-exists?+ "Whether the unarchived Collection with `collection-id` exists."+ [collection-id :- ::lib.schema.id/collection]+ (t2/exists? :model/Collection :id collection-id :archived false))++(mu/defn action-model-id+ "The model Card id of the Action with `action-id`, or nil."+ [action-id :- ::lib.schema.id/action]+ (t2/select-one-fn :model_id [:model/Action :model_id] :id action-id))+(mu/defn table"The Table with `table-id`, or nil."[table-id :- [:maybe ::lib.schema.id/table]]@@ -107,11 +133,6 @@[action :- ::actions.schema/query-action.update](t2/insert! :model/QueryAction action))-(mu/defn insert-http-action!- "Insert the HTTPAction `action`, returning the number inserted."- [action :- ::actions.schema/httpaction.update]- (t2/insert! :model/HTTPAction action))-(mu/defn insert-implicit-action!"Insert the ImplicitAction `action`, returning the number inserted."[action :- ::actions.schema/implicit-action.update]@@ -123,12 +144,6 @@changes :- ::actions.schema/query-action.update](t2/update! :model/QueryAction action-id changes))-(mu/defn update-http-action!- "Apply `changes` to the HTTPAction with `action-id`, returning the number updated."- [action-id :- ::lib.schema.id/action- changes :- ::actions.schema/httpaction.update]- (t2/update! :model/HTTPAction action-id changes))-(mu/defn update-implicit-action!"Apply `changes` to the ImplicitAction with `action-id`, returning the number updated."[action-id :- ::lib.schema.id/action@@ -140,11 +155,6 @@[action-id :- ::lib.schema.id/action](t2/delete! :model/QueryAction :action_id action-id))-(mu/defn delete-http-action!- "Delete the HTTPAction of the Action with `action-id`, returning the number deleted."- [action-id :- ::lib.schema.id/action]- (t2/delete! :model/HTTPAction :action_id action-id))-(mu/defn delete-implicit-action!"Delete the ImplicitAction of the Action with `action-id`, returning the number deleted."[action-id :- ::lib.schema.id/action]@@ -160,11 +170,6 @@[action-id :- ::lib.schema.id/action](t2/select-one :model/QueryAction :action_id action-id))-(mu/defn http-actions- "The HTTPActions of the Actions with `action-ids`."- [action-ids :- [:sequential ::lib.schema.id/action]]- (t2/select :model/HTTPAction :action_id [:in action-ids]))-(mu/defn implicit-actions"The ImplicitActions of the Actions with `action-ids`."[action-ids :- [:sequential ::lib.schema.id/action]]@@ -190,26 +195,11 @@[entity-id :- :string](t2/select :model/Action :entity_id entity-id))-(mu/defn actions-of-type- "The Actions of `action-type`."- [action-type :- :keyword]- (t2/select :model/Action :type action-type))-(mu/defn unarchived-actions-for-models"The unarchived Actions whose `:model_id` is in `model-ids`."[model-ids :- [:sequential ms/PositiveInt]](t2/select :model/Action :model_id [:in model-ids] :archived false))-(mu/defn unarchived-non-http-actions-for-model- "The unarchived, non-HTTP Actions of the model Card with `model-id`."- [model-id :- ms/PositiveInt]- (t2/select :model/Action :model_id model-id :archived false :type [:not= "http"]))--(mu/defn unarchived-non-http-actions-for-models- "The unarchived, non-HTTP Actions whose `:model_id` is in `model-ids`."- [model-ids :- [:set ms/PositiveInt]]- (t2/select :model/Action :model_id [:in model-ids] :archived false :type [:not= "http"]))-(mu/defn fields-for-parameters"The id, base type, display name, and description of the Fields with `field-ids`."[field-ids :- [:set ::lib.schema.id/field]]@@ -218,11 +208,10 @@(mu/defn action-database-settings"The id and Database settings of the Actions with `action-ids`."[action-ids :- [:sequential ::lib.schema.id/action]]- (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]}))+ (t2/query {:select [:action.id :db.settings]+ :from [[(t2/table-name :model/Action) :action]]+ :left-join (action-database-joins)+ :where [:and [:in :action.id action-ids] [:not= :db.id nil]]}))(mu/defn card-scope-columns"The query-relevant columns of the Card with `card-id`, plus its Collection id and display, or nil."diff --git a/src/metabase/actions/execution.clj b/src/metabase/actions/execution.cljindex f6ebd75b0c8..a8dc83df587 100644--- a/src/metabase/actions/execution.clj+++ b/src/metabase/actions/execution.clj@@ -6,7 +6,6 @@[metabase.actions.args :as actions.args][metabase.actions.audit :as actions.audit][metabase.actions.db :as actions.db]- [metabase.actions.http-action :as http-action][metabase.actions.models :as action][metabase.actions.schema :as actions.schema][metabase.analytics.core :as analytics]@@ -17,6 +16,7 @@[metabase.lib.schema.id :as lib.schema.id][metabase.lib.schema.parameter :as lib.schema.parameter][metabase.model-persistence.core :as model-persistence]+ [metabase.models.interface :as mi][metabase.parameters.schema :as parameters.schema][metabase.queries.models.query :as query][metabase.query-processor.card :as qp.card]@@ -36,19 +36,25 @@(def ^:private ExecuteActionOpts[:map {:closed true}- [:allow-http-actions? {:optional true} [:maybe :boolean]][:context {:optional true} [:maybe :keyword]][:dashboard-id {:optional true} [:maybe ms/PositiveInt]]])+(defn- check-action-read-perms+ "Throws a permissions error unless the current user, when there is one, can read `action`."+ [action]+ (when (and api/*current-user-id* (not (mi/can-read? action)))+ (throw (ex-info (tru "You do not have permissions to run this action.")+ {:type qp.error-type/missing-required-permissions, :status-code 403}))))+(mu/defn- execute-query-action!"Execute a `QueryAction` with parameters as passed in from anendpoint of shape `{<parameter-id> <value>}`.`action` should already be hydrated with its `:card`. `opts` carries the audit attribution from the endpoint."- [{query :dataset_query, model-id :model_id, :as action} :- ::actions.schema/action+ [{query :dataset_query, action-id :id, :as action} :- ::actions.schema/actionrequest-parameters :- RequestParametersopts :- [:maybe ExecuteActionOpts]]- (log/tracef "Executing action for model %d" model-id)+ (log/tracef "Executing action %d" action-id)(driver.conn/with-write-connection(try(let [parameters (for [parameter (:parameters action)]@@ -61,19 +67,20 @@;; the routed destination database and the impersonation flag are only knowable from inside the;; writeback QP's middleware stackexecution-context (volatile! nil)]- (binding [qp.perms/*card-id* model-id]- (actions.audit/with-audited-execution- {:action :query/execute- :action-id (:id action)- :dashboard-id (:dashboard-id opts)- :database-id (:database substituted-query)- :user-id api/*current-user-id*- :context (:context opts :action-execute)- :native? true- :template (dissoc query :parameters :info)- :inputs (filterv (comp some? :value) parameters)}- (fn [result]- (merge {:result_rows (or (:rows-affected result) 0)} @execution-context))+ (actions.audit/with-audited-execution+ {:action :query/execute+ :action-id action-id+ :dashboard-id (:dashboard-id opts)+ :database-id (:database substituted-query)+ :user-id api/*current-user-id*+ :context (:context opts :action-execute)+ :native? true+ :template (dissoc query :parameters :info)+ :inputs (filterv (comp some? :value) parameters)}+ (fn [result]+ (merge {:result_rows (or (:rows-affected result) 0)} @execution-context))+ (do+ (check-action-read-perms action)(qp/do-with-captured-execution-context #(qp/execute-write-query! substituted-query)#(vreset! execution-context %)))))(catch Throwable e@@ -91,51 +98,24 @@(t2/hydrate (actions.db/table table-id) :fields)))(defn- execute-custom-action! [action request-parameters opts]- (let [{action-type :type, action-id :id} action]- (actions/check-actions-enabled! action)- (let [model (actions.db/card (:model_id action))- ;; the query executes against its own :database; fall back to the derived column if absent- action-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!- (actions.db/database action-db-id))))- (try- (case action-type- :query- (execute-query-action! action request-parameters opts)-- :http- ;; `execute-http-action!` refuses every call today, so this records the refused attempt. The template holds- ;; `url`/`headers`/`body`, which may carry credentials and `query.query` is plaintext -- so the hash- ;; identifies the action, never its content.- (actions.audit/with-audited-execution- {:action :http/execute- :action-id action-id- :dashboard-id (:dashboard-id opts)- :database-id nil- :user-id api/*current-user-id*- :context (:context opts :action-execute)- :native? false- :template {:type :internal, :action :http/execute, :action-id action-id}- :inputs (if (seq request-parameters) [request-parameters] [])}- (constantly {:result_rows 0})- (http-action/execute-http-action! action request-parameters)))- (catch Exception e- (log/errorf "Error executing action: %s" (ex-message e))- (if-let [ed (ex-data e)]- (let [ed (cond-> ed- (and (nil? (:status-code ed))- (= (:type ed) :missing-required-permissions))- (assoc :status-code 403)+ (actions/check-actions-enabled action)+ (try+ (execute-query-action! action request-parameters opts)+ (catch Exception e+ (log/errorf "Error executing action: %s" (ex-message e))+ (if-let [ed (ex-data e)]+ (let [ed (cond-> ed+ (and (nil? (:status-code ed))+ (= (:type ed) :missing-required-permissions))+ (assoc :status-code 403)- (nil? (:message ed))- (assoc :message (ex-message e)))]- (if (= (ex-data e) ed)- (throw e)- (throw (ex-info (ex-message e) ed e))))- {:body {:message (or (ex-message e) (tru "Error executing action."))}- :status 500})))))+ (nil? (:message ed))+ (assoc :message (ex-message e)))]+ (if (= (ex-data e) ed)+ (throw e)+ (throw (ex-info (ex-message e) ed e))))+ {:body {:message (or (ex-message e) (tru "Error executing action."))}+ :status 500}))))(defn- check-no-extra-parameters"Check that the given request parameters do not contain any parameters that are not in the given set of destination parameter ids"@@ -249,10 +229,7 @@(execute-action! action request-parameters nil))([action :- ::actions.schema/actionrequest-parameters :- RequestParameters- {:keys [allow-http-actions?] :or {allow-http-actions? true} :as opts} :- [:maybe ExecuteActionOpts]]- (when (and (= (:type action) :http) (not allow-http-actions?))- (throw (ex-info (tru "HTTP actions cannot be executed from public endpoints.")- {:status-code 403})))+ opts :- [:maybe ExecuteActionOpts]](let [;; if a value is supplied for a hidden parameter, it should raise an errorfield-settings (get-in action [:visualization_settings :fields])hidden-param-ids (->> (vals field-settings)@@ -273,7 +250,7 @@(case (:type action):implicit(execute-implicit-action! action request-parameters opts)- (:query :http)+ :query(execute-custom-action! action request-parameters opts)(throw (ex-info (tru "Unknown action type {0}." (name (:type action :unknown))) action))))))diff --git a/src/metabase/actions/http_action.clj b/src/metabase/actions/http_action.cljdeleted file mode 100644index 941cfc9fdc9..00000000000--- a/src/metabase/actions/http_action.clj+++ /dev/null@@ -1,182 +0,0 @@-(ns metabase.actions.http-action- (:require- [clj-http.client :as http]- [clojure.string :as str]- [metabase.lib.core :as lib]- [metabase.query-processor.error-type :as qp.error-type]- [metabase.util.i18n :refer [tru]]- [metabase.util.json :as json]- [metabase.util.log :as log]- [metabase.util.malli :as mu]- [metabase.util.malli.registry :as mr])- (:import- (com.fasterxml.jackson.databind ObjectMapper)- (net.thisptr.jackson.jq BuiltinFunctionLoader JsonQuery Output Scope Versions)))--(set! *warn-on-reflection* true)--(defonce ^:private root-scope- (delay- (let [scope (Scope/newEmptyScope)]- (.loadFunctions (BuiltinFunctionLoader/getInstance) Versions/JQ_1_6 scope))))--(defonce ^:private object-mapper- (delay (ObjectMapper.)))--;; Largely copied from sql drivers param substitute.-;; May go away if parameters substitution is taken out of query-processing/db dependency-(declare substitute*)--(mr/def ::acc- [:tuple [:maybe :string] [:maybe [:sequential :string]]])--(mu/defn- substitute-param- [param->value :- [:maybe [:map-of :string :metabase.lib.parameters.parse.types/parsed-value]]- [sql missing] :- ::acc- _in-optional? :- :boolean- {:keys [k]} :- :metabase.lib.parameters.parse.types/param]- (if-not (contains? param->value k)- [sql (conj missing k)]- (let [v (get param->value k)]- (cond- (= v lib/parsed-param-no-value-placeholder)- [sql (conj missing k)]-- :else- [(str sql v) missing]))))--(mu/defn- substitute-optional- [param->value :- [:maybe [:map-of :string :metabase.lib.parameters.parse.types/parsed-value]]- [sql missing] :- ::acc- {subclauses :args} :- :metabase.lib.parameters.parse.types/optional]- (let [[opt-sql opt-missing] (substitute* param->value subclauses true)]- (if (seq opt-missing)- [sql missing]- [(str sql opt-sql) missing])))--(defn- substitute*- "Returns a sequence of `[replaced-sql-string jdbc-args missing-parameters]`."- [param->value parsed in-optional?]- (reduce- (fn [[sql missing] x]- (cond- (string? x)- [(str sql x) missing]-- (lib/parsed-param? x)- (substitute-param param->value [sql missing] in-optional? x)-- (lib/parsed-optional-param? x)- (substitute-optional param->value [sql missing] x)))- nil- parsed))--(defn- substitute- "Substitute `Optional` and `Param` objects in a `parsed-template`, a sequence of parsed string fragments and tokens, with- the values from the map `param->value` (using logic from `substitution` to decide what replacement SQL should be- generated).-- (substitute [\"https://example.com/?filter=\" (param \"bird_type\")]- {\"bird_type\" \"Steller's Jay\"})- ;; -> \"https://example.com/?filter=Steller's Jay\""- [parsed-template param->value]- (log/trace "Substituting params in template")- (let [[sql missing] (try- (substitute* param->value parsed-template false)- (catch Throwable e- (throw (ex-info (tru "Unable to substitute parameters: {0}" (ex-message e))- {:type (or (:type (ex-data e)) qp.error-type/qp)- :params param->value- :parsed-query parsed-template}- e))))]- (when (seq missing)- (throw (ex-info (tru "Cannot call the service: missing required parameters: {0}" (str/join ", " (set missing)))- {:type qp.error-type/missing-required-parameter- :missing missing- :status-code 400})))- (str/trim sql)))--(defn- parse-and-substitute [s params->value]- (when s- (-> s- lib/parse-parameters- (substitute params->value))))-;;--(deftype ActionOutput [results]- Output- (emit [_ x]- (vswap! results conj (str x))))--(defn apply-json-query- "Executes a jq query on [[object]]."- [object jq-query]- ;; TODO this is pretty inefficient. We parse with `:as :json`, then re-encode within a response- ;; I couldn't find a way to get JSONNode out of cheshire, so we fall back to jackson.- ;; Should jackson be added explicitly to deps.edn?- (let [json-node (.readTree ^ObjectMapper @object-mapper (json/encode object))- vresults (volatile! [])- output (ActionOutput. vresults)- expr (JsonQuery/compile jq-query Versions/JQ_1_6)- ;; might need to Scope childScope = Scope.newChildScope(rootScope); if root-scope can be modified by expression- _ (.apply expr @root-scope json-node output)- results @vresults]- (if (<= (count results) 1)- (first results)- (throw (ex-info (tru "Too many results returned: {0}" (pr-str results)) {:jq-query jq-query :results results})))))--(defn execute-http-action!- "Calls an http endpoint based on action and params"- [_action _params->value]- (throw (ex-info (tru "HTTP actions are disabled.")- {:type :http- :status-code 400})))--;; the real implementation, kept intact while execute-http-action! above refuses; nothing calls it-;; until HTTP actions are switched back on-#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var :unused-private-var]}-(defn- execute-http-action-impl!- [action params->value]- (try- (let [{:keys [method url body headers]} (:template action)- request {:method (keyword method)- :url (parse-and-substitute url params->value)- :accept :json- :content-type :json- :throw-exceptions false- :headers (merge- ;; TODO maybe we want to default Agent here? Maybe Origin/Referer?- {"X-Metabase-Action" (:name action)}- (-> headers- (parse-and-substitute params->value)- (json/decode)))- :body (parse-and-substitute body params->value)}- response (-> (http/request request)- (select-keys [:body :headers :status])- (update :body json/decode))- error (json/decode (apply-json-query response (or (:error_handle action) ".status >= 400")))]- (log/trace "Response status before handle:" (:status response))- (if error- {:status 400- :headers {"Content-Type" "application/json"}- :body (if (boolean? error)- {:remote-status (:status response)- ;; this is a very lazy approach to get some string identifying the error from the incoming data,- ;; just to pass `dashcard-http-action-execution-test`; ideally the whole logic here should be- ;; updated to pass enough details back to the client- :message (let [body (:body response)]- (or (get body "error")- (get body "error-code")- (get body "message")))}- error)}- (if-some [response (some->> action :response_handle (apply-json-query response))]- {:status 200- :headers {"Content-Type" "application/json"}- :body response}- {:status 204- :body nil})))- (catch Exception e- (throw (ex-info (str "Problem building request: " (ex-message e))- {:template (:template action)- :status-code (:status-code (ex-data e) 500)}- e)))))diff --git a/src/metabase/actions/models.clj b/src/metabase/actions/models.cljindex 1db38af9933..a8d96d44ba7 100644--- a/src/metabase/actions/models.clj+++ b/src/metabase/actions/models.clj@@ -1,15 +1,18 @@(ns metabase.actions.models(:require[medley.core :as m]+ [metabase.actions.actions :as actions][metabase.actions.db :as actions.db][metabase.actions.schema :as actions.schema]+ [metabase.api.common :as api]+ [metabase.collections.models.collection :as collection][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.schema.id :as lib.schema.id][metabase.models.interface :as mi][metabase.models.serialization :as serdes][metabase.parameters.core :as parameters]- [metabase.parameters.schema :as parameters.schema]+ [metabase.permissions.core :as perms][metabase.public-sharing.core :as public-sharing][metabase.queries.models.query :as query][metabase.queries.schema :as queries.schema]@@ -28,16 +31,13 @@(methodical/defmethod t2/table-name :model/Action [_model] :action)(methodical/defmethod t2/table-name :model/QueryAction [_model] :query_action)-(methodical/defmethod t2/table-name :model/HTTPAction [_model] :http_action)(methodical/defmethod t2/table-name :model/ImplicitAction [_model] :implicit_action)-(def ^:private action-sub-models [:model/QueryAction :model/HTTPAction :model/ImplicitAction])+(def ^:private action-sub-models [:model/QueryAction :model/ImplicitAction])(doto :model/Action(derive :metabase/model)- ;;; You can read/write an Action if you can read/write its model (Card)- (derive ::mi/read-policy.full-perms-for-perms-set)- (derive ::mi/write-policy.full-perms-for-perms-set)+ (derive :perms/use-parent-collection-perms)(derive :hook/entity-id)(derive :hook/timestamped?))@@ -47,7 +47,6 @@(derive :model/QueryAction :hook/search-index)(methodical/defmethod t2/primary-keys :model/QueryAction [_model] [:action_id])-(methodical/defmethod t2/primary-keys :model/HTTPAction [_model] [:action_id])(methodical/defmethod t2/primary-keys :model/ImplicitAction [_model] [:action_id])(def ^:private transform-action-visualization-settings@@ -77,91 +76,149 @@(t2/deftransforms :model/ImplicitAction{:kind mi/transform-keyword})-(def ^:private transform-json-with-nested-parameters- {:in (comp mi/json-in- (fn [template]- (u/update-if-exists template :parameters #(lib/normalize ::parameters.schema/parameters %))))- :out (comp (fn [template]- (u/update-if-exists template :parameters (mi/catch-normalization-exceptions #(lib/normalize ::parameters.schema/parameters %))))- mi/json-out-with-keywordization)})--(t2/deftransforms :model/HTTPAction- {:template transform-json-with-nested-parameters})-(methodical/defmethod t2/batched-hydrate [:model/Action :model][_model k actions](mi/instances-with-hydrated-dataactions k- #(actions.db/cards-by-id (map :model_id actions))+ #(when-let [model-ids (seq (keep :model_id actions))]+ (actions.db/cards-by-id model-ids)):model_id))-(defn- check-model-is-not-a-saved-question+(defn- implicit?+ "Whether `action` is an implicit action."+ [action]+ (= :implicit (keyword (:type action))))++(defn- check-implicit-action-model+ "Throws a 400 unless the Card with `model-id` is a model."[model-id](when-not (= (actions.db/card-type model-id) :model)(throw (ex-info (tru "Actions must be made with models, not cards."){:status-code 400}))))+(defn check-implicit-actions-supported+ "Throws a 400 when `action` is implicit and its model's query does not support implicit actions."+ [{model-id :model_id, :as action}]+ (when (and (implicit? action)+ (not (query/supports-implicit-actions? (some-> model-id actions.db/card-query))))+ (throw (ex-info (tru "Implicit actions are not supported for models with clauses.")+ {:status-code 400}))))++(defn- check-collection-content+ "Throws unless an Action may go in the Collection with `collection-id`."+ [collection-id]+ (collection/check-collection-namespace :model/Action collection-id)+ (collection/check-allowed-content :action collection-id))++(defn- set-model-collection+ "`action` with the `:collection_id` of its model Card."+ [{model-id :model_id, :as action}]+ (assoc action :collection_id (actions.db/card-collection-id model-id)))+(t2/define-before-insert :model/Action[{model-id :model_id, :as action}]- (u/prog1 (public-sharing/add-public-uuid-prefix action)- (check-model-is-not-a-saved-question model-id)))+ (u/prog1 (cond-> (public-sharing/add-public-uuid-prefix action)+ model-id set-model-collection)+ (when (implicit? action)+ (check-implicit-action-model model-id))+ (check-collection-content (:collection_id <>))))(t2/define-before-update :model/Action- [{archived? :archived, id :id, model-id :model_id, :as changes}]- (u/prog1 (public-sharing/add-public-uuid-prefix-if-changed changes)- (if archived?- (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 (actions.db/card (:model_id instance)) read-or-write))+ [{model-id :model_id, :as action}]+ (let [changed? (fn [k] (contains? (t2/changes action) k))]+ (u/prog1 (cond-> (public-sharing/add-public-uuid-prefix-if-changed action)+ (and model-id (changed? :model_id))+ set-model-collection)+ (when (and (implicit? action) (or (changed? :type) (changed? :model_id)))+ (check-implicit-action-model model-id)+ (check-implicit-actions-supported action))+ (when (contains? (t2/changes <>) :collection_id)+ (check-collection-content (:collection_id <>))))))++(defn- set-query-database+ "`query-action` with the `:database_id` of its query, when it has one."+ [{query :dataset_query, :as query-action}]+ (if-let [database-id (when (map? query) (:database query))]+ (assoc query-action :database_id database-id)+ query-action))++(t2/define-before-insert :model/QueryAction+ [query-action]+ (set-query-database query-action))++(t2/define-before-update :model/QueryAction+ [query-action]+ (set-query-database query-action))++(defn- action-database-ids+ "The ids of the Databases `action` runs against: its query's, or its model's for an implicit action."+ [{model-id :model_id, query :dataset_query, :keys [database_id], :as action}]+ (case (keyword (:type action))+ :implicit [(:database_id (actions.db/card-scope-columns model-id))]+ :query [(or (:database query) database_id)]+ []))++(defn check-action-databases-enabled+ "Throws a 400 unless actions are enabled on every Database `action` runs against."+ [action]+ (doseq [database-id (action-database-ids action)+ :when database-id]+ (actions/check-actions-enabled-for-database (actions.db/database database-id))))++(defn- native-query-permitted?+ "Whether the current user may author the query of `action`: a native one needs native query permission."+ [{query :dataset_query, :keys [database_id]}]+ (or (not (and (seq query) (lib/native? query)))+ (= :query-builder-and-native+ (perms/full-database-permission-for-user api/*current-user-id* :perms/create-queries+ (or (:database query) database_id)))))++(defn- effective-collection-id+ "The id of the Collection `action` goes in, its model's when it has one; throws a 404 when either does not exist."+ [{model-id :model_id, collection-id :collection_id}]+ (if model-id+ (:collection_id (api/check-404 (actions.db/card-scope-columns model-id)))+ (u/prog1 collection-id+ (when collection-id+ (api/check-404 (actions.db/collection-exists? collection-id))))))++(defn- collection-writable?+ "Whether the current user can write the Collection `action` goes in."+ [action]+ ((get-method mi/can-create? :perms/use-parent-collection-perms)+ :model/Action+ (assoc action :collection_id (effective-collection-id action))))++(defmethod mi/can-create? :model/Action+ [_model action]+ (and (collection-writable? action)+ (native-query-permitted? action)))++(defmethod mi/can-update? :model/Action+ [action changes]+ (and (mi/can-write? action)+ (collection-writable? (merge action changes))+ (native-query-permitted? changes)))(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])+ [:archived :archived_directly :collection_id :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]);;; ------------------------------------------------ CRUD fns ------------------------------------------------------(defn- query->database-id- [query]- (when (map? query)- (:database query)))--(defn- derive-query-action-database-id- "For `:query` actions, `:database_id` is wholly derived from the database the query executes against: it is- redundant metadata that must track `(:database dataset_query)`, exactly as a Card's `database_id` tracks its query- ([[metabase.queries.models.card/populate-query-fields]]).-- On update the query may not be part of the change, so `fallback-query` (the existing action's query) supplies the- database so that a `:database_id`-only change can't repoint it. A no-op for non-query actions and when no query is- available."- ([action-row]- (derive-query-action-database-id action-row nil))- ([{action-type :type, query :dataset_query, :as action-row} fallback-query]- (if-let [query-db-id (and (= action-type :query)- (or (query->database-id query)- (query->database-id fallback-query)))]- (assoc action-row :database_id query-db-id)- action-row)))-;;; TODO (Cam 10/2/25) -- this should just be the default Toucan 2 insert behavior for an action(mu/defn- insert*! :- ::actions.schema/id[action-data :- ::actions.schema/action.for-insert]- (let [action-data (derive-query-action-database-id action-data)]- (t2/with-transaction [_conn]- (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)))]- (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)))))+ (t2/with-transaction [_conn]+ (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)))]+ (case (:type action)+ :query (actions.db/insert-query-action! row)+ :implicit (actions.db/insert-implicit-action! row))+ (:id action))))(mu/defn insert! :- ::actions.schema/id"Inserts an Action and related type table. Returns the action id."@@ -171,12 +228,17 @@(mu/defn- update*![{:keys [id] :as updates} :- ::actions.schema/action.for-updateexisting-action :- ::actions.schema/action]- (let [updates (derive-query-action-database-id- (assoc updates :type (or (:type updates) (:type existing-action)))- (:dataset_query existing-action))]+ (let [updates (cond-> (assoc updates :type (or (:type updates) (:type existing-action)))+ (get updates :model_id (:model_id existing-action)) (dissoc :collection_id))](t2/with-transaction [_conn](when-let [action-row (not-empty (select-keys updates action-columns))](actions.db/update-action! id action-row))+ (when (and (:archived updates) (not (:archived existing-action)))+ (actions.db/delete-dashcards-for-action! id))+ (when-let [collection-id (and (contains? updates :collection_id)+ (not= (:collection_id updates) (:collection_id existing-action))+ (:collection_id updates))]+ (api/check-400 (actions.db/unarchived-collection-exists? collection-id)))(when-let [type-row (not-empty (cond-> (apply dissoc updates :id action-columns)(= (or (:type updates) (:type existing-action)):implicit)@@ -186,16 +248,14 @@(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))))))))+ :implicit (actions.db/update-implicit-action! id type-row)))))+ (collection/check-for-remote-sync-update (t2/instance :model/Action existing-action)))))(mu/defn update!"Updates an Action and the related type table.@@ -212,19 +272,6 @@(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 (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))]- (-> action- (merge- {:disabled false}- (select-keys http-action [:template :response_handle :error_handle])- (select-keys (:template http-action) [:parameters :parameter_mappings])))))- actions))))-(defn- normalize-implicit-actions [actions](when (seq actions)(let [implicit-actions (actions.db/implicit-actions (map :id actions))@@ -242,25 +289,21 @@(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]+ {:keys [id entity_id 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))))+ (let [{:keys [query implicit]} (group-by :type actions)+ query-actions (normalize-query-actions query)+ implicit-actions (normalize-implicit-actions implicit)]+ (sort-by :updated_at (concat query-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@@ -405,7 +448,7 @@(seq implicit-params)(-> (assoc :parameters implicit-params)(update-in [:visualization_settings :fields] enrich-viz-settings-fields implicit-params field-id->viz-field))))- (:query :http)+ :queryaction))(defn- enrich-actions-with-implicit-params@@ -454,15 +497,6 @@model-ids :- [:sequential ms/PositiveInt]](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 :- [:maybe [:sequential ::queries.schema/card]]- model-ids :- [:set ms/PositiveInt]]- (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 interpreted by [[select-actions-matching-options]]."@@ -484,7 +518,7 @@(map (juxt :id get-database-enable-actions))(actions.db/action-database-settings action-ids))](map (fn [action]- (assoc action :database_enabled_actions (get id->database-enable-actions (:id action))))+ (assoc action :database_enabled_actions (get id->database-enable-actions (:id action) false)))actions)))(methodical/defmethod t2.hydrate/batched-hydrate [:model/DashboardCard :dashcard/action]@@ -518,40 +552,41 @@:database_id (serdes/fk :model/Database):dataset_query {:export serdes/export-mbql :import serdes/import-mbql}}})-(defmethod serdes/generate-path "HTTPAction" [_ _] nil)-(defmethod serdes/make-spec "HTTPAction" [_model-name _opts]- {:copy [:error_handle :response_handle :template]- :transform {:action_id (serdes/parent-ref)}})-(defmethod serdes/generate-path "ImplicitAction" [_ _] nil)(defmethod serdes/make-spec "ImplicitAction" [_model-name _opts]{:copy [:kind]:transform {:action_id (serdes/parent-ref)}})(defmethod serdes/make-spec "Action" [_model-name opts]- {:copy [:archived :description :entity_id :name :public_uuid]+ {:copy [:archived :archived_directly :description :entity_id :name :public_uuid]:skip [;; always re-derived from public_uuid on import:public_uuid_prefix]:transform {:created_at (serdes/date):type (serdes/kw):creator_id (serdes/fk :model/User):made_public_by_id (serdes/fk :model/User)+ :collection_id (serdes/fk :model/Collection):model_id (serdes/fk :model/Card):query (serdes/nested :model/QueryAction :action_id (merge {:sort-by (juxt :name :created_at)} opts))- :http (serdes/nested :model/HTTPAction :action_id (merge {:sort-by (juxt :name :created_at)} opts)):implicit (serdes/nested :model/ImplicitAction :action_id (merge {:sort-by (juxt :name :created_at)} opts)):parameters {:export serdes/export-parameters :import serdes/import-parameters}:parameter_mappings {:export serdes/export-parameter-mappings:import serdes/import-parameter-mappings}:visualization_settings {:export serdes/export-visualization-settings:import serdes/import-visualization-settings}}- :defaults {:archived false}})+ :defaults {:archived false, :archived_directly false}})++(defmethod serdes/load-one! "Action" [ingested maybe-local]+ (when-not (= "http" (some-> (:type ingested) name))+ (serdes/default-load-one! ingested maybe-local)))(defmethod serdes/deserialization-dependencies "Action" [action](set(concat- ;; other stuff is implicitly referenced through a Card- [[{:model "Card" :id (:model_id action)}]]+ (when-let [collection-id (:collection_id action)]+ [[{:model "Collection" :id collection-id}]])+ (when-let [model-id (:model_id action)]+ [[{:model "Card" :id model-id}]]);; this method is called on ingested data before transformation, and so here it always will be a string(when (= (:type action) "query")(let [{:keys [database_id dataset_query]} (first (:query action))]@@ -559,11 +594,12 @@[[{:model "Database" :id database_id}]](serdes/mbql-deps false dataset_query)))))))-(defmethod serdes/serialization-dependencies "Action" [_model-name {:keys [id model_id type]}]+(defmethod serdes/serialization-dependencies "Action" [_model-name {:keys [id collection_id model_id type]}];; Serialization runs on the raw entity, whose query lives in the `query_action` child table (`:type` is a keyword;; here, not a string), so the query is fetched rather than read from a nested `:query` key.(set(concat+ (when collection_id [[{:model "Collection" :id collection_id}]])(when model_id [[{:model "Card" :id model_id}]])(when (= type :query)(when-let [{:keys [database_id dataset_query]} (actions.db/query-action id)]@@ -571,15 +607,16 @@(when database_id [[{:model "Database" :id database_id}]])(serdes/mbql-deps true dataset_query)))))))-(defmethod serdes/storage-path "Action" [action _ctx]- [{:label "actions"} {:label (:name action) :key (:entity_id action)}])+(defmethod serdes/descendants "Action" [_model-name id _opts]+ (when-let [model-id (actions.db/action-model-id id)]+ {["Card" model-id] {"Action" id}}));;;; ------------------------------------------------- Search ----------------------------------------------------------(search/define-spec "action"{:model :model/Action:attrs {:archived true- :collection-id :model.collection_id+ :collection-id true:creator-id true:database-id :query_action.database_id:native-query :query_action.dataset_query@@ -593,4 +630,4 @@:where [:= :collection.namespace nil]:joins {:model [:model/Card [:= :model.id :this.model_id]]:query_action [:model/QueryAction [:= :query_action.action_id :this.id]]- :collection [:model/Collection [:= :collection.id :model.collection_id]]}})+ :collection [:model/Collection [:= :collection.id :this.collection_id]]}})diff --git a/src/metabase/actions/schema.clj b/src/metabase/actions/schema.cljindex ecbcccefcf3..fdeaaf86950 100644--- a/src/metabase/actions/schema.clj+++ b/src/metabase/actions/schema.clj@@ -1,6 +1,5 @@(ns metabase.actions.schema(:require- [metabase.actions.http-action :as http-action][metabase.actions.types :as actions.types][metabase.lib-be.schema :as lib-be.schema][metabase.lib.schema.actions :as lib.schema.actions]@@ -85,36 +84,9 @@[:enum{:decode/normalize keyword:description (deferred-tru "Unsupported action type")}- :http:implicit:query])-(mr/def ::http-action.json-query- [:and- {:description (deferred-tru "must be a valid json-query, something like ''.item.title''")}- string?- [:fn- {:error/fn (fn [_ _]- (deferred-tru "must be a valid json-query, something like ''.item.title''"))}- #(http-action/apply-json-query {} %)]])--(mr/def ::http-action.template- [:map {:closed true}- [:method [:enum "GET" "POST" "PUT" "DELETE" "PATCH"]]- [:url [string? {:min 1}]]- [:body {:optional true} [:maybe string?]]- [:headers {:optional true} [:maybe string?]]- [:parameters {:optional true} [:maybe ::parameters.schema/parameters]]])--(def ^:private http-action-entries- [[:template {:optional true} [:maybe ::http-action.template]]- [:response_handle {:optional true} [:maybe ::http-action.json-query]]- [:error_handle {:optional true} [:maybe ::http-action.json-query]]- [:disabled {:optional true} :boolean]])--(mr/def ::http-action- (into [:map {:closed true}] http-action-entries))-(mr/def ::implicit-action.kind[:enum{:decode/normalize keyword@@ -171,8 +143,10 @@:insert nil)[[:name required-for-insert :string][:type required-for-insert ::type]- [:model_id required-for-insert ::lib.schema.id/card]+ [:model_id {:optional true} [:maybe ::lib.schema.id/card]]+ [:collection_id {:optional true} [:maybe ::lib.schema.id/collection]][:archived {:optional true} :boolean]+ [:archived_directly {:optional true} :boolean][:description {:optional true} [:maybe :string]][:parameters {:optional true} [:maybe [:sequential ::action.parameter]]][:database_id {:optional true} [:maybe ::lib.schema.id/database]]@@ -189,12 +163,11 @@[:merge(into [:map {:closed true}] common)[:multi {:decode/normalize lib.schema.common/normalize-map-no-kebab-case- :dispatch (comp keyword :type)}- [:http (into [:map {:closed true}] http-action-entries)]- [:implicit (into [:map {:closed true}] implicit-action-entries)]+ :dispatch (comp #{:implicit :query} keyword :type)}+ [:implicit (into [:map {:closed true} [:model_id required-for-insert ::lib.schema.id/card]] implicit-action-entries)][:query (into [:map {:closed true}] query-action-entries)];; a partial update need not repeat `:type`; accept every type's keys rather than dropping them- [nil (into [:map {:closed true}] cat [http-action-entries implicit-action-entries query-action-entries])]]]))+ [nil (into [:map {:closed true}] cat [implicit-action-entries query-action-entries])]]]))(mr/def ::action"An Action as it should appear when we `SELECT` it from the app DB."@@ -208,20 +181,6 @@"Schema for updating an Action (REST API or internally)."(action-schema :update))-(mr/def ::httpaction- "A HTTPAction as selected from the app DB: every column of `:http_action`."- [:merge- ::httpaction.update- [:map {:closed true}]])--(mr/def ::httpaction.update- "What an update (or insert) of a HTTPAction accepts: every column of `:http_action` except `id`, all optional."- [:map {:closed true}- [:action_id {:optional true} [:maybe ::lib.schema.id/action]]- [:template {:optional true} [:maybe ::http-action.template]]- [:response_handle {:optional true} [:maybe :string]]- [:error_handle {:optional true} [:maybe :string]]])-(mr/def ::implicit-action.row"A ImplicitAction as selected from the app DB: every column of `:implicit_action`."[:map {:closed true}diff --git a/src/metabase/actions_rest/api.clj b/src/metabase/actions_rest/api.cljindex 0914e558ed9..1aeb0454706 100644--- a/src/metabase/actions_rest/api.clj+++ b/src/metabase/actions_rest/api.clj@@ -10,11 +10,9 @@[metabase.api.macros :as api.macros][metabase.eid-translation.core :as eid-translation][metabase.events.core :as events]- [metabase.lib.core :as lib][metabase.lib.schema.id :as lib.schema.id][metabase.permissions.core :as perms][metabase.public-sharing.validation :as public-sharing.validation]- [metabase.queries.core :as queries][metabase.util :as u][metabase.util.i18n :refer [tru]][metabase.util.malli.schema :as ms]@@ -22,32 +20,19 @@(set! *warn-on-reflection* true)-(defn- check-native-query-perms!- "Creating or updating a native query action requires ad-hoc native query permission on the target database."- [database-id dataset-query]- (when (and (seq dataset-query) (lib/native? dataset-query))- (when-let [db-id (or database-id (:database dataset-query))]- (api/check-403- (= :query-builder-and-native- (perms/full-database-permission-for-user api/*current-user-id* :perms/create-queries db-id))))))-(api.macros/defendpoint :get "/" :- [:sequential ::actions.schema/action]- "Returns actions that can be used for QueryActions. By default lists all viewable actions. Pass optional- `?model-id=<model-id>` to limit to actions on a particular model."+ "Returns the unarchived actions in collections the current user can read. Pass optional `?model-id=<model-id>` to+ limit to the actions of a particular model."{:scope api-scope/data-app}[_route-params{:keys [model-id]} :- [:map {:closed true}[:model-id {:optional true} [:maybe ::lib.schema.id/card]]]]- (letfn [(actions-for [models]- (if (seq models)- (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)]- ;; action permission keyed off of model permission- (actions-rest.db/unarchived-models-visible-to-user))]- (actions-for models))))+ (let [actions (if model-id+ (let [model (api/read-check :model/Card model-id)]+ (actions/select-actions-for-models [model] [model-id]))+ (when-let [action-ids (seq (actions-rest.db/unarchived-action-ids-visible-to-user))]+ (actions/select-actions-for-ids nil (vec action-ids))))]+ (t2/hydrate (vec actions) :creator)))(api.macros/defendpoint :get "/public" :- [:sequential ::actions.schema/action]"Fetch a list of Actions with public UUIDs. These actions are publicly-accessible *if* public sharing is enabled."@@ -86,38 +71,24 @@"Create a new action."[_route-params_query-params- {:keys [model_id parameters database_id]+ {:keys [parameters database_id]action-type :type:as action} :- ::actions.schema/action.for-insert]- (when (= action-type :http)- (throw (ex-info (tru "HTTP actions are not supported.")- {:type :http- :status-code 400})))(when (and (nil? database_id)(= action-type :query))(throw (ex-info (tru "Must provide a database_id for query actions"){:type action-type:status-code 400})))- (check-native-query-perms! database_id (:dataset_query action))- (let [model (api/write-check :model/Card model_id)]- (when (and (= action-type :implicit)- (not (queries/model-supports-implicit-actions? model)))- (throw (ex-info (tru "Implicit actions are not supported for models with clauses.")- {:status-code 400})))- (doseq [db-id (cond-> [(:database_id model)] database_id (conj database_id))]- (actions/check-actions-enabled-for-database!- (actions-rest.db/database db-id))))+ (api/create-check :model/Action action)+ (actions/check-implicit-actions-supported action)+ (actions/check-action-databases-enabled action)(let [action-id (actions/insert! (assoc action :creator_id api/*current-user-id*))](analytics/track-event! :snowplow/action{:event :action-created:type action-type:action_id action-id:num_parameters (count parameters)})- (u/prog1 (if action-id- (actions/select-action :id action-id)- ;; t2/insert! does not return a value when used with h2- ;; so we return the most recently updated http action.- (last (actions/select-actions nil :type action-type)))+ (u/prog1 (actions/select-action :id action-id)(events/publish-event! :event/action-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@@ -130,21 +101,10 @@[:id ::actions.schema/id]]_query-paramsaction :- ::actions.schema/action.for-update]- (when (= (:type action) :http)- (throw (ex-info (tru "HTTP actions are not supported.")- {:type :http- :status-code 400})))- (actions/check-actions-enabled! id)- (let [existing-action (api/write-check :model/Action id)]- (when (= (:type existing-action) :http)- (throw (ex-info (tru "HTTP actions are not supported.")- {:type :http- :status-code 400})))- (when-let [model-id (:model_id action)]- (when (not= model-id (:model_id existing-action))- (api/write-check :model/Card model-id)))- (when-let [dataset-query (:dataset_query action)]- (check-native-query-perms! (:database_id action) dataset-query))+ (let [existing-action (api/write-check :model/Action id)+ action (api/updates-with-archived-directly existing-action action)]+ (api/update-check existing-action action)+ (actions/check-action-databases-enabled (merge (actions/select-action :id id) action))(actions/update! (assoc action :id id) existing-action))(let [{:keys [parameters type] :as action} (actions/select-action :id id)](events/publish-event! :event/action-update {:object action :user-id api/*current-user-id*})@@ -171,7 +131,7 @@(api/check-superuser)(public-sharing.validation/check-public-sharing-enabled)(let [action (api/read-check :model/Action id :archived false)]- (actions/check-actions-enabled! action)+ (actions/check-actions-enabled action){:uuid (or (:public_uuid action)(u/prog1 (str (random-uuid))(actions-rest.db/set-action-public-uuid! id <> api/*current-user-id*)))}))@@ -192,7 +152,7 @@(perms/check-has-application-permission :setting)(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)+ (actions/check-actions-enabled id)(actions-rest.db/set-action-public-uuid! id nil nil){:status 204, :body nil})@@ -206,7 +166,7 @@_query-params{:keys [parameters]} :- [:map {:closed true}[:parameters ::actions.schema/prefetch-parameter-values]]]- (actions/check-actions-enabled! action-id)+ (actions/check-actions-enabled action-id)(-> (actions/select-action :id action-id :archived false)api/read-check(actions/fetch-values parameters)))@@ -251,10 +211,6 @@[:parameters {:optional true} [:maybe ::actions.schema/execute-parameter-values]]]]](let [resolved-id (eid-translation/->id-or-404 :action id){:keys [type] :as action} (api/read-check (actions/select-action :id resolved-id :archived false))]- (when (= type :http)- (throw (ex-info (tru "HTTP actions are not supported.")- {:type :http- :status-code 400})))(analytics/track-event! :snowplow/action{:event :action-executed:source :model_detaildiff --git a/src/metabase/actions_rest/db.clj b/src/metabase/actions_rest/db.cljindex c2726b03b72..6afda99af11 100644--- a/src/metabase/actions_rest/db.clj+++ b/src/metabase/actions_rest/db.clj@@ -7,13 +7,12 @@[metabase.util.malli :as mu][toucan2.core :as t2]))-(mu/defn unarchived-models-visible-to-user- "The unarchived model Cards in Collections the current user can read."+(mu/defn unarchived-action-ids-visible-to-user+ "The ids of the unarchived Actions in Collections the current user can read."[]- (t2/select :model/Card {:where [:and- [:= :type "model"]- [:= :archived false]- (collection/visible-collection-filter-clause)]}))+ (t2/select-pks-vec :model/Action {:where [:and+ [:= :archived false]+ (collection/visible-collection-filter-clause)]}))(mu/defn public-actions"The name, id, public uuid, and model id of the unarchived Actions that are publicly shared."diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex 5b40a247bbd..6d01b759364 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -101,7 +101,6 @@:model/ParameterCard:model/Action:model/ImplicitAction- :model/HTTPAction:model/QueryAction:model/DashboardTab:model/ModelIndex@@ -409,7 +408,6 @@#{:model/Setting:model/Session:model/ImplicitAction- :model/HTTPAction:model/FieldUserSettings:model/TableUserSettings:model/QueryActiondiff --git a/src/metabase/collections/db.clj b/src/metabase/collections/db.cljindex 187166f3cf9..221c000d285 100644--- a/src/metabase/collections/db.clj+++ b/src/metabase/collections/db.clj@@ -398,6 +398,32 @@archived? :- :boolean](t2/update! :model/Timeline {:collection_id [:in collection-ids]} {:archived archived?}))+(mu/defn set-action-archived-in-collections!+ "Archive the unarchived Actions in the Collections with `collection-ids` along with them, or unarchive the ones+ archived along with them whose model, if any, is not archived, returning the number updated."+ [collection-ids :- [:sequential ::lib.schema.id/collection]+ archived? :- :boolean]+ (if archived?+ (t2/update! :model/Action {:collection_id [:in collection-ids], :archived false}+ {:archived true, :archived_directly false})+ (if-let [action-ids (not-empty (into #{} (map :id)+ (t2/query {:select [:action.id]+ :from [[(t2/table-name :model/Action) :action]]+ :left-join [[(t2/table-name :model/Card) :model]+ [:= :model.id :action.model_id]]+ :where [:and+ [:in :action.collection_id collection-ids]+ [:= :action.archived true]+ [:= :action.archived_directly false]+ [:or [:= :action.model_id nil] [:= :model.archived false]]]})))]+ (t2/update! :model/Action :id [:in action-ids] {:archived false})+ 0)))++(mu/defn delete-actions-in-collections!+ "Delete the Actions in the Collections with `collection-ids`, returning the number deleted."+ [collection-ids :- [:sequential ::lib.schema.id/collection]]+ (t2/delete! :model/Action :collection_id [:in collection-ids]))+(mu/defn set-card-archived-in-collections-not-directly!"Set `archived?` on the Cards in the Collections with `collection-ids` that were not archived directly, returningthe number updated."@@ -489,6 +515,13 @@[:= :exploration_id nil](when skip-archived? [:not :archived])]}))+(mu/defn action-ids-in-collection+ "The IDs of the Actions in the Collection with `collection-id`, excluding archived ones when `skip-archived?`."+ [collection-id :- [:maybe ::lib.schema.id/collection]+ skip-archived? :- [:maybe :boolean]]+ (t2/select-pks-set :model/Action+ {:where [:and [:= :collection_id collection-id] (when skip-archived? [:not :archived])]}))+(mu/defn timeline-ids-in-collection"The IDs of the Timelines in the ::collections.schema/collection with `collection-id`, excluding archived ones when `skip-archived?`."[collection-id :- [:maybe ::lib.schema.id/collection]diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex 489fef27e0b..484c09d9bba 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -53,7 +53,7 @@(defn- collectable-models[](set/union (archived-directly-models)- #{:model/Pulse :model/NativeQuerySnippet :model/Timeline}))+ #{:model/Action :model/Pulse :model/NativeQuerySnippet :model/Timeline}))(def ^:private ^:const collection-slug-max-length"Maximum number of characters allowed in a Collection `slug`."@@ -1693,6 +1693,7 @@(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-action-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)@@ -1760,6 +1761,7 @@(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)+ (collections.db/set-action-archived-in-collections! affected-collection-ids false)(when (:is_remote_synced collection)(check-non-remote-synced-dependencies collection)))))@@ -2071,7 +2073,8 @@(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))+ (collections.db/delete-timelines-in-collections! affected-collection-ids)+ (collections.db/delete-actions-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)@@ -2158,13 +2161,15 @@{["Document" doc-id] {"Collection" id}})))timelines (into {} (for [timeline-id (collections.db/timeline-ids-in-collection id skip-archived)]{["Timeline" timeline-id] {"Collection" id}}))+ actions (into {} (for [action-id (collections.db/action-ids-in-collection id skip-archived)]+ {["Action" action-id] {"Collection" id}}))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 (collections.db/transform-ids-in-collection id)]{["Transform" transform-id] {"Collection" id}})))]- (merge child-colls dashboards cards documents timelines tables transforms)))+ (merge child-colls dashboards cards documents timelines actions tables transforms)))(defmethod serdes/storage-path "Collection" [coll {:keys [collections]}](let [path (get collections (:entity_id coll))diff --git a/src/metabase/dashboards/db.clj b/src/metabase/dashboards/db.cljindex 3a2c3e7bec3..01bca49d59c 100644--- a/src/metabase/dashboards/db.clj+++ b/src/metabase/dashboards/db.clj@@ -152,6 +152,11 @@[:not= :dashboard_id nil][:in :id card-ids]]}))+(mu/defn action-entity-ids-in+ "The entity ids among `entity-ids` that name an existing Action."+ [entity-ids :- [:set :string]]+ (t2/select-fn-set :entity_id [:model/Action :entity_id] :entity_id [:in entity-ids]))+(mu/defn dashcard-serdes-columns"The id, Card, Action, parameter mappings, and visualization settings of the DashboardCards of the Dashboard with`dashboard-id`."diff --git a/src/metabase/dashboards/models/dashboard.clj b/src/metabase/dashboards/models/dashboard.cljindex 2840632f71b..b9644c02588 100644--- a/src/metabase/dashboards/models/dashboard.clj+++ b/src/metabase/dashboards/models/dashboard.clj@@ -447,6 +447,17 @@(set/union (when collection_id #{[{:model "Collection" :id collection_id}]}))(set/union (serdes/parameters-deps allow-int-ids? parameters))))+(defn- without-unloaded-action-dashcards+ "`ingested` without the dashcards whose action has no local row."+ [{:keys [dashcards] :as ingested}]+ (if-let [action-eids (not-empty (into #{} (keep :action_id) dashcards))]+ (let [loaded (dashboards.db/action-entity-ids-in action-eids)]+ (assoc ingested :dashcards (filterv #(or (nil? (:action_id %)) (contains? loaded (:action_id %))) dashcards)))+ ingested))++(defmethod serdes/load-one! "Dashboard" [ingested maybe-local]+ (serdes/default-load-one! (without-unloaded-action-dashcards ingested) maybe-local))+(defmethod serdes/deserialization-dependencies "Dashboard" [dashboard](dashboard-deps false dashboard))diff --git a/src/metabase/models/db.clj b/src/metabase/models/db.cljindex 170371c63b1..2f7e677bd4f 100644--- a/src/metabase/models/db.clj+++ b/src/metabase/models/db.clj@@ -70,7 +70,6 @@:model/FieldUserSettings :metabase.warehouse-schema.schema/field-user-settings.update:model/FieldValues :metabase.warehouse-schema.schema/field-values.update:model/Glossary :metabase.glossary.schema/glossary.update- :model/HTTPAction :metabase.actions.schema/httpaction.update:model/ImplicitAction :metabase.actions.schema/implicit-action.update:model/Measure :metabase.measures.schema/measure.update:model/Metabot :metabase.metabot.schema/metabot.updatediff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 412bb426a8f..55c0c20af08 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -64,7 +64,6 @@:model/FieldValues metabase.warehouse-schema.models.field-values:model/Glossary metabase.glossary.models.glossary:model/Sandbox metabase-enterprise.sandbox.models.sandbox- :model/HTTPAction metabase.actions.models:model/ImplicitAction metabase.actions.models:model/LoginHistory metabase.login-history.models.login-history:model/McpFeedback metabase.mcp.models.mcp-feedbackdiff --git a/src/metabase/public_sharing_rest/api.clj b/src/metabase/public_sharing_rest/api.cljindex a926f84c77c..f8c8ac062fa 100644--- a/src/metabase/public_sharing_rest/api.clj+++ b/src/metabase/public_sharing_rest/api.clj@@ -506,8 +506,7 @@(actions/execute-dashcard! dashboard-id dashcard-id (update-keys parameters name);; `as-admin` grants perms but leaves the user nil, so the audit row has no;; executor; the context is what says the run came from a public link- {:allow-http-actions? false- :context :public-action-execute})))))))+ {:context :public-action-execute})))))))(defn- iframe"Return an `<iframe>` HTML fragment to embed a public page."@@ -553,7 +552,7 @@[:uuid ms/UUIDString]]](public-sharing.validation/check-public-sharing-enabled)(let [action (api/check-404 (actions/select-action :id (public-sharing/public-uuid->id :model/Action uuid)))]- (actions/check-actions-enabled! action)+ (actions/check-actions-enabled action)(public-action action)));;; +----------------------------------------------------------------------------------------------------------------+@@ -743,7 +742,7 @@;; you're by definition allowed to run it without a perms check anyway(request/as-admin(let [action (api/check-404 (actions/select-action :id (public-sharing/public-uuid->id :model/Action uuid)))]- (actions/check-actions-enabled! action)+ (actions/check-actions-enabled action)(analytics/track-event! :snowplow/action{:event :action-executed:source :public_form@@ -752,8 +751,7 @@;; Undo middleware string->keyword coercion(actions/execute-action! action (update-keys parameters name);; see the note on the public dashcard endpoint above- {:allow-http-actions? false- :context :public-action-execute})))))))+ {:context :public-action-execute})))))));;; ----------------------------------------------------- Map Tiles --------------------------------------------------diff --git a/src/metabase/queries/core.clj b/src/metabase/queries/core.cljindex 2d97f74d73b..a8197ed3221 100644--- a/src/metabase/queries/core.clj+++ b/src/metabase/queries/core.clj@@ -33,7 +33,8 @@card-param-remapped-value][metabase.queries.dbcard-query-info- cards-queries-info]+ cards-queries-info+ move-actions-of-models!][metabase.queries.models.cardcreate-card!][metabase.queries.card-write-checks@@ -51,7 +52,6 @@[metabase.queries.models.cardfully-parameterized?maybe-unverify!- model-supports-implicit-actions?model?sole-dashboard-idstarting-card-schema-versiondiff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.cljindex 5cad5184d2a..53bf1d36909 100644--- a/src/metabase/queries/db.clj+++ b/src/metabase/queries/db.clj@@ -354,13 +354,21 @@:join [:implicit_action [:= :action.id :implicit_action.action_id]]:where [:= :action.model_id model-id]}))-(mu/defn action-ids-for-model- "The IDs of the Actions of the model Card with `model-id`, leaving out archived Actions when `skip-archived`."- [model-id :- ms/PositiveInt- skip-archived :- [:maybe :boolean]]- (if skip-archived- (t2/select-pks-set :model/Action :model_id model-id :archived false)- (t2/select-pks-set :model/Action :model_id model-id)))+(mu/defn move-actions-of-models!+ "Move the Actions of the Cards with `model-ids` to the Collection with `collection-id`, returning the number+ updated."+ [model-ids :- [:set ::lib.schema.id/card]+ collection-id :- [:maybe ::lib.schema.id/collection]]+ (t2/update! :model/Action :model_id [:in model-ids] {:collection_id collection-id}))++(mu/defn set-actions-of-model-archived!+ "Archive the unarchived Actions of the Card with `model-id` along with it, or unarchive the ones archived along with+ it, returning the number updated."+ [model-id :- ms/PositiveInt+ archived? :- :boolean]+ (if archived?+ (t2/update! :model/Action {:model_id model-id, :archived false} {:archived true, :archived_directly false})+ (t2/update! :model/Action {:model_id model-id, :archived true, :archived_directly false} {:archived false})))(mu/defn actions-for-model"The Actions of the model Card with `model-id`."@@ -372,10 +380,19 @@[action-ids :- [:set ::lib.schema.id/action]](t2/delete! :model/Action :id [:in action-ids]))+(mu/defn delete-dashcards-for-model-actions!+ "Delete the DashboardCards of the Actions of the model Card with `model-id`, returning the number deleted."+ [model-id :- ms/PositiveInt]+ (if-let [action-ids (not-empty (t2/select-pks-set :model/Action :model_id model-id))]+ (t2/delete! :model/DashboardCard :action_id [:in action-ids])+ 0))+(mu/defn archive-explicit-actions-for-model!- "Archive the non-implicit Actions of the model Card with `model-id`, returning the number updated."+ "Archive the unarchived non-implicit Actions of the model Card with `model-id` directly, returning the number+ updated."[model-id :- ms/PositiveInt]- (t2/update! :model/Action {:model_id model-id :type [:not= :implicit]} {:archived true}))+ (t2/update! :model/Action {:model_id model-id, :type [:not= :implicit], :archived false}+ {:archived true, :archived_directly true}))(mu/defn delete-implicit-actions-for-model!"Delete the implicit Actions of the model Card with `model-id`, returning the number deleted."diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex 7b3f37719f8..d1565e4ac86 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -537,18 +537,6 @@: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,- meaning there are no clauses such as filter, limit, breakout...-- It should be the opposite of [[metabase.lib.stage/has-clauses]] but for all stages."- [{query :dataset_query :as _card} :- ::queries.schema/card]- (and (seq query)- (every? (fn [stage-number]- (and (lib/mbql-stage? query stage-number)- (not (lib/has-clauses? query stage-number))))- (range 0 (count (:stages query))))))-(defn- disable-implicit-action-for-model!"Delete all implicit actions of a model if exists."[model-id]@@ -592,13 +580,16 @@;; updating a model dataset query to not support implicit actions will disable implicit actions if they exist(when (and (:dataset_query changes)(= (:type old-card-info) :model)- (not (model-supports-implicit-actions? changes)))+ (not (query/supports-implicit-actions? (:dataset_query changes))))(disable-implicit-action-for-model! id));; Changing from a Model to a Question: archive associated actions(when (and (= (:type changes) :question)(= (:type old-card-info) :model))+ (queries.db/delete-dashcards-for-model-actions! id)(queries.db/archive-explicit-actions-for-model! id)(queries.db/delete-implicit-actions-for-model! id))+ (when (contains? changes :archived)+ (queries.db/set-actions-of-model-archived! id (boolean (:archived changes))));; 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,6 +877,13 @@(sync.field-values/update-field-values-for-on-demand-dbs! field-ids))(parameter-card/upsert-or-delete-from-parameters! "card" (:id card) (:parameters card))))+(defn- move-model-actions+ "Moves the Actions of `card` into its Collection when the update changes it, returning `card`."+ [card original]+ (u/prog1 card+ (when (not= (:collection_id card) (:collection_id original))+ (queries.db/move-actions-of-models! #{(:id card)} (:collection_id card)))))+(defn- apply-dashboard-question-updates [card changes](if-let [dashboard-id (:dashboard_id changes)](assoc card :collection_id (queries.db/dashboard-collection-id dashboard-id))@@ -940,6 +938,7 @@(populate-query-fields (contains? changes :dataset_query))(clear-metabot-origin changes)(pre-update changes)+ (move-model-actions original)maybe-populate-initially-published-atpublic-sharing/add-public-uuid-prefix-if-changed)))@@ -1339,15 +1338,18 @@(log/errorf "Update of dependent card parameters failed!: %s" (ex-message e))))(collection/check-for-remote-sync-update card-before-update)))-(defn- retired-action-events- "The `[topic action]` pairs that announce how an update to a model retired its actions: `:event/action-delete` with+(defn- changed-action-events+ "The `[topic action]` pairs that announce how an update to a card changed its actions: `:event/action-delete` withthe old action for each of `actions-before` absent from `actions-after`, and `:event/action-update` with the new- action for each one that became archived."+ action for each one that was archived, unarchived, or moved to another Collection while unarchived."[actions-before actions-after](let [id->after (m/index-by :id actions-after)](for [before actions-before:let [after (id->after (:id before))]- :when (or (nil? after) (and (:archived after) (not (:archived before))))]+ :when (or (nil? after)+ (not= (:archived after) (:archived before))+ (and (not= (:collection_id after) (:collection_id before))+ (not (and (:archived before) (:archived after)))))](if after[:event/action-update after][:event/action-delete before]))))@@ -1355,14 +1357,13 @@(defn update-card!"Update a Card. Metadata is fetched asynchronously. If it is ready before [[metadata-sync-wait-ms]] elapses it will beincluded, otherwise the metadata will be saved to the database asynchronously. Publishes `:event/card-update`, plus- an action event for each action of a model that the update deletes or archives."+ an action event for each action of the card that the update deletes, archives, unarchives, or moves."[{:keys [card-before-update card-updates actor delete-old-dashcards?]}]- ;; The card hooks delete or archive a model's actions without events, so compare the actions before and after.- (let [actions-before (when (= :model (keyword (:type card-before-update)))- (queries.db/actions-for-model (:id card-before-update)))]+ ;; The card hooks delete, archive, or move a card's actions without events, so compare the actions before and after.+ (let [actions-before (queries.db/actions-for-model (:id card-before-update))](update-card-in-db! card-before-update card-updates actor delete-old-dashcards?)(when (seq actions-before)- (doseq [[topic action] (retired-action-events actions-before (queries.db/actions-for-model (:id card-before-update)))]+ (doseq [[topic action] (changed-action-events actions-before (queries.db/actions-for-model (:id card-before-update)))](events/publish-event! topic {:object action :user-id api/*current-user-id*}))));; Fetch the updated Card from the DB(let [card (queries.db/card (:id card-before-update))]@@ -1554,7 +1555,7 @@(defmethod serdes/deserialization-dependencies "Card" [card](card-deps false card))-(defmethod serdes/descendants "Card" [_model-name id {:keys [skip-archived]}]+(defmethod serdes/descendants "Card" [_model-name id _opts](let [card (queries.db/card id)query (not-empty (:dataset_query card))source-cards (some-> query lib/all-source-card-ids)@@ -1570,11 +1571,7 @@(for [card-id parameters-card-id]{["Card" card-id] {"Card" id}})(for [snippet-id snippets]- {["NativeQuerySnippet" snippet-id] {"Card" id}})- ;; An Action points at its model, but the model doesn't reference its actions, so list them here.- (when (= :model (:type card))- (for [action-id (queries.db/action-ids-for-model id skip-archived)]- {["Action" action-id] {"Card" id}}))))))+ {["NativeQuerySnippet" snippet-id] {"Card" id}})))))(defmethod serdes/extract-query "Card"[model-name {:keys [collection-set filter-column filter-ids] :as opts}]diff --git a/src/metabase/queries/models/query.clj b/src/metabase/queries/models/query.cljindex 989d02674e9..e9ead8a55b6 100644--- a/src/metabase/queries/models/query.clj+++ b/src/metabase/queries/models/query.clj@@ -176,3 +176,12 @@regardless of whether the Card has a native query or not."[query :- [:maybe [:or ::lib.schema/query ::lib-be.schema/empty-query]]](boolean (some-> query not-empty lib/native-only-query?)))++(mu/defn supports-implicit-actions? :- :boolean+ "Whether a model with `query` supports implicit actions: every stage is MBQL with no clauses, so it is a raw table."+ [query :- [:maybe [:or ::lib.schema/query ::lib-be.schema/empty-query]]]+ (boolean (and (seq query)+ (every? (fn [stage-number]+ (and (lib/mbql-stage? query stage-number)+ (not (lib/has-clauses? query stage-number))))+ (range 0 (count (:stages query)))))))diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.cljindex 2e8d41ee22b..23722eba4c9 100644--- a/src/metabase/queries_rest/api/card.clj+++ b/src/metabase/queries_rest/api/card.clj@@ -731,7 +731,8 @@(when-let [cards-without-position (seq (for [card cards:when (not (:collection_position card))](u/the-id card)))]- (queries-rest.db/set-cards-collection-raw! (set cards-without-position) new-collection-id-or-nil))+ (queries-rest.db/set-cards-collection-raw! (set cards-without-position) new-collection-id-or-nil)+ (queries/move-actions-of-models! (set cards-without-position) new-collection-id-or-nil))(doseq [card cards](collection/check-for-remote-sync-update card)))))diff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.cljindex 9ae8ba568e9..681a300dbda 100644--- a/src/metabase/search/in_place/legacy.clj+++ b/src/metabase/search/in_place/legacy.clj@@ -221,6 +221,7 @@search-ctx :- SearchContext](let [collection-id-col (case model"collection" :collection.id+ "action" :action.collection_id"search-index" :search_index.collection_id:collection_id)permitted-clause (if (= model "table")@@ -342,7 +343,7 @@[_](conj default-columns :model_id:creator_id- [:model.collection_id :collection_id]+ [:action.collection_id :collection_id][:model.id :model_id][:model.name :model_name][:query_action.database_id :database_id]diff --git a/src/metabase/typed_schemas/db.clj b/src/metabase/typed_schemas/db.cljindex 4bc54f2c376..88592b377f9 100644--- a/src/metabase/typed_schemas/db.clj+++ b/src/metabase/typed_schemas/db.clj@@ -57,12 +57,11 @@(t2/select [:model/Table :id :db_id :name :display_name] :id [:in table-ids] {:from [(warehouse-schema-overlay/table-query)]}))(mu/defn model-actions- "The id, model id, name, and type of the unarchived non-HTTP Actions of the model Cards with `model-ids`."+ "The id, model id, name, and type of the unarchived Actions of the model Cards with `model-ids`."[model-ids :- [:set ms/PositiveInt]](t2/select [:model/Action :id :model_id :name :type]:model_id [:in model-ids]- :archived false- :type [:not= "http"]))+ :archived false))(mu/defn field-table-id"The Table id of the Field with `field-id`, or nil."diff --git a/src/metabase/typed_schemas/schema/model.clj b/src/metabase/typed_schemas/schema/model.cljindex d3411ddd32c..d25e1c0962b 100644--- a/src/metabase/typed_schemas/schema/model.clj+++ b/src/metabase/typed_schemas/schema/model.clj@@ -169,7 +169,7 @@"Returns action details from the actions module, preserving lookup error context."[model](try- (actions/select-actions-non-http-for-models [model] #{(:id model)})+ (actions/select-actions-for-models [model] [(:id model)])(catch Exception exception(throw (ex-info (model-action-error-message model (ex-message exception))(error-data-with-cause-message@@ -182,7 +182,7 @@[models](let [model-ids (set (map :id models))](try- (actions/select-actions-non-http-for-models models model-ids)+ (actions/select-actions-for-models models (vec 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/warehouses/db.clj b/src/metabase/warehouses/db.cljindex e85bb02d66c..5da3d2f0de9 100644--- a/src/metabase/warehouses/db.clj+++ b/src/metabase/warehouses/db.clj@@ -102,6 +102,13 @@:select [:id]:where [:= :database_id database-id]}))+(mu/defn delete-query-actions-for-database!+ "Delete the query Actions whose query runs against the Database with `database-id`, returning the number deleted."+ [database-id :- ::lib.schema.id/database]+ (if-let [action-ids (not-empty (t2/select-fn-set :action_id :model/QueryAction :database_id database-id))]+ (t2/delete! :model/Action :id [:in action-ids])+ 0))+(mu/defn delete-cards-for-database!"Delete the Cards of the Database with `database-id`."[database-id :- ::lib.schema.id/database]diff --git a/src/metabase/warehouses/models/database.clj b/src/metabase/warehouses/models/database.cljindex 55a61ac423b..50a05f31b5c 100644--- a/src/metabase/warehouses/models/database.clj+++ b/src/metabase/warehouses/models/database.clj@@ -441,6 +441,7 @@(unschedule-tasks! database)(secret/delete-orphaned-secrets! database)(delete-database-fields! id)+ (warehouses.db/delete-query-actions-for-database! id)(->> (eduction(map t2.realize/realize)(partition-all 1000)diff --git a/test/metabase/actions/execution_test.clj b/test/metabase/actions/execution_test.cljindex 1f68c7a560e..1e031b91804 100644--- a/test/metabase/actions/execution_test.clj+++ b/test/metabase/actions/execution_test.clj@@ -167,15 +167,13 @@(testing "a public execution has no executor and its own context"(let [since (mt/latest-query-execution-id)](actions.execution/execute-action! (action/select-action :id action-id) {"id" 1 "name" "Bird"}- {:allow-http-actions? false- :context :public-action-execute})+ {:context :public-action-execute})(is (=? {:context :public-action-execute}(first (mt/action-executions since))))))(testing "a public dashcard execution carries the dashboard and the public context"(let [since (mt/latest-query-execution-id)](actions.execution/execute-dashcard! dashboard-id dashcard-id {"id" 1 "name" "Bird"}- {:allow-http-actions? false- :context :public-action-execute})+ {:context :public-action-execute})(is (=? {:context :public-action-execute, :dashboard_id dashboard-id}(first (mt/action-executions since))))))))))))@@ -189,8 +187,7 @@since (mt/latest-query-execution-id)](request/as-admin(actions.execution/execute-action! action {"id" 1 "name" "Bird"}- {:allow-http-actions? false- :context :public-action-execute}))+ {:context :public-action-execute}))(is (=? {:context :public-action-execute, :executor_id nil}(first (mt/action-executions since))))))))))@@ -206,8 +203,7 @@(mt/with-log-messages-for-level [messages [metabase.actions.audit :warn]](request/as-admin(actions.execution/execute-action! action {"id" 1 "name" "Bird"}- {:allow-http-actions? false- :context :public-action-execute}))+ {:context :public-action-execute}))(is (=? {:context :public-action-execute, :executor_id nil, :is_impersonated false}(first (mt/action-executions since))))(is (empty? (messages)))))))))))@@ -233,27 +229,6 @@(is (= #{1 "Bird"}(into #{} (map :value) (json/decode+kw (:parameters row))))))))))))))))-(deftest http-action-audit-trail-test- (testing "a refused HTTP action still leaves a trace, and the trace holds no template"- (mt/test-helpers-set-global-values!- (mt/with-actions-test-data-and-actions-enabled- (mt/with-actions [{:keys [action-id]} {:type :http}]- (mt/with-test-user :crowberto- (let [action (action/select-action :id action-id)- since (mt/latest-query-execution-id)]- (is (thrown-with-msg? ExceptionInfo #"HTTP actions are disabled."- (actions.execution/execute-action! action {"id" 1})))- (let [row (first (mt/action-executions since))]- (is (=? {:context :action-execute- :action_id action-id- :database_id nil- :native false- :error "HTTP actions are disabled."}- row))- (testing "only the internal descriptor is stored, never url/headers/body"- (is (= {:type "internal", :action "http/execute", :action-id action-id}- (recorded-template row))))))))))))-(deftest audit-write-failure-does-not-fail-the-action-test(testing "an audit insert that blows up after the warehouse write is logged, not thrown"(mt/test-helpers-set-global-values!diff --git a/test/metabase/actions/http_action_test.clj b/test/metabase/actions/http_action_test.cljdeleted file mode 100644index 8b5d8f0ad3c..00000000000--- a/test/metabase/actions/http_action_test.clj+++ /dev/null@@ -1,19 +0,0 @@-(ns metabase.actions.http-action-test- (:require- [clojure.test :refer :all]- [metabase.actions.http-action :as actions.http-action]))--(deftest ^:parallel parse-and-substitute-test- (are [params expected] (= expected- (#'actions.http-action/parse-and-substitute "https://example.com/{{param}}[[/{{optional-param}}]]" params))- {"param" "X"}- "https://example.com/X"-- {"param" "X", "optional-param" "Y"}- "https://example.com/X/Y"))--(deftest ^:parallel parse-and-substitute-error-test- (is (thrown-with-msg?- clojure.lang.ExceptionInfo- #"\QCannot call the service: missing required parameters: param\E"- (#'actions.http-action/parse-and-substitute "https://example.com/{{param}}[[/{{optional-param}}]]" nil))))diff --git a/test/metabase/actions/models_test.clj b/test/metabase/actions/models_test.cljindex 8e3625b4b27..43ca9d6474c 100644--- a/test/metabase/actions/models_test.clj+++ b/test/metabase/actions/models_test.clj@@ -9,10 +9,12 @@[metabase.driver :as driver][metabase.driver.mysql :as mysql][metabase.lib.core :as lib]+ [metabase.models.serialization :as serdes][metabase.query-processor.preprocess :as qp.preprocess][metabase.sync.core :as sync][metabase.test :as mt][metabase.test.data.one-off-dbs :as one-off-dbs]+ [metabase.util :as u][toucan2.core :as t2]))(deftest hydrate-query-action-test@@ -225,27 +227,72 @@(action/update! {:id action-id, :database_id Integer/MAX_VALUE} existing)(is (= model-db-id (:database_id (action/select-action :id action-id)))))))))+(deftest query-action-without-model-test+ (mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)+ (testing "a query action can be inserted and updated without a model, and keeps its own collection"+ (mt/with-temp [:model/Collection {coll-id :id} {}]+ (mt/with-model-cleanup [:model/Action]+ (let [action-id (action/insert! (lib/normalize ::actions.schema/action.for-insert+ {:type :query+ :name "No model"+ :collection_id coll-id+ :database_id (mt/id)+ :dataset_query (mt/native-query {:query "update categories set name = 'x' where id = 1"})}))]+ (is (=? {:model_id nil :collection_id coll-id :database_id (mt/id)}+ (action/select-action :id action-id)))+ (action/update! {:id action-id :name "Renamed"} (action/select-action :id action-id))+ (is (=? {:name "Renamed" :model_id nil :collection_id coll-id}+ (action/select-action :id action-id)))))))))++(deftest implicit-action-requires-model-test+ (mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)+ (testing "an implicit action cannot be inserted without a model"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"model_id"+ (action/insert! {:type :implicit :name "No model" :kind :row/create}))))+ (testing "an implicit action cannot be detached from its model"+ (mt/with-actions-enabled+ (mt/with-actions [{:keys [action-id]} {:type :implicit :kind "row/create"}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"model_id"+ (action/update! {:id action-id :model_id nil} (action/select-action :id action-id))))+ (is (some? (t2/select-one-fn :model_id :model/Action :id action-id))))))))++(deftest switching-to-implicit-checks-the-model-test+ (mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)+ (mt/with-actions-enabled+ (testing "a query action cannot become implicit when its card is a question"+ (mt/with-temp [:model/Card {question-id :id} {:type :question :dataset_query (mt/mbql-query categories)}]+ (mt/with-model-cleanup [:model/Action]+ (let [action-id (action/insert! (lib/normalize ::actions.schema/action.for-insert+ {:type :query+ :name "On a question"+ :model_id question-id+ :dataset_query (mt/native-query {:query "update categories set name = 'x' where id = 1"})}))]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Actions must be made with models, not cards"+ (action/update! {:id action-id :type :implicit :kind :row/update}+ (action/select-action :id action-id))))))))+ (testing "a query action cannot become implicit when its model has clauses"+ (mt/with-actions [_ {:type :model :dataset_query (mt/mbql-query categories {:limit 1})}+ {:keys [action-id]} {:type :query}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not supported for models with clauses"+ (action/update! {:id action-id :type :implicit :kind :row/update}+ (action/select-action :id action-id)))))))))+(deftest model-to-saved-question-test(mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)(mt/with-actions-enabled- (testing "Non-implicit actions are archived if their model is converted to a saved question"- (doseq [type [:http :query]]- (mt/with-actions [{:keys [action-id model-id]} {:type type}]+ (testing "Non-implicit actions are archived directly, and their dashboard buttons deleted, if their model is converted to a saved question"+ (mt/with-actions [{:keys [action-id model-id]} {:type :query}]+ (mt/with-temp [:model/Dashboard {dashboard-id :id} {}+ :model/DashboardCard {dashcard-id :id} {:action_id action-id :dashboard_id dashboard-id}](is (false? (t2/select-one-fn :archived :model/Action action-id)))(t2/update! :model/Card model-id {:type :question})- (is (true? (t2/select-one-fn :archived :model/Action action-id))))))+ (is (= [true true] ((juxt :archived :archived_directly) (t2/select-one :model/Action :id action-id))))+ (is (not (t2/exists? :model/DashboardCard :id dashcard-id))))))(testing "Implicit actions are deleted if their model is converted to a saved question"(mt/with-actions [{:keys [action-id model-id]} {:type :implicit}](is (false? (t2/select-one-fn :archived :model/Action action-id)))(t2/update! :model/Card model-id {:type :question})- (is (false? (t2/exists? :model/Action action-id)))))- (testing "Actions can't be unarchived if their model is a saved question"- (mt/with-actions [{:keys [action-id model-id]} {}]- (t2/update! :model/Card model-id {:type :question})- (is (thrown-with-msg?- Exception- #"Actions must be made with models, not cards"- (t2/update! :model/Action action-id {:archived false}))))))))+ (is (false? (t2/exists? :model/Action action-id))))))))(deftest model-to-saved-question-test-2(mt/test-drivers (mt/normal-drivers-with-feature :actions/custom)@@ -390,3 +437,13 @@(is (= {"name" true} (hide-state (action/select-action action-id))))(exec! "ALTER TABLE \"FOO\" ALTER COLUMN \"name\" BIGINT;")(is (= {"name" true} (hide-state (action/select-action action-id)))))))))))++(deftest load-skips-http-actions-test+ (testing "HTTP actions from older exports are skipped on load"+ (let [entity-id (u/generate-nano-id)]+ (serdes/load-one! {:type "http"+ :name "Old HTTP action"+ :entity_id entity-id+ :serdes/meta [{:model "Action" :id entity-id}]}+ nil)+ (is (not (t2/exists? :model/Action :entity_id entity-id))))))diff --git a/test/metabase/actions/test_util.clj b/test/metabase/actions/test_util.cljindex 27243db1b7b..df1966b5149 100644--- a/test/metabase/actions/test_util.clj+++ b/test/metabase/actions/test_util.clj@@ -19,7 +19,6 @@[metabase.test.data.datasets :as datasets][metabase.test.data.interface :as tx][metabase.test.data.users :as test.users]- [metabase.test.http-client :as client][metabase.test.initialize :as initialize][metabase.test.util :as tu][metabase.util.honey-sql-2 :as h2x]@@ -236,29 +235,6 @@options-map))]{:action-id action-id :model-id model-id}))-(defmethod create-action*! :http- [options-map model-id]- (let [action-id (insert-action! (merge- {:type :http- :name "Echo Example"- :template {:url (client/build-url "testing/echo[[?fail={{fail}}]]" {})- :method "POST"- :body "{\"the_parameter\": {{id}}}"- :headers "{\"x-test\": \"{{id}}\"}"}- :parameters [{:id "id"- :type "number"- :target [:dimension [:template-tag "id"]]}- {:id "fail"- :type "text"- :target [:dimension [:template-tag "fail"]]}]- :response_handle ".body"- :model_id model-id- :public_uuid (str (random-uuid))- :made_public_by_id (test.users/user->id :crowberto)- :creator_id (test.users/user->id :crowberto)}- options-map))]- {:action-id action-id :model-id model-id}))-(defn create-action!"Impl for [[with-action]]."[options-map model-id]@@ -286,7 +262,7 @@(with-actions [{model-card-id :id} {:type :model :dataset_query (mt/mbql-query types)}{id :action-id} {}- {:keys [action-id model-id]} {:type :http :name \"Temp HTTP Action\"}]+ {:keys [action-id model-id]} {:type :implicit :name \"Temp Implicit Action\"}](assert (= model-card-id model-id))(something model-card-id id action-id model-id))"{:style/indent 1, :arglists '([action-bindings & body]@@ -319,7 +295,7 @@(comment(with-actions [{id :action-id} {:type :implicit :kind "row/create"}- {:keys [action-id model-id]} {:type :http}]+ {:keys [action-id model-id]} {}](something id action-id model-id))(with-actions [{model-card-id :id} {:type :model, :dataset_query (data/mbql-query types)}{id :action-id} {:type :implicit :kind "row/create"}diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.cljindex b6c035f94c8..d17034e9d62 100644--- a/test/metabase/actions_rest/api_test.clj+++ b/test/metabase/actions_rest/api_test.clj@@ -229,7 +229,7 @@(is (= {:rows-affected 1} (mt/user-http-request :crowberto :post 200 url params)))))))))))))))(deftest action-query-db-differs-from-declared-db-test- (testing "a query action cannot execute against a database other than the one its query targets"+ (testing "a query action cannot be created against a database other than the one its query targets"(mt/dataset test-data(let [target-db-id (mt/id)] ;; the DB the malicious query really targets; actions OFF here(mt/dataset time-test-data@@ -247,16 +247,10 @@:dataset_query {:type "native":database target-db-id:native {:query "update people set source = 'pwned' where id = 1"}}- :parameters []}- created (mt/user-http-request :crowberto :post 200 "action" action)]- (testing "the declared database_id is overwritten with the query's real database on save"- (is (= target-db-id (:database_id created))))- (testing "execution is blocked because actions are disabled on the query's real DB"- (is (partial= {:message "Actions are not enabled."- :data {:database-id target-db-id}}- (mt/user-http-request :crowberto :post 400- (format "action/%s/execute" (:id created))- {:parameters {}})))))))))))))+ :parameters []}]+ (testing "creating it is refused because actions are disabled on the query's real DB"+ (is (= "Actions are not enabled."+ (:cause (mt/user-http-request :crowberto :post 400 "action" action))))))))))))))(deftest unified-action-create-test(mt/test-helpers-set-global-values!@@ -303,10 +297,13 @@(is (= "Actions are not enabled."(:cause(mt/user-http-request :crowberto :post 400 "action" initial-action))))))- (testing "a plain card instead of a model"+ (testing "an implicit action on a plain card instead of a model"(mt/with-temp [:model/Card {plain-card-id :id} {:dataset_query (mt/mbql-query users)}](is (= "Actions must be made with models, not cards."- (mt/user-http-request :crowberto :post 400 "action" (assoc initial-action :model_id plain-card-id)))))))+ (mt/user-http-request :crowberto :post 400 "action" {:name "implicit on a card"+ :type "implicit"+ :kind "row/create"+ :model_id plain-card-id}))))))(let [created-action (mt/user-http-request :crowberto :post 200 "action" initial-action)action-path (str "action/" (:id created-action))](testing "Create"@@ -422,9 +419,8 @@(is (=? {:errors {:name "string"},:specific-errors {:name ["missing required key, received: nil"]}}(mt/user-http-request :crowberto :post 400 "action" {:type "query"})))- (is (=? {:errors {:model_id "Valid Card ID"}- :specific-errors {:model_id ["missing required key, received: nil"]}}- (mt/user-http-request :crowberto :post 400 "action" {:type "query" :name "test"}))))))))))+ (is (=? {:specific-errors {:model_id ["missing required key, received: nil"]}}+ (mt/user-http-request :crowberto :post 400 "action" {:type "implicit" :name "test"}))))))))))(deftest native-query-action-requires-native-permission-test(testing "creating or updating a native query action requires native query permission on the database"@@ -476,6 +472,125 @@{:dataset_query (lib/native-query (mt/metadata-provider)"update users set name = 'baz' where id = {{x}}")}))))))))))))))+(defn- model-less-query-action+ "A POST body for a query action on the categories table with no model, in the Collection with `collection-id`."+ [collection-id]+ {:name "Rename Category"+ :type "query"+ :collection_id collection-id+ :database_id (mt/id)+ :dataset_query {:database (mt/id)+ :type "native"+ :native {:query "UPDATE categories SET name = {{name}} WHERE id = {{id}}"+ :template-tags {"id" {:name "id" :display-name "ID" :type "number" :required true}+ "name" {:name "name" :display-name "Name" :type "text" :required true}}}}+ :parameters [{:id "id" :slug "id" :type "number" :target [:variable [:template-tag "id"]]}+ {:id "name" :slug "name" :type "text" :target [:variable [:template-tag "name"]]}]})++(deftest action-without-model-test+ (testing "a query action without a model can be created, moved between collections, and executed"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-model-cleanup [:model/Action]+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Collection {other-id :id} {}]+ (let [created (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action coll-id))+ path (str "action/" (:id created))]+ (is (=? {:model_id nil :collection_id coll-id :database_id (mt/id)} created))+ (is (=? {:name "Renamed" :model_id nil :collection_id other-id}+ (mt/user-http-request :crowberto :put 200 path {:name "Renamed" :collection_id other-id})))+ (is (=? {:rows-affected 1}+ (mt/user-http-request :crowberto :post 200 (str path "/execute")+ {:parameters {:id 1 :name "Renamed Category"}})))+ (is (= "Renamed Category"+ (-> (mt/run-mbql-query categories {:fields [$name] :filter [:= $id 1]})+ mt/rows+ ffirst)))))))))++(deftest action-without-model-collection-perms-test+ (testing "creating or moving an action without a model requires write permission on its collection"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-model-cleanup [:model/Action]+ (mt/with-temp [:model/Collection {locked-id :id} {}]+ (let [personal-id (:id (collection/user->personal-collection (mt/user->id :rasta)))]+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "action" (model-less-query-action locked-id))))+ (let [created (mt/user-http-request :rasta :post 200 "action" (model-less-query-action personal-id))]+ (is (=? {:collection_id personal-id} created))+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 (str "action/" (:id created)) {:collection_id locked-id})))+ (is (= personal-id (t2/select-one-fn :collection_id :model/Action :id (:id created))))))))))))++(deftest list-actions-without-model-test+ (testing "the action list includes actions without a model, filtered by collection permissions"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-model-cleanup [:model/Action]+ (mt/with-temp [:model/Collection {locked-id :id} {}]+ (let [personal-id (:id (collection/user->personal-collection (mt/user->id :rasta)))+ visible (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action personal-id))+ hidden (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action locked-id))+ listed-ids (fn [user] (set (map :id (mt/user-http-request user :get 200 "action"))))]+ (is (set/subset? #{(:id visible) (:id hidden)} (listed-ids :crowberto)))+ (is (contains? (listed-ids :rasta) (:id visible)))+ (is (not (contains? (listed-ids :rasta) (:id hidden)))))))))))++(deftest attached-action-keeps-model-collection-test+ (testing "an action with a model stays in the model's collection whatever collection_id an update sends"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Collection {other-id :id} {}]+ (mt/with-actions [{:keys [action-id]} {:public_uuid nil :made_public_by_id nil :collection_id coll-id}]+ (let [model-collection (t2/select-one-fn :collection_id :model/Action :id action-id)]+ (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:collection_id other-id})+ (is (= model-collection (t2/select-one-fn :collection_id :model/Action :id action-id)))))))))++(deftest action-without-model-collection-guards-test+ (testing "an action without a model can only go in an existing, unarchived Collection of the default namespace"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-model-cleanup [:model/Action]+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Collection {snippets-id :id} {:namespace "snippets"}+ :model/Collection {archived-id :id} {:archived true}]+ (is (re-find #"can only go in Collections in the"+ (str (mt/user-http-request :crowberto :post 400 "action" (model-less-query-action snippets-id)))))+ (is (= "Not found."+ (mt/user-http-request :crowberto :post 404 "action" (model-less-query-action Integer/MAX_VALUE))))+ (let [path (str "action/" (:id (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action coll-id))))]+ (mt/user-http-request :crowberto :put 400 path {:collection_id archived-id})+ (is (= coll-id (:collection_id (mt/user-http-request :crowberto :get 200 path))))))))))++(deftest action-with-missing-model-test+ (testing "creating or moving an action onto a model that does not exist is a 404"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-model-cleanup [:model/Action]+ (is (= "Not found."+ (mt/user-http-request :crowberto :post 404 "action"+ (assoc (model-less-query-action nil) :model_id Integer/MAX_VALUE))))+ (let [path (str "action/" (:id (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action nil))))]+ (is (= "Not found."+ (mt/user-http-request :crowberto :put 404 path {:model_id Integer/MAX_VALUE}))))))))++(deftest archiving-directly-test+ (testing "archiving an action through the API marks it as archived directly, and unarchiving clears that"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-model-cleanup [:model/Action]+ (let [action-id (:id (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action nil)))+ state #((juxt :archived :archived_directly) (t2/select-one :model/Action :id action-id))]+ (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived true})+ (is (= [true true] (state)))+ (mt/user-http-request :crowberto :put 200 (str "action/" action-id) {:archived false})+ (is (= [false false] (state))))))))++(deftest update-checks-actions-enabled-test+ (testing "any update of a query action is refused while actions are disabled on its database"+ (mt/with-actions-test-data-and-actions-enabled+ (mt/with-model-cleanup [:model/Action]+ (let [path (str "action/" (:id (mt/user-http-request :crowberto :post 200 "action" (model-less-query-action nil))))]+ (mt/with-actions-disabled+ (is (= "Actions are not enabled."+ (:cause (mt/user-http-request :crowberto :put 400 path {:name "Renamed"}))))))))))+(deftest remap-parameter-keys-test(testing "remap-parameter-keys translates incoming parameter keys to the destination parameter's :id"(let [action {:parameters [{:id "d800e41d-edde-49cb-b63b-2386aba34334"@@ -827,3 +942,11 @@:errors {:user_id "This value does not exist in table \"users\"."}}(mt/user-http-request :rasta :post 400 (format "action/%d/execute" update-action){:parameters {"id" 1 "user_id" 99999}})))))))))++(deftest http-action-type-rejected-test+ (testing "HTTP actions no longer exist, so the API rejects their type"+ (mt/with-actions-enabled+ (mt/with-temp [:model/Card {model-id :id} {:type :model :dataset_query (mt/mbql-query venues)}]+ (is (contains? (:specific-errors (mt/user-http-request :crowberto :post 400 "action"+ {:name "HTTP" :type "http" :model_id model-id}))+ :type))))))diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex e53d01e5740..b83b40e3c90 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -3507,3 +3507,99 @@:mysql " AND table_schema = database()":postgres " AND table_schema = current_schema()":h2 ""))]))))))))++(deftest action-collection-id-backfill-test+ (testing "v65.2026-10-02T00:00:06: each action takes its model's collection, model_id becomes nullable, and+ already-archived actions count as archived directly, and archived models' actions get archived"+ (impl/test-migrations ["v65.2026-10-02T00:00:00" "v65.2026-10-02T00:00:07"] [migrate!]+ (let [user-id (t2/insert-returning-pk! :core_user {:first_name "Action"+ :last_name "Owner"+ :email "[email protected]"+ :password "superstrong"+ :entity_id (u/generate-nano-id)+ :date_joined :%now})+ db-id (t2/insert-returning-pk! :metabase_database {:name "Action Test DB"+ :engine "h2"+ :created_at :%now+ :updated_at :%now+ :details "{}"})+ coll-id (t2/insert-returning-pk! :collection {:name "Models"+ :slug "models"+ :entity_id (u/generate-nano-id)+ :location "/"})+ insert-model! (fn [collection-id & {:keys [archived]}]+ (t2/insert-returning-pk! :report_card {:name "Model"+ :entity_id (u/generate-nano-id)+ :type "model"+ :display "table"+ :dataset_query "{}"+ :visualization_settings "{}"+ :creator_id user-id+ :database_id db-id+ :collection_id collection-id+ :archived (boolean archived)+ :created_at :%now+ :updated_at :%now}))+ insert-action! (fn [model-id & {:keys [archived]}]+ (t2/insert-returning-pk! :action {:name "Action"+ :archived (boolean archived)+ :entity_id (u/generate-nano-id)+ :type "implicit"+ :model_id model-id+ :created_at :%now+ :updated_at :%now}))+ in-coll (insert-action! (insert-model! coll-id))+ in-root (insert-action! (insert-model! nil))+ archived (insert-action! (insert-model! coll-id) :archived true)+ on-trashed-model (insert-action! (insert-model! coll-id :archived true))]+ (migrate!)+ (is (true? (t2/select-one-fn :archived_directly :action :id archived)))+ (is (false? (t2/select-one-fn :archived_directly :action :id in-coll)))+ (testing "the actions of an archived model are archived with it"+ (is (= [true false] ((juxt :archived :archived_directly) (t2/select-one :action :id on-trashed-model)))))+ (is (= coll-id (t2/select-one-fn :collection_id :action :id in-coll)))+ (is (nil? (t2/select-one-fn :collection_id :action :id in-root)))+ (testing "an action can be inserted without a model"+ (is (pos-int? (insert-action! nil))))))))++(deftest drop-http-actions-test+ (testing "v65.2026-10-03T00:00:01: HTTP actions and the dashboard buttons that ran them are deleted, other actions stay"+ (impl/test-migrations ["v65.2026-10-03T00:00:00" "v65.2026-10-03T00:00:01"] [migrate!]+ (let [user-id (t2/insert-returning-pk! :core_user {:first_name "Action"+ :last_name "Owner"+ :email "[email protected]"+ :password "superstrong"+ :entity_id (u/generate-nano-id)+ :date_joined :%now})+ dash-id (t2/insert-returning-pk! :report_dashboard {:name "Buttons"+ :creator_id user-id+ :parameters "[]"+ :entity_id (u/generate-nano-id)+ :created_at :%now+ :updated_at :%now})+ insert-action! (fn [action-type]+ (t2/insert-returning-pk! :action {:name "Action"+ :entity_id (u/generate-nano-id)+ :type action-type+ :created_at :%now+ :updated_at :%now}))+ insert-button! (fn [action-id]+ (t2/insert-returning-pk! :report_dashboardcard {:dashboard_id dash-id+ :action_id action-id+ :parameter_mappings "[]"+ :visualization_settings "{}"+ :entity_id (u/generate-nano-id)+ :size_x 4+ :size_y 4+ :row 0+ :col 0+ :created_at :%now+ :updated_at :%now}))+ http-id (insert-action! "http")+ implicit-id (insert-action! "implicit")+ http-button (insert-button! http-id)+ other-button (insert-button! implicit-id)]+ (t2/insert! :http_action {:action_id http-id :template "{}"})+ (migrate!)+ (is (= #{implicit-id} (t2/select-pks-set :action)))+ (is (= #{other-button} (t2/select-pks-set :report_dashboardcard :id [:in [http-button other-button]])))))))diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex 663547f3125..81ff49684b1 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -200,6 +200,42 @@(unarchive-collection! (t2/select-one :model/Collection :id (u/the-id collection)))(is (false? (t2/select-one-fn :archived :model/Card :id (u/the-id card)))))))+(deftest archive-actions-test+ (testing "archiving a Collection archives its Actions and keeps their dashboard buttons, and unarchiving restores+ only the Actions archived along with it"+ (mt/with-temp [:model/Collection collection {}+ :model/Card model {:type :model :collection_id (u/the-id collection)}+ :model/Action action {:type :query :name "Rename" :model_id (u/the-id model)}+ :model/Action old-action {:type :query :name "Old" :model_id (u/the-id model)+ :archived true :archived_directly true}+ :model/Dashboard dashboard {:collection_id (u/the-id collection)}+ :model/DashboardCard dashcard {:dashboard_id (u/the-id dashboard) :action_id (u/the-id action)}]+ (archive-collection! collection)+ (is (true? (t2/select-one-fn :archived :model/Action :id (u/the-id action))))+ (is (t2/exists? :model/DashboardCard :id (u/the-id dashcard)))+ (unarchive-collection! (t2/select-one :model/Collection :id (u/the-id collection)))+ (is (false? (t2/select-one-fn :archived :model/Action :id (u/the-id action))))+ (is (true? (t2/select-one-fn :archived :model/Action :id (u/the-id old-action)))))))++(deftest unarchive-collection-keeps-actions-of-archived-models-test+ (testing "restoring a Collection does not restore the Actions of a model that is still in the trash"+ (mt/with-temp [:model/Collection collection {}+ :model/Card model {:type :model :collection_id (u/the-id collection)}+ :model/Action action {:type :query :name "Rename" :model_id (u/the-id model)}]+ (t2/update! :model/Card (u/the-id model) {:archived true :archived_directly true})+ (archive-collection! collection)+ (unarchive-collection! (t2/select-one :model/Collection :id (u/the-id collection)))+ (is (true? (t2/select-one-fn :archived :model/Card :id (u/the-id model))))+ (is (true? (t2/select-one-fn :archived :model/Action :id (u/the-id action)))))))++(deftest delete-collection-deletes-actions-test+ (testing "deleting a Collection deletes the Actions in it, including the ones without a model"+ (mt/with-temp [:model/Collection collection {}+ :model/Action action {:type :query :name "No model" :model_id nil+ :collection_id (u/the-id collection)}]+ (t2/delete! :model/Collection :id (u/the-id collection))+ (is (not (t2/exists? :model/Action :id (u/the-id action)))))))+(deftest validate-name-test(testing "check that collections' names cannot be blank"(is (thrown?diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.cljindex 0ed03eb8cc9..43264b587a7 100644--- a/test/metabase/dashboards_rest/api_test.clj+++ b/test/metabase/dashboards_rest/api_test.clj@@ -2370,7 +2370,7 @@(deftest dashcard-action-create-update-test(mt/test-drivers (mt/normal-drivers-with-feature :actions)(mt/with-actions-test-data-and-actions-enabled- (doseq [action-type [:http :implicit :query]]+ (doseq [action-type [:implicit :query]](mt/with-actions [{:keys [action-id]} {:type action-type :visualization_settings {:hello true}}](testing (str "Creating dashcard with action: " action-type)(mt/with-temp [:model/Dashboard {dashboard-id :id} {}]@@ -2387,12 +2387,11 @@:action_id action-id:visualization_settings {:label "Update"}}]:tabs []}))))- (is (partial= {:dashcards [{:action (cond-> {:visualization_settings {:hello true}- :type (name action-type)- :parameters [{:id "id"}]- :database_enabled_actions true}- (#{:query :implicit} action-type)- (assoc :database_id (mt/id)))}]}+ (is (partial= {:dashcards [{:action {:visualization_settings {:hello true}+ :type (name action-type)+ :parameters [{:id "id"}]+ :database_enabled_actions true+ :database_id (mt/id)}}]}(mt/user-http-request :crowberto :get 200 (format "dashboard/%s" dashboard-id)))))))))))(deftest dashcard-action-database-enabled-actions-testdiff --git a/test/metabase/eid_translation/util_test.clj b/test/metabase/eid_translation/util_test.cljindex 7d1d92778ed..6f38b61aa9c 100644--- a/test/metabase/eid_translation/util_test.clj+++ b/test/metabase/eid_translation/util_test.clj@@ -80,7 +80,7 @@:model/Field {field-id :id} {};; eid models:- :model/Action {action_id :id action_eid :entity_id} {:name "model for creating action" :model_id model-id :type :http}+ :model/Action {action_id :id action_eid :entity_id} {:name "model for creating action" :model_id model-id :type :query}:model/Collection {collection_id :id collection_eid :entity_id} {};; filling entity id for User doesn't work: do it manually below.:model/User {core_user_id :id #_#_core_user_eid :entity_id} {}diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex eb3ef330e42..5a68c516621 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -115,7 +115,7 @@[database-id]{:database database-id:type :query- :query {:source-table 1}})+ :query {:source-table (mt/id :venues)}})(deftest database-id-test(mt/with-temp [:model/Card {:keys [id]} {:name "some name"@@ -179,16 +179,14 @@(deftest disable-implicit-actions-if-needed-test-3(mt/with-actions-enabled(testing "unhappy paths\n"- (testing "only disable implicit actions, not http and query"+ (testing "only disable implicit actions, not query"(mt/with-actions [{model-id :id} {:type :model, :dataset_query (mt/mbql-query users)}{implicit-id :action-id} {:type :implicit}- {http-id :action-id} {:type :http}{query-id :action-id} {:type :query}];; make sure we have thing exists to start with- (is (= 3 (t2/count :model/Action :id [:in [implicit-id http-id query-id]])))+ (is (= 2 (t2/count :model/Action :id [:in [implicit-id query-id]])))(t2/update! :model/Card :id model-id {:dataset_query (mt/mbql-query users {:limit 1})})(is (not (t2/exists? :model/Action :id implicit-id)))- (is (t2/exists? :model/Action :id http-id))(is (t2/exists? :model/Action :id query-id)))))))(deftest disable-implicit-actions-if-needed-test-4@@ -769,21 +767,6 @@(is (= {["Card" (:id card1)] {"Card" (:id card2)}}(serdes/descendants "Card" (:id card2) {}))))))-(deftest ^:parallel descendants-model-actions-test- (testing "GHY-4722: a model's actions are its descendants, though the model doesn't reference them"- (mt/with-temp [:model/Card {model-id :id} {:type :model- :dataset_query {:database (mt/id)- :type :query- :query {:source-table (mt/id :venues)}}}- :model/Action {action-id :id} {:type :implicit :name "Live" :model_id model-id}- :model/Action {archived-id :id} {:type :implicit :name "Archived" :model_id model-id :archived true}]- (is (= {["Action" action-id] {"Card" model-id}- ["Action" archived-id] {"Card" model-id}}- (serdes/descendants "Card" model-id {})))- (testing "with :skip-archived, archived actions are left out"- (is (= {["Action" action-id] {"Card" model-id}}- (serdes/descendants "Card" model-id {:skip-archived true})))))))-(defn- action-events-during!"The set of `[topic action-id archived?]` for the action events `thunk` publishes."[thunk]@@ -801,7 +784,8 @@(mt/with-temp [:model/Card {model-id :id} {:type :model :dataset_query (mt/mbql-query venues)}:model/Action {implicit :id} {:type :implicit :name "Create" :model_id model-id}:model/Action {query :id} {:type :query :name "Rename" :model_id model-id}- :model/Action {archived :id} {:type :query :name "Old" :model_id model-id :archived true}]+ :model/Action {archived :id} {:type :query :name "Old" :model_id model-id :archived true+ :archived_directly true}];; the implicit_action row is what marks an action implicit to the queries that retire them(t2/insert! :model/ImplicitAction {:action_id implicit :kind "row/create"})(f {:model-id model-id :implicit implicit :query query :archived archived})))@@ -821,7 +805,7 @@(lib/filter (lib/> (lib.metadata/field mp (mt/id :venues :price)) 1)))))(deftest model-becoming-question-publishes-action-events-test- (testing "GHY-4722: update-card! announces the actions it archives and deletes when a model becomes a question"+ (testing "update-card! announces the actions it archives and deletes when a model becomes a question"(do-with-model-actions!(fn [{:keys [model-id implicit query]}](is (= #{[:event/action-update query true]@@ -835,6 +819,57 @@(is (= #{[:event/action-delete implicit false]}(action-events-during! #(update-model! model-id {:dataset_query (filtered-venues-query)}))))))))+(deftest model-move-publishes-action-events-test+ (testing "update-card! announces the unarchived actions that move with a model to another collection"+ (mt/with-temp [:model/Collection {coll-id :id} {}]+ (do-with-model-actions!+ (fn [{:keys [model-id implicit query]}]+ (is (= #{[:event/action-update implicit false]+ [:event/action-update query false]}+ (action-events-during! #(update-model! model-id {:collection_id coll-id})))))))))++(deftest question-move-publishes-action-events-test+ (testing "update-card! announces the actions that move with a question"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Card {question-id :id} {:type :question :dataset_query (mt/mbql-query venues)}+ :model/Action {action-id :id} {:type :query :name "On a question" :model_id question-id}]+ (is (= #{[:event/action-update action-id false]}+ (action-events-during! #(update-model! question-id {:collection_id coll-id})))))))++(deftest model-archive-cascades-to-actions-test+ (testing "archiving a model archives its actions, and unarchiving it restores only those"+ (do-with-model-actions!+ (fn [{:keys [model-id implicit query archived]}]+ (let [archived-state #(t2/select-pk->fn (juxt :archived :archived_directly) :model/Action :model_id model-id)]+ (is (= #{[:event/action-update implicit true]+ [:event/action-update query true]}+ (action-events-during! #(update-model! model-id {:archived true}))))+ (is (= {implicit [true false], query [true false], archived [true true]} (archived-state)))+ (is (= #{[:event/action-update implicit false]+ [:event/action-update query false]}+ (action-events-during! #(update-model! model-id {:archived false}))))+ (is (= {implicit [false false], query [false false], archived [true true]} (archived-state))))))))++(deftest model-actions-follow-model-collection-test+ (testing "the actions of a model are kept in the model's collection"+ (mt/with-temp [:model/Collection {coll-1 :id} {}+ :model/Collection {coll-2 :id} {}+ :model/Card {model-id :id} {:type :model :collection_id coll-1 :dataset_query (mt/mbql-query venues)}+ :model/Card {other-id :id} {:type :model :collection_id coll-2 :dataset_query (mt/mbql-query venues)}+ :model/Action {action-id :id} {:type :query :name "Rename" :model_id model-id}]+ (let [action-collection #(t2/select-one-fn :collection_id :model/Action :id action-id)]+ (testing "an inserted action takes its model's collection"+ (is (= coll-1 (action-collection))))+ (testing "moving the model moves its actions"+ (t2/update! :model/Card model-id {:collection_id coll-2})+ (is (= coll-2 (action-collection)))+ (t2/update! :model/Card model-id {:collection_id nil})+ (is (nil? (action-collection))))+ (testing "attaching an action to another model moves it to that model's collection"+ (t2/update! :model/Card model-id {:collection_id coll-1})+ (t2/update! :model/Action action-id {:model_id other-id})+ (is (= coll-2 (action-collection))))))))+(deftest model-changes-outside-update-card-publish-no-action-events-test(testing "GHY-4722: a serdes load writes models with t2 directly, and must not publish action events (they would dirty the remote sync ledger during a pull)"(testing "a model becoming a question"diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.cljindex eaafaf0b8c3..a892efb9b81 100644--- a/test/metabase/queries_rest/api/card_test.clj+++ b/test/metabase/queries_rest/api/card_test.clj@@ -3180,6 +3180,18 @@:collections ["New Collection" "New Collection"]}(POST-card-collections! :crowberto 200 new-collection [card-1 card-2])))))+(deftest bulk-move-moves-model-actions-test+ (testing "bulk-moving models moves their actions too"+ (mt/with-temp [:model/Collection old-collection {}+ :model/Collection new-collection {}+ :model/Card model-1 {:type :model :collection_id (u/the-id old-collection)}+ :model/Card model-2 {:type :model :collection_id (u/the-id old-collection)}+ :model/Action action-1 {:type :query :name "One" :model_id (u/the-id model-1)}+ :model/Action action-2 {:type :query :name "Two" :model_id (u/the-id model-2)}]+ (POST-card-collections! :crowberto 200 new-collection [model-1 model-2])+ (is (= #{(u/the-id new-collection)}+ (t2/select-fn-set :collection_id :model/Action :id [:in [(u/the-id action-1) (u/the-id action-2)]]))))))+(deftest test-that-we-can-bulk-remove-some-cards-from-a-collection(mt/with-temp [:model/Collection collection {}:model/Card card-1 {:collection_id (u/the-id collection)}diff --git a/test/metabase/search/api_test.clj b/test/metabase/search/api_test.cljindex fb86c9f5b52..826899a471b 100644--- a/test/metabase/search/api_test.clj+++ b/test/metabase/search/api_test.clj@@ -1236,7 +1236,7 @@:model/Card {card-id-4 :id} {:name (format "%s Card 4" search-term) :creator_id user-id-2}:model/Card {model-id :id} {:name (format "%s Dataset 1" search-term) :type :model :creator_id user-id}:model/Dashboard {dashboard-id :id} {:name (format "%s Dashboard 1" search-term) :creator_id user-id}- :model/Action {action-id :id} {:name (format "%s Action 1" search-term) :model_id model-id :creator_id user-id :type :http}]+ :model/Action {action-id :id} {:name (format "%s Action 1" search-term) :model_id model-id :creator_id user-id :type :query}](testing "sanity check that without search by created_by we have more results than if a filter is provided"(is (> (:total (mt/user-http-request :crowberto :get 200 "search" :q search-term))5)))@@ -1459,7 +1459,7 @@:model/Card {metric-id :id} {:name search-term :type :metric}:model/Action {action-id :id} {:name search-term:model_id model-id- :type :http}]+ :type :query}](doseq [[model id] [[:model/Card card-id] [:model/Card model-id][:model/Dashboard dash-id] [:model/Card metric-id]]](revision/push-revision!@@ -1549,7 +1549,7 @@(t2/select-one-fn :query_type :model/Card :id native-card-in-query)))(mt/with-actions[_ {:type :model :dataset_query (mt/mbql-query venues)}- {http-action :action-id} {:type :http :name search-term}+ {named-action :action-id} {:type :implicit :name search-term}{query-action :action-id} {:type :query :dataset_query (mt/native-query {:query (format "delete from %s" search-term)})}];; TODO investigate why the actions don't get indexed automatically(search/reindex! {:async? false :in-place? true})@@ -1558,7 +1558,7 @@["card" native-card-in-name]["dataset" mbql-model]["dataset" native-model-in-name]- ["action" http-action]}+ ["action" named-action]}(->> (mt/user-http-request :crowberto :get 200 "search" :q search-term):data(map (juxt :model :id))@@ -1568,7 +1568,7 @@["card" native-card-in-name]["dataset" mbql-model]["dataset" native-model-in-name]- ["action" http-action]+ ["action" named-action]["card" native-card-in-query]["dataset" native-model-in-query]["action" query-action]}diff --git a/test/metabase/search/appdb/index_test.clj b/test/metabase/search/appdb/index_test.cljindex 5256ea6e65f..0d4e6ae1fae 100644--- a/test/metabase/search/appdb/index_test.clj+++ b/test/metabase/search/appdb/index_test.clj@@ -375,7 +375,8 @@:updated_at yesterday;; :archived = true:archived true}- :model/QueryAction _ {:dataset_query (mt/native-query {:query "select * from metabase"})+ :model/QueryAction _ {:dataset_query (assoc (mt/native-query {:query "select * from metabase"})+ :database db-id);; :database_id = db-id:database_id db-id:action_id action-id}]diff --git a/test/metabase/search/impl_test.clj b/test/metabase/search/impl_test.cljindex 1503af23e16..600725ffd5a 100644--- a/test/metabase/search/impl_test.clj+++ b/test/metabase/search/impl_test.clj@@ -157,11 +157,11 @@:created_at two-years-ago}:model/Action {action-new :id} {:name search-term:model_id model-new- :type :http+ :type :query:created_at new}:model/Action {action-old :id} {:name search-term:model_id model-old- :type :http+ :type :query:created_at two-years-ago}:model/Segment {_segment-new :id} {:name search-term:created_at new}@@ -236,11 +236,11 @@:model/Card {metric-old :id} {:name search-term :type :metric}:model/Action {action-new :id} {:name search-term:model_id model-new- :type :http+ :type :query:updated_at new}:model/Action {action-old :id} {:name search-term:model_id model-old- :type :http+ :type :query:updated_at two-years-ago}](t2/insert! (t2/table-name :model/Revision) (for [[model model-id timestamp][["Dashboard" dashboard-new new]diff --git a/test/metabase/test/generate.clj b/test/metabase/test/generate.cljindex 0f18a95500a..6fc7ea6099e 100644--- a/test/metabase/test/generate.clj+++ b/test/metabase/test/generate.clj@@ -124,14 +124,11 @@(s/def ::parameter (s/keys :req-un [:parameter/id :parameter/type]))(s/def ::parameters (s/coll-of ::parameter))-(s/def :action/type #{:query :implicit :http})+(s/def :action/type #{:query :implicit});; * implicit_action(s/def ::kind #{"row/create" "row/update" "row/delete"})-;; * http_action-(s/def ::template #{{:method "GET" :url "https://example.com"}})-;; * pulse(s/def ::row pos-int?)(s/def ::col pos-int?)@@ -143,7 +140,6 @@(s/def ::action (s/keys :req-un [::id :action/type ::name]))(s/def ::query-action (s/keys :req-un [::dataset_query]))(s/def ::implicit-action (s/keys :req-un [::kind]))-(s/def ::http-action (s/keys :req-un [::template]))(s/def ::core-user (s/keys :req-un [::id ::first_name ::last_name ::email ::password]))(s/def ::collection (s/keys :req-un [::id ::name]))@@ -208,10 +204,6 @@:spec ::implicit-action:insert! {:model :model/ImplicitAction}:relations {:action_id [:action :id]}}- :http-action {:prefix :http-action- :spec ::http-action- :insert! {:model :model/HTTPAction}- :relations {:action_id [:action :id]}}:database {:prefix :db:spec ::database:insert! {:model :model/Database}}diff --git a/test/metabase/typed_schemas/schema/model_test.clj b/test/metabase/typed_schemas/schema/model_test.cljindex c63e010cf3b..ba7c1a99805 100644--- a/test/metabase/typed_schemas/schema/model_test.clj+++ b/test/metabase/typed_schemas/schema/model_test.clj@@ -87,7 +87,7 @@{:id 43 :name "Model 43"}])schema.model/action-rows(constantly [{:id 5 :model_id 42 :name "Create" :type :query}])- actions/select-actions-non-http-for-models+ actions/select-actions-for-models(constantly [{:id 5:model_id 42:name "Create"@@ -107,13 +107,13 @@schema.model/action-rows (fn [model-ids](swap! action-rows-calls conj model-ids)[])- actions/select-actions-non-http-for-models (fn [known-models model-ids]- (swap! action-details-calls conj [known-models model-ids])- [])]+ actions/select-actions-for-models (fn [known-models model-ids]+ (swap! action-details-calls conj [known-models model-ids])+ [])](is (= {:models [] :errors []} (schema.model/model-schemas #{1} nil)))(is (= [#{42 43}] @action-rows-calls))(is (= [[models #{42 43}]]- @action-details-calls)))))+ (map (fn [[known-models model-ids]] [known-models (set model-ids)]) @action-details-calls))))))(deftest model-schemas-collects-broken-model-errors-test(testing "a broken model becomes an :errors entry while healthy models still build"@@ -124,7 +124,7 @@(constantly [{:id 5 :model_id 42 :name "Create" :type :query};; model 43's action row resolves to no action details{:id 6 :model_id 43 :name "Broken action" :type :broken}])- actions/select-actions-non-http-for-models+ actions/select-actions-for-models(constantly [{:id 5:model_id 42:name "Create"@@ -144,13 +144,13 @@(constantly [{:id 42 :name "Model 42"}{:id 43 :name "Broken model"}]);; bulk lookup blows up for the whole batch- actions/select-actions-non-http-for-models+ actions/select-actions-for-models(fn [_known-models model-ids](cond(< 1 (count model-ids))(throw (ex-info "bulk lookup exploded" {}))- (= model-ids #{42})+ (= (set model-ids) #{42})[{:id 5 :model_id 42 :name "Create" :type :query :parameters []}]:else@@ -174,7 +174,7 @@(with-redefs [schema.common/select-schema-cards(constantly [{:id 42 :name "Model 42"}])schema.model/action-rows (constantly [])- actions/select-actions-non-http-for-models+ actions/select-actions-for-models(fn [& _] (throw (InterruptedException. "cancelled")))](let [thrown (is (thrown? clojure.lang.ExceptionInfo(schema.model/model-schemas #{1} nil)))]@@ -183,7 +183,7 @@(with-redefs [schema.common/select-schema-cards(constantly [{:id 42 :name "Model 42"}])schema.model/action-rows (constantly [])- actions/select-actions-non-http-for-models (constantly [])+ actions/select-actions-for-models (constantly [])schema.model/model-action-schemas(fn [& _] (throw (ex-info "cancelled" {} (InterruptedException. "cancelled"))))](let [thrown (is (thrown? clojure.lang.ExceptionInfo@@ -195,7 +195,7 @@(with-redefs [schema.common/select-schema-cards(constantly [{:id 42 :name "Model 42"}])schema.model/action-rows (constantly [])- actions/select-actions-non-http-for-models (constantly [])+ actions/select-actions-for-models (constantly [])schema.model/model-action-schemas(fn [& _] (throw (NullPointerException. "boom")))](is (thrown? NullPointerException@@ -203,7 +203,7 @@(deftest model-schema-surfaces-action-selection-errors-test(with-redefs [schema.model/action-rows (constantly [])- actions/select-actions-non-http-for-models+ actions/select-actions-for-models(fn [& _](throw (ex-info "action lookup failed"{:status-code 500})))]@@ -219,7 +219,7 @@(ex-data exception))))))(deftest model-schema-surfaces-action-rendering-errors-test- (with-redefs [actions/select-actions-non-http-for-models+ (with-redefs [actions/select-actions-for-models(constantly [{:id 200:name "Broken action":type :query}])@@ -247,7 +247,7 @@(with-redefs [schema.model/action-rows (constantly [{:id 200:name "Broken action":type :broken}])- actions/select-actions-non-http-for-models (constantly [])]+ actions/select-actions-for-models (constantly [])](let [exception (is (thrown? clojure.lang.ExceptionInfo(schema.model/model-schema {:id 100:name "Broken model"})))]diff --git a/test/metabase/warehouses/models/database_test.clj b/test/metabase/warehouses/models/database_test.cljindex 55085c0966f..9d0dd6989aa 100644--- a/test/metabase/warehouses/models/database_test.clj+++ b/test/metabase/warehouses/models/database_test.clj@@ -119,6 +119,17 @@(is (= nil(trigger-for-db db-id))))))))+(deftest delete-database-deletes-query-actions-test+ (testing "deleting a Database deletes the query Actions that run against it, including the ones without a model"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Action {action-id :id} {:type :query :name "No model" :model_id nil}+ :model/QueryAction _ {:action_id action-id+ :dataset_query {:database db-id+ :type :native+ :native {:query "select 1"}}}]+ (t2/delete! :model/Database :id db-id)+ (is (not (t2/exists? :model/Action :id action-id))))))+(deftest health-check-candidates-test(testing "startup health checks pick one representative database per engine: the lowest id, skippingaudit/sample/destination databases"diff --git a/test_resources/serialization_baseline/actions/my_action.yaml b/test_resources/serialization_baseline/collections/main/my_action.yamlsimilarity index 97%rename from test_resources/serialization_baseline/actions/my_action.yamlrename to test_resources/serialization_baseline/collections/main/my_action.yamlindex 865dfe2236f..9a4f7cce7bc 100644--- a/test_resources/serialization_baseline/actions/my_action.yaml+++ b/test_resources/serialization_baseline/collections/main/my_action.yaml@@ -1,7 +1,6 @@created_at: '2026-04-02T01:50:06.081195Z'creator_id: [email protected]entity_id: aCtiOn00ExAmPlEx00001-http: []implicit:- kind: row/updatemodel_id: sRcMoDeL00ExAmPlEx001