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
Support named tables for python transforms (#66934)
Ngoc Khuatf14e1f144499
diff --git a/e2e/test/scenarios/data-studio/transforms.cy.spec.ts b/e2e/test/scenarios/data-studio/transforms.cy.spec.tsindex 23c617d050b..364ed96a45e 100644--- a/e2e/test/scenarios/data-studio/transforms.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/transforms.cy.spec.ts@@ -235,7 +235,7 @@ describe("scenarios > admin > transforms", () => {});cy.findByTestId("python-data-picker")- .findByText("Select a database")+ .findByText("Writable Postgres12").click();cy.log("Unsupported databases should be disabled");@@ -606,7 +606,13 @@ LIMITit("should not be possible to create a sql transform from a table from an unsupported database", () => {visitTransformListPage();cy.button("Create a transform").click();+H.popover().findByText("SQL query").click();++ cy.findByTestId("gui-builder-data")+ .findByText("Writable Postgres12")+ .click();+H.popover().findByRole("option", { name: "Sample Database" }).should("have.attr", "aria-disabled", "true")diff --git a/enterprise/backend/src/metabase_enterprise/transforms/api.clj b/enterprise/backend/src/metabase_enterprise/transforms/api.cljindex 38c7cdfa679..901cf57edcf 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/api.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/api.clj@@ -47,6 +47,18 @@(mr/def ::run-trigger[:enum "none" "global-schedule"])+(defn- python-source-table-ref->table-id+ "Change source of python transform from name->table-ref to name->table-id.++ We now supported table-ref as source but since FE is still expecting table-id we need to temporarily do this.+ Should update FE to fully use table-ref"+ [transform]+ (if (transforms.util/python-transform? transform)+ (update-in transform [:source :source-tables]+ (fn [source-tables]+ (update-vals source-tables #(if (int? %) % (:table_id %)))))+ transform))+(comment;; Examples[{:id 1@@ -88,7 +100,8 @@(comp (transforms.util/->date-field-filter-xf [:last_run :start_time] last_run_start_time)(transforms.util/->status-filter-xf [:last_run :status] last_run_statuses)(transforms.util/->tag-filter-xf [:tag_ids] tag_ids)- (map #(update % :last_run transforms.util/localize-run-timestamps)))+ (map #(update % :last_run transforms.util/localize-run-timestamps))+ (map python-source-table-ref->table-id))(t2/hydrate transforms :last_run :transform_tag_ids :creator))));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest@@ -144,7 +157,7 @@;; Return with hydrated tag_ids(t2/hydrate transform :transform_tag_ids :creator)))](events/publish-event! :event/transform-create {:object transform :user-id api/*current-user-id*})- transform))+ (python-source-table-ref->table-id transform)))(defn get-transform"Get a specific transform."@@ -155,7 +168,8 @@(-> transform(t2/hydrate :last_run :transform_tag_ids :creator)(u/update-some :last_run transforms.util/localize-run-timestamps)- (assoc :table target-table))))+ (assoc :table target-table)+ python-source-table-ref->table-id)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -181,7 +195,7 @@global-ordering (transforms.ordering/transform-ordering (vals id->transform))dep-ids (get global-ordering id)dependencies (map id->transform dep-ids)]- (t2/hydrate dependencies :creator)))+ (mapv python-source-table-ref->table-id (t2/hydrate dependencies :creator))));; TODO (Cam 10/28/25) -- fix this endpoint so it uses kebab-case for query parameters for consistency with the rest;; of the REST API@@ -250,7 +264,7 @@(transform.model/update-transform-tags! id (:tag_ids body)))(t2/hydrate (t2/select-one :model/Transform id) :transform_tag_ids :creator))](events/publish-event! :event/transform-update {:object transform :user-id api/*current-user-id*})- transform))+ (python-source-table-ref->table-id transform)));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/enterprise/backend/src/metabase_enterprise/transforms/interface.clj b/enterprise/backend/src/metabase_enterprise/transforms/interface.cljindex 735d41567bf..1adcfd63cf6 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/interface.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/interface.clj@@ -47,12 +47,16 @@The transform execution system uses these dependencies to determine the correct order of executionand to detect circular dependencies.- Each dependency is represented as either:+ Each dependency is represented as one of:- `{:table <table-id>}`A dependency on a table that exists and has been synced.- `{:transform <transform-id>}`A dependency on a table that does not yet exist, but is known to be the target of another transform.Represents a 'placeholder' table (as we no table id / metadata) for the same purposes.+ - `{:table-ref {:database_id <db-id> :schema <schema> :table <name>}}`+ A dependency on a table by name, for cases where the table_id may not exist yet (e.g., when+ bulk importing transforms that depend on each other's outputs). The ordering system will+ resolve these to transforms by matching against target table definitions.An empty set indicates no dependencies."{:added "0.57.0" :arglists '([transform])}diff --git a/enterprise/backend/src/metabase_enterprise/transforms/models/transform.clj b/enterprise/backend/src/metabase_enterprise/transforms/models/transform.cljindex 6d79c3bb8c0..69ad10d762d 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/models/transform.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/models/transform.clj@@ -30,16 +30,23 @@(derive ::mi/read-policy.superuser)(derive ::mi/write-policy.superuser))+(defn- keywordize-source-table-refs+ "Keywordize keys in source-tables map values (refs are maps, ints pass through)."+ [source-tables]+ (update-vals source-tables #(if (map? %) (update-keys % keyword) %)))+(defn- transform-source-out [m](-> mmi/json-out-without-keywordization(update-keys keyword)+ (m/update-existing :source-tables keywordize-source-table-refs)(m/update-existing :query lib-be/normalize-query)(m/update-existing :type keyword)(m/update-existing :source-incremental-strategy #(update-keys % keyword))))(defn- transform-source-in [m](-> m+ (m/update-existing :source-tables transforms.util/normalize-source-tables)(m/update-existing :query (comp lib/prepare-for-serialization lib-be/normalize-query))mi/json-in))diff --git a/enterprise/backend/src/metabase_enterprise/transforms/ordering.clj b/enterprise/backend/src/metabase_enterprise/transforms/ordering.cljindex 900256f3194..57491a75879 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/ordering.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/ordering.clj@@ -50,6 +50,24 @@[output-table (:id transform)])))transforms)))+(defn- target-ref-map+ "Build a map from [database_id schema table_name] -> transform_id for all transforms."+ [transforms]+ (into {}+ (map (fn [{:keys [id target]}]+ [[(:database target) (:schema target) (:name target)] id]))+ transforms))++(defn- resolve-dependency+ "Resolve a single dependency to a transform id, or nil if not resolvable.+ Used to map table/transform/table-ref dependencies to actual transform ids."+ [{:keys [table transform table-ref]} output-tables transform-ids target-refs]+ (or (output-tables table)+ (transform-ids transform)+ (when table-ref+ (let [{:keys [database_id schema table]} table-ref]+ (target-refs [database_id schema table])))))+(defn transform-ordering"Computes an 'ordering' of a given list of transforms.@@ -63,19 +81,19 @@(let [db-id (transforms.i/target-db-id transform)]{db-id [transform]})))(apply merge-with into))- transform-ids (into #{} (map :id) transforms)- {:keys [output-tables dependencies]} (->> transforms-by-db- (map (mu/fn [[db-id db-transforms] :- [:tuple- [:maybe ::lib.schema.id/database]- [:maybe [:sequential :any]]]]- (let [mp (lib-be/application-database-metadata-provider db-id)]- {:output-tables (output-table-map mp db-transforms)- :dependencies (dependency-map db-transforms)})))- (apply merge-with merge))]+ transform-ids (into #{} (map :id) transforms)+ target-refs (target-ref-map transforms)+ {:keys [output-tables+ dependencies]} (->> transforms-by-db+ (map (mu/fn [[db-id db-transforms] :- [:tuple+ [:maybe ::lib.schema.id/database]+ [:maybe [:sequential :any]]]]+ (let [mp (lib-be/application-database-metadata-provider db-id)]+ {:output-tables (output-table-map mp db-transforms)+ :dependencies (dependency-map db-transforms)})))+ (apply merge-with merge))](update-vals dependencies #(into #{}- (keep (fn [{:keys [table transform]}]- (or (output-tables table)- (transform-ids transform))))+ (keep (fn [dep] (resolve-dependency dep output-tables transform-ids target-refs)))%))))(defn find-cycle@@ -125,9 +143,9 @@db-transforms (filter #(= (get-in % [:source :query :database]) db-id) transforms)output-tables (output-table-map mp db-transforms)transform-ids (into #{} (map :id) db-transforms)- node->children #(->> % transforms-by-id transforms.i/table-dependencies (keep (fn [{:keys [table transform]}]- (or (output-tables table)- (transform-ids transform)))))+ target-refs (target-ref-map transforms)+ node->children #(->> % transforms-by-id transforms.i/table-dependencies+ (keep (fn [dep] (resolve-dependency dep output-tables transform-ids target-refs))))id->name (comp :name transforms-by-id)cycle (find-cycle node->children [transform-id])](when cyclediff --git a/enterprise/backend/src/metabase_enterprise/transforms/schema.clj b/enterprise/backend/src/metabase_enterprise/transforms/schema.cljindex 272d6485cc1..a0360a8d7a7 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/schema.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/schema.clj@@ -5,6 +5,19 @@[metabase.util.malli.registry :as mr][metabase.util.malli.schema :as ms]))+(mr/def ::source-table-ref+ "A reference to a source table by name, for cases where table_id may not exist yet.+ Also saves querying metadata in situations where we'll need the name."+ [:map+ [:database_id :int]+ [:schema {:optional true} [:maybe :string]]+ [:table :string]+ [:table_id {:optional true} [:maybe :int]]])++(mr/def ::source-table-value+ "Either a table ID (int) or a reference map."+ [:or :int ::source-table-ref])+(mr/def ::checkpoint-strategy[:map[:type [:= "checkpoint"]]@@ -29,7 +42,7 @@[:map[:source-database {:optional true} :int];; NB: if source is checkpoint, only one table allowed- [:source-tables [:map-of :string :int]]+ [:source-tables [:map-of :string ::source-table-value]][:type [:= "python"]][:body :string][:source-incremental-strategy {:optional true} ::source-incremental-strategy]]]])diff --git a/enterprise/backend/src/metabase_enterprise/transforms/util.clj b/enterprise/backend/src/metabase_enterprise/transforms/util.cljindex f4f57043132..3330f45d294 100644--- a/enterprise/backend/src/metabase_enterprise/transforms/util.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms/util.clj@@ -433,6 +433,95 @@(some->> (:router-database-id db-or-id)(t2/exists? :model/DatabaseRouter :database_id))))+;;; ------------------------------------------------- Source Table Resolution -----------------------------------------++(def ^:private ^:const batch-lookup-chunk-size+ "Maximum number of table refs to query at once to avoid SQL query size limits."+ 100)++(defn batch-lookup-table-ids+ "Batch lookup table IDs from ref maps. Returns {[db_id schema name] -> table_id}.+ Queries the exact conjunction of each [database_id, schema, table] triple rather than+ a Cartesian product of all values. Uses chunking to avoid query size limits."+ [refs]+ (when (seq refs)+ (let [unique-refs (distinct (map (juxt :database_id :schema :table) refs))+ ref->clause (fn [[db-id schema table-name]]+ [:and+ [:= :db_id db-id]+ (if (some? schema)+ [:= :schema schema]+ [:is :schema nil])+ [:= :name table-name]])+ fetch-batch (fn [batch]+ (t2/select-fn->fn (juxt :db_id :schema :name) :id+ [:model/Table :id :db_id :schema :name]+ {:where (into [:or] (map ref->clause batch))}))]+ (into {} (mapcat fetch-batch) (partition-all batch-lookup-chunk-size unique-refs)))))++(defn- source-table-ref->key+ "Convert a source table ref map to a lookup key [db_id schema name]."+ [{:keys [database_id schema table]}]+ [database_id schema table])++(defn- missing-table-id?+ "Returns true if `v` is a source table ref map that needs table_id lookup."+ [v]+ (and (map? v) (nil? (:table_id v))))++(defn normalize-source-tables+ "Normalize source-tables to consistent map format {:database_id :schema :table :table_id}.++ The old format stored just integer table IDs. New transforms store maps on write.+ Old data is converted on read via transform-source-out for backwards compatibility.++ Throws if an integer table ID references a non-existent table.+ Map refs with non-existent tables get nil table_id (resolved later at execute time)."+ [source-tables]+ (let [int-table-ids (into #{} (filter int?) (vals source-tables))+ int-id->metadata (when (seq int-table-ids)+ (t2/select-pk->fn (fn [{:keys [db_id schema name]}]+ {:database_id db_id :schema schema :table name})+ [:model/Table :id :db_id :schema :name]+ :id [:in int-table-ids]))+ missing-ids (when (seq int-table-ids)+ (remove int-id->metadata int-table-ids))+ refs-needing-id (filter missing-table-id? (vals source-tables))+ ref-lookup (or (batch-lookup-table-ids refs-needing-id) {})]+ (when (seq missing-ids)+ (throw (ex-info (str "Tables not found for ids: " (str/join ", " (sort missing-ids)))+ {:table_ids (vec missing-ids)})))+ (update-vals source-tables+ (fn [v]+ (cond+ (int? v) (assoc (int-id->metadata v) :table_id v)+ (:table_id v) v+ :else (assoc v :table_id (ref-lookup (source-table-ref->key v))))))))++(defn resolve-source-tables+ "Resolve source-tables to {alias -> table_id}. Throws if any table not found.+ For execute time - all entries must resolve to valid table IDs.+ Handles both integer IDs (old format) and map refs (new format)."+ [source-tables]+ (let [needs-lookup (filter missing-table-id? (vals source-tables))+ lookup (or (batch-lookup-table-ids needs-lookup) {})+ resolved (u/for-map [[alias v] source-tables]+ [alias (if (int? v)+ v+ (or (:table_id v) (lookup (source-table-ref->key v))))])+ unresolved (for [[alias table-id] resolved+ :when (nil? table-id)+ :let [v (get source-tables alias)]]+ {:alias alias+ :table (if-let [schema (:schema v)]+ (str schema "." (:table v))+ (:table v))+ :ref v})]+ (when (seq unresolved)+ (throw (ex-info (str "Tables not found: " (str/join ", " (map :table unresolved)))+ {:unresolved unresolved})))+ resolved))+(defn- matching-timestamp?[job field-path {:keys [start end]}](when-let [field-instant (->instant (get-in job field-path))]diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.cljindex cabcd70d5da..ac286381bd5 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj@@ -271,71 +271,73 @@(python-runner/cancel-python-code-http-call! server-url run-id))))(defn- run-python-transform! [{:keys [source] :as transform} db run-id cancel-chan message-log]- ;; TODO restructure things such that s3 can we swapped out for other transfer mechanisms- (with-open [^Closeable log-future-ref- (if (app-db/in-transaction?)- ;; if in a transaction (such as under mt/with-temp), it is not safe to poll for logs (close race / contention)- ;; tests that want to test async log behaviour should opt out of thread-local test helpers- (reify Closeable (close [_]))- (open-python-message-update-future! run-id message-log))- shared-storage-ref (s3/open-shared-storage! (:source-tables source))]- (let [driver (:engine db)- server-url (transforms-python.settings/python-runner-url)- _ (python-runner/copy-tables-to-s3! {:run-id run-id- :shared-storage @shared-storage-ref- :source source- :cancel-chan cancel-chan- :limit (:limit source)- :transform-id (:id transform)})- _ (start-cancellation-process! server-url run-id cancel-chan) ; inherits lifetime of cancel-chan- {:keys [status body] :as response}- (python-runner/execute-python-code-http-call!- {:server-url server-url- :code (:body source)- :run-id run-id- :table-name->id (:source-tables source)- :shared-storage @shared-storage-ref})-- output-manifest (python-runner/read-output-manifest @shared-storage-ref)- events (python-runner/read-events @shared-storage-ref)]- (.close ^Closeable log-future-ref) ; early close to force any writes to flush- (replace-python-logs! message-log events)- (if (not= 200 status)- (do- (when (:timeout body)- (transforms/timeout-run! run-id))- (throw (ex-info "Python runner call failed"- {:transform-message (i18n/tru "Python execution failure (exit code {0})" (:exit_code body "?"))- :status-code 400- :api-status-code status- :body body- :events events})))- (try- (let [temp-path (Files/createTempFile "transform-output-" ".jsonl" (u/varargs FileAttribute))- temp-file (.toFile temp-path)]- (when-not (seq (:fields output-manifest))- (throw (ex-info "No fields in metadata"- {:metadata output-manifest- :raw-body body- :events events})))- (try- (with-open [in (python-runner/open-output @shared-storage-ref)]- (io/copy in temp-file))- (let [file-size (.length temp-file)]- (transforms.instrumentation/with-stage-timing [run-id [:import :file-to-dwh]]- (transfer-file-to-db driver db transform output-manifest temp-file))- (transforms.instrumentation/record-data-transfer! run-id :file-to-dwh file-size nil))- (finally- (.delete temp-file))))- response- (catch Exception e- (log/error e "Failed to to create resulting table")- (throw (ex-info "Failed to create the resulting table"- {:transform-message (or (:transform-message (ex-data e))+ ;; Resolve name-based source table refs to table IDs (throws if any not found)+ (let [resolved-source-tables (transforms.util/resolve-source-tables (:source-tables source))]+ ;; TODO restructure things such that s3 can we swapped out for other transfer mechanisms+ (with-open [^Closeable log-future-ref+ (if (app-db/in-transaction?)+ ;; if in a transaction (such as under mt/with-temp), it is not safe to poll for logs (close race / contention)+ ;; tests that want to test async log behaviour should opt out of thread-local test helpers+ (reify Closeable (close [_]))+ (open-python-message-update-future! run-id message-log))+ shared-storage-ref (s3/open-shared-storage! resolved-source-tables)]+ (let [driver (:engine db)+ server-url (transforms-python.settings/python-runner-url)+ _ (python-runner/copy-tables-to-s3! {:run-id run-id+ :shared-storage @shared-storage-ref+ :source (assoc source :source-tables resolved-source-tables)+ :cancel-chan cancel-chan+ :limit (:limit source)+ :transform-id (:id transform)})+ _ (start-cancellation-process! server-url run-id cancel-chan) ; inherits lifetime of cancel-chan+ {:keys [status body] :as response}+ (python-runner/execute-python-code-http-call!+ {:server-url server-url+ :code (:body source)+ :run-id run-id+ :table-name->id resolved-source-tables+ :shared-storage @shared-storage-ref})++ output-manifest (python-runner/read-output-manifest @shared-storage-ref)+ events (python-runner/read-events @shared-storage-ref)]+ (.close ^Closeable log-future-ref) ; early close to force any writes to flush+ (replace-python-logs! message-log events)+ (if (not= 200 status)+ (do+ (when (:timeout body)+ (transforms/timeout-run! run-id))+ (throw (ex-info "Python runner call failed"+ {:transform-message (i18n/tru "Python execution failure (exit code {0})" (:exit_code body "?"))+ :status-code 400+ :api-status-code status+ :body body+ :events events})))+ (try+ (let [temp-path (Files/createTempFile "transform-output-" ".jsonl" (u/varargs FileAttribute))+ temp-file (.toFile temp-path)]+ (when-not (seq (:fields output-manifest))+ (throw (ex-info "No fields in metadata"+ {:metadata output-manifest+ :raw-body body+ :events events})))+ (try+ (with-open [in (python-runner/open-output @shared-storage-ref)]+ (io/copy in temp-file))+ (let [file-size (.length temp-file)]+ (transforms.instrumentation/with-stage-timing [run-id [:import :file-to-dwh]]+ (transfer-file-to-db driver db transform output-manifest temp-file))+ (transforms.instrumentation/record-data-transfer! run-id :file-to-dwh file-size nil))+ (finally+ (.delete temp-file))))+ response+ (catch Exception e+ (log/error e "Failed to to create resulting table")+ (throw (ex-info "Failed to create the resulting table"+ {:transform-message (or (:transform-message (ex-data e));; TODO keeping messaging the same at this level;; should be more specific in underlying calls- (i18n/tru "Failed to create the resulting table"))}- e))))))))+ (i18n/tru "Failed to create the resulting table"))}+ e)))))))))(defn- exceptional-run-message [message-log ex](str/join "\n" (remove str/blank? [(message-log->transform-run-message message-log)diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/impl.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/impl.cljindex b427bd71fd0..95ea6214d50 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/impl.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/impl.clj@@ -17,8 +17,24 @@[transform options](transforms-python.execute/execute-python-transform! transform options))+(defn- source-table-value->dependency+ "Convert a source table value (int or ref map) to a dependency map."+ [v]+ (cond+ ;; Integer table ID - direct table dependency+ (int? v)+ {:table v}++ ;; Map with resolved table_id - direct table dependency+ (:table_id v)+ {:table (:table_id v)}++ ;; Map without table_id - return ref for ordering system to resolve+ :else+ {:table-ref (select-keys v [:database_id :schema :table])}))+(defmethod transforms.i/table-dependencies :python[transform](into #{}- (map #(hash-map :table %))+ (map source-table-value->dependency)(vals (get-in transform [:source :source-tables]))))diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.cljindex c7c97850881..d20adcda0dc 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/python_runner.clj@@ -289,9 +289,9 @@(when (and (:source-incremental-strategy source)(> (count (:source-tables source)) 1))(throw (ex-info "Incremental transforms for python only supports one source table" {})))- ;; TODO there's scope for some parallelism here, in particular across different databases- (doseq [[table-name table-id] (:source-tables source)- :let [{:keys [s3-client bucket-name objects]} shared-storage+ (doseq [[table-name v] (:source-tables source)+ :let [table-id (if (int? v) v (:table_id v))+ {:keys [s3-client bucket-name objects]} shared-storage{data-path :path} (get objects [:table table-id :data]){manifest-path :path} (get objects [:table table-id :manifest])]](let [tmp-data-file (File/createTempFile data-path "")diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.cljindex 226c3297e11..16654d517cf 100644--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/table_utils_test.clj@@ -224,9 +224,9 @@(testing "returns tables with correct structure for valid table-ids"(mt/with-current-user (mt/user->id :crowberto)- (is (= [{:id table1-id :name "users" :schema "public"}- {:id table3-id :name "products" :schema "inventory"}]- (table-utils/used-tables-from-ids db-id [table1-id table3-id])))))+ (is (= #{{:id table1-id :name "users" :schema "public"}+ {:id table3-id :name "products" :schema "inventory"}}+ (set (table-utils/used-tables-from-ids db-id [table1-id table3-id]))))))(testing "handles empty table-ids collection"(mt/with-current-user (mt/user->id :crowberto)@@ -255,9 +255,9 @@(testing "handles mix of valid and invalid table-ids"(mt/with-current-user (mt/user->id :crowberto)(let [fake-id 999999]- (is (= [{:id table1-id :name "users" :schema "public"}- {:id table2-id :name "orders" :schema "public"}]- (table-utils/used-tables-from-ids db-id [table1-id fake-id table2-id])))))))))+ (is (= #{{:id table1-id :name "users" :schema "public"}+ {:id table2-id :name "orders" :schema "public"}}+ (set (table-utils/used-tables-from-ids db-id [table1-id fake-id table2-id]))))))))));; ======================================;; Edge Cases and Error Handlingdiff --git a/enterprise/backend/test/metabase_enterprise/transforms/models_test.clj b/enterprise/backend/test/metabase_enterprise/transforms/models_test.cljindex 35368a13add..273453db6cc 100644--- a/enterprise/backend/test/metabase_enterprise/transforms/models_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms/models_test.clj@@ -273,6 +273,61 @@(:creator (second hydrated)))"Second hydrated should match the second user's data")))))))+(deftest python-transform-source-table-resolution-on-save-test+ (testing "Python transform source-tables with name refs get table_id resolved on save"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id+ :name "existing_table"+ :schema "public"}]+ (testing "table_id is populated when table exists"+ (mt/with-temp [:model/Transform transform {:name "Transform with ref"+ :source {:type "python"+ :body "def transform(): pass"+ :source-tables {"input" {:database_id db-id+ :schema "public"+ :table "existing_table"}}}+ :target {:type "table"+ :schema "public"+ :name "output"+ :database db-id}}]+ (let [saved (t2/select-one :model/Transform :id (:id transform))+ source-table (get-in saved [:source :source-tables "input"])]+ (is (= table-id (:table_id source-table))+ "table_id should be resolved from database lookup"))))++ (testing "table_id remains nil when table doesn't exist"+ (mt/with-temp [:model/Transform transform {:name "Transform with missing ref"+ :source {:type "python"+ :body "def transform(): pass"+ :source-tables {"input" {:database_id db-id+ :schema "public"+ :table "nonexistent_table"}}}+ :target {:type "table"+ :schema "public"+ :name "output"+ :database db-id}}]+ (let [saved (t2/select-one :model/Transform :id (:id transform))+ source-table (get-in saved [:source :source-tables "input"])]+ (is (nil? (:table_id source-table))+ "table_id should be nil for non-existent table"))))++ (testing "existing table_id is preserved"+ (mt/with-temp [:model/Transform transform {:name "Transform with explicit table_id"+ :source {:type "python"+ :body "def transform(): pass"+ :source-tables {"input" {:database_id db-id+ :schema "public"+ :table "existing_table"+ :table_id 999}}}+ :target {:type "table"+ :schema "public"+ :name "output"+ :database db-id}}]+ (let [saved (t2/select-one :model/Transform :id (:id transform))+ source-table (get-in saved [:source :source-tables "input"])]+ (is (= 999 (:table_id source-table))+ "explicit table_id should be preserved")))))))+(deftest check-allowed-content-transforms(mt/with-premium-features #{:data-studio}(mt/with-temp [:model/Collection transforms {:name "Test Transforms" :namespace collection/transforms-ns}diff --git a/enterprise/backend/test/metabase_enterprise/transforms/ordering_test.clj b/enterprise/backend/test/metabase_enterprise/transforms/ordering_test.cljindex 138cd9598c6..f2a1cc03957 100644--- a/enterprise/backend/test/metabase_enterprise/transforms/ordering_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms/ordering_test.clj@@ -357,3 +357,66 @@(is (= {:cycle-str "transform_table_2 -> transform_table_1 -> transform_table_3",:cycle [t1 t3 t2]}(ordering/get-transform-cycle (t2/select-one :model/Transform :id t1))))))))++(defn- make-python-transform+ "Create a python transform definition with the given source-tables and target name."+ [source-tables target-name & [target-schema]]+ (let [default-schema "public"+ schema (or target-schema default-schema)]+ {:source {:type "python"+ :source-database (mt/id)+ :source-tables source-tables+ :body "df.write_output()"}+ :name (str "transform_" target-name)+ :target {:database (mt/id)+ :schema schema+ :name target-name+ :type "table"}}))++(deftest python-transform-table-ref-ordering-test+ (testing "Python transform with name-based source table ref resolves to producing transform"+ (mt/with-temp [;; Transform A produces table "intermediate_output"+ :model/Transform {t-a :id} (make-python-transform+ {"input" (mt/id :orders)}+ "intermediate_output")+ ;; Transform B references intermediate_output by name (table doesn't exist yet)+ :model/Transform {t-b :id} (make-python-transform+ {"source" {:database_id (mt/id)+ :schema "public"+ :table "intermediate_output"}}+ "final_output")]+ (testing "table-dependencies returns table-ref for unresolved name reference"+ (let [deps (transforms.i/table-dependencies (t2/select-one :model/Transform :id t-b))]+ (is (contains? deps {:table-ref {:database_id (mt/id)+ :schema "public"+ :table "intermediate_output"}}))))++ (testing "transform-ordering correctly resolves the dependency"+ (is (= {t-a #{}+ t-b #{t-a}}+ (ordering/transform-ordering (t2/select :model/Transform :id [:in [t-a t-b]]))))))))++(deftest python-transform-mixed-source-tables-test+ (testing "Python transform with mixed int and name-based refs"+ (mt/with-temp [:model/Transform {t-a :id} (make-python-transform+ {"input" (mt/id :orders)}+ "output_a")+ :model/Transform {t-b :id} (make-python-transform+ {;; Direct table reference (existing table)+ "existing" (mt/id :products)+ ;; Name-based reference (table doesn't exist yet)+ "from_transform" {:database_id (mt/id)+ :schema "public"+ :table "output_a"}}+ "output_b")]+ (testing "table-dependencies includes both types"+ (let [deps (transforms.i/table-dependencies (t2/select-one :model/Transform :id t-b))]+ (is (contains? deps {:table (mt/id :products)}))+ (is (contains? deps {:table-ref {:database_id (mt/id)+ :schema "public"+ :table "output_a"}}))))++ (testing "transform-ordering resolves both dependencies"+ (is (= {t-a #{}+ t-b #{t-a}}+ (ordering/transform-ordering (t2/select :model/Transform :id [:in [t-a t-b]]))))))))diff --git a/enterprise/backend/test/metabase_enterprise/transforms/util_test.clj b/enterprise/backend/test/metabase_enterprise/transforms/util_test.cljindex 4aa9a254d0d..db660e26203 100644--- a/enterprise/backend/test/metabase_enterprise/transforms/util_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms/util_test.clj@@ -108,3 +108,107 @@(catch Exception _e;; Ignore cleanup errorsnil)))))))))++;;; ------------------------------------------------- Source Table Resolution Tests ----------------------------------++(deftest batch-lookup-table-ids-test+ (testing "batch-lookup-table-ids looks up table IDs from ref maps"+ (mt/with-temp [:model/Database db {}+ :model/Table t1 {:db_id (:id db) :name "table_one" :schema nil}+ :model/Table t2 {:db_id (:id db) :name "table_two" :schema "my_schema"}]+ (testing "returns nil for empty input"+ (is (nil? (transforms.util/batch-lookup-table-ids [])))+ (is (nil? (transforms.util/batch-lookup-table-ids nil))))++ (testing "looks up table without schema"+ (let [refs [{:database_id (:id db) :schema nil :table "table_one"}]+ result (transforms.util/batch-lookup-table-ids refs)]+ (is (= {[(:id db) nil "table_one"] (:id t1)} result))))++ (testing "looks up table with schema"+ (let [refs [{:database_id (:id db) :schema "my_schema" :table "table_two"}]+ result (transforms.util/batch-lookup-table-ids refs)]+ (is (= {[(:id db) "my_schema" "table_two"] (:id t2)} result))))++ (testing "handles mixed refs with and without schema"+ (let [refs [{:database_id (:id db) :schema nil :table "table_one"}+ {:database_id (:id db) :schema "my_schema" :table "table_two"}]+ result (transforms.util/batch-lookup-table-ids refs)]+ (is (= {[(:id db) nil "table_one"] (:id t1)+ [(:id db) "my_schema" "table_two"] (:id t2)}+ result))))++ (testing "returns empty for non-existent table"+ (let [refs [{:database_id (:id db) :schema nil :table "nonexistent"}]+ result (transforms.util/batch-lookup-table-ids refs)]+ (is (= {} result)))))))++(deftest normalize-source-tables-test+ (testing "normalize-source-tables converts all entries to map format"+ (mt/with-temp [:model/Database db {}+ :model/Table t1 {:db_id (:id db) :name "existing_table" :schema nil}]+ (testing "converts integer table ID to map format"+ (let [result (transforms.util/normalize-source-tables {"t" (:id t1)})]+ (is (map? (get result "t")))+ (is (= (:id db) (get-in result ["t" :database_id])))+ (is (= "existing_table" (get-in result ["t" :table])))+ (is (= (:id t1) (get-in result ["t" :table_id])))))++ (testing "throws for non-existent integer table ID"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tables not found for ids: 999999"+ (transforms.util/normalize-source-tables {"t" 999999}))))++ (testing "populates table_id for existing table"+ (let [source-tables {"t" {:database_id (:id db) :schema nil :table "existing_table"}}+ result (transforms.util/normalize-source-tables source-tables)]+ (is (= (:id t1) (get-in result ["t" :table_id])))))++ (testing "preserves existing table_id"+ (let [source-tables {"t" {:database_id (:id db) :schema nil :table "existing_table" :table_id 999}}+ result (transforms.util/normalize-source-tables source-tables)]+ (is (= 999 (get-in result ["t" :table_id])))))++ (testing "leaves table_id nil for non-existent table ref"+ (let [source-tables {"t" {:database_id (:id db) :schema nil :table "nonexistent"}}+ result (transforms.util/normalize-source-tables source-tables)]+ (is (nil? (get-in result ["t" :table_id])))))++ (testing "handles mixed int and map entries"+ (let [source-tables {"t1" (:id t1)+ "t2" {:database_id (:id db) :schema nil :table "existing_table"}}+ result (transforms.util/normalize-source-tables source-tables)]+ (is (map? (get result "t1")))+ (is (= (:id t1) (get-in result ["t1" :table_id])))+ (is (= (:id t1) (get-in result ["t2" :table_id]))))))))++(deftest resolve-source-tables-test+ (testing "resolve-source-tables returns {alias -> table_id} map"+ (mt/with-temp [:model/Database db {}+ :model/Table t1 {:db_id (:id db) :name "table_one" :schema nil}+ :model/Table t2 {:db_id (:id db) :name "table_two" :schema nil}]+ (testing "passes through integer entries (old format)"+ (is (= {"t" 123} (transforms.util/resolve-source-tables {"t" 123}))))++ (testing "resolves map with table_id"+ (let [source-tables {"t" {:database_id (:id db) :schema nil :table "table_one" :table_id (:id t1)}}]+ (is (= {"t" (:id t1)} (transforms.util/resolve-source-tables source-tables)))))++ (testing "looks up table_id for map without it"+ (let [source-tables {"t" {:database_id (:id db) :schema nil :table "table_one"}}]+ (is (= {"t" (:id t1)} (transforms.util/resolve-source-tables source-tables)))))++ (testing "throws for non-existent table"+ (let [source-tables {"t" {:database_id (:id db) :schema nil :table "nonexistent"}}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tables not found: nonexistent"+ (transforms.util/resolve-source-tables source-tables)))))++ (testing "throws with schema in error message"+ (let [source-tables {"t" {:database_id (:id db) :schema "my_schema" :table "nonexistent"}}]+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Tables not found: my_schema\.nonexistent"+ (transforms.util/resolve-source-tables source-tables)))))++ (testing "handles mixed entries (old and new format)"+ (let [source-tables {"t1" (:id t1)+ "t2" {:database_id (:id db) :schema nil :table "table_two"}}]+ (is (= {"t1" (:id t1) "t2" (:id t2)}+ (transforms.util/resolve-source-tables source-tables))))))))diff --git a/enterprise/backend/test/metabase_enterprise/transforms_python/execute_test.clj b/enterprise/backend/test/metabase_enterprise/transforms_python/execute_test.cljindex b79f175b2d6..32e2dd833be 100644--- a/enterprise/backend/test/metabase_enterprise/transforms_python/execute_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms_python/execute_test.clj@@ -127,3 +127,45 @@(testing "Transform run should have timeout status"(is (= :timeout run-status)"Transform run status should be :timeout when Python script times out")))))))))))))++(deftest python-transform-unresolved-source-table-test+ (testing "Python transform execution throws when source table cannot be resolved"+ (mt/test-drivers #{:postgres}+ (mt/with-premium-features #{:transforms-python}+ (mt/dataset transforms-dataset/transforms-test+ (let [schema (t2/select-one-fn :schema :model/Table (mt/id :transforms_products))]+ (with-transform-cleanup! [target {:type "table"+ :schema schema+ :name "unresolved_test"}]+ (mt/with-temp [:model/Transform transform {:name "Transform with unresolved ref"+ :source {:type "python"+ :body "def transform(input): return input"+ :source-tables {"input" {:database_id (mt/id)+ :schema schema+ :table "nonexistent_table"}}}+ :target (assoc target :database (mt/id))}]+ (testing "Execution throws with informative error message"+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Tables not found:.*nonexistent_table"+ (transforms-python.execute/execute-python-transform! transform {:run-method :manual}))))))))))))++(deftest python-transform-unresolved-source-table-no-schema-test+ (testing "Python transform error message omits schema when nil"+ (mt/test-drivers #{:postgres}+ (mt/with-premium-features #{:transforms-python}+ (mt/dataset transforms-dataset/transforms-test+ (with-transform-cleanup! [target {:type "table"+ :schema nil+ :name "unresolved_no_schema_test"}]+ (mt/with-temp [:model/Transform transform {:name "Transform with unresolved ref no schema"+ :source {:type "python"+ :body "def transform(input): return input"+ :source-tables {"input" {:database_id (mt/id)+ :schema nil+ :table "missing_table"}}}+ :target (assoc target :database (mt/id))}]+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo+ #"Tables not found: missing_table"+ (transforms-python.execute/execute-python-transform! transform {:run-method :manual}))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/transforms_python/transforms_api_test.clj b/enterprise/backend/test/metabase_enterprise/transforms_python/transforms_api_test.cljindex c2bb5569334..665ba5e89d8 100644--- a/enterprise/backend/test/metabase_enterprise/transforms_python/transforms_api_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms_python/transforms_api_test.clj@@ -541,3 +541,31 @@(let [updated-rows (transforms.tu/table-rows table-name)](is (= [["Alice" "Bob"] ["Bob" "Alice"]] updated-rows)"Updated data should show Alice/Bob with friends instead of ages"))))))))))++(deftest create-python-transform-with-table-ref-source-test+ (testing "Creating a Python transform with name-based source table refs is allowed"+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)+ (mt/with-premium-features #{:transforms :transforms-python}+ (mt/dataset transforms-dataset/transforms-test+ (with-transform-cleanup! [target {:type "table"+ :schema (get-test-schema)+ :name "table_ref_test"}]+ (let [;; Use a name-based ref instead of table ID+ source-tables {"input" {:database_id (mt/id)+ :schema (get-test-schema)+ :table "transforms_products"}}+ transform-payload {:name "Transform with table ref"+ :source {:type "python"+ :body "def transform(input):\n return input"+ :source-tables source-tables}+ :target (assoc target :database (mt/id))}+ response (mt/user-http-request :crowberto :post 200 "ee/transform" transform-payload)]+ (testing "Transform is created successfully"+ (is (integer? (:id response)))+ (is (= "python" (:source_type response))))++ ;; currently not allowed and used on UI so we're still converting this back to integer+ #_(testing "Source tables are preserved in response"+ (is (map? (get-in response [:source :source-tables :input])))+ (is (= "transforms_products"+ (get-in response [:source :source-tables :input :table])))))))))))