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
Enable specifying a database for Athena (#62183)
Riley Thompsonb39d5925b0cf
diff --git a/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.cljindex bd77d61ed85..ce01a33d12d 100644--- a/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj+++ b/enterprise/backend/test/metabase_enterprise/database_routing/e2e_test.clj@@ -213,7 +213,7 @@(defmethod router-dataset-name :default [_driver] "db-router-data")-(doseq [driver [:redshift :databricks :athena :presto-jdbc]]+(doseq [driver [:redshift :databricks :presto-jdbc]](defmethod router-dataset-name driver [_driver] "db-routing-data"))(defmulti routed-dataset-name@@ -224,7 +224,7 @@(defmethod routed-dataset-name :default [_driver] "db-routed-data")-(doseq [driver [:redshift :databricks :athena :presto-jdbc]]+(doseq [driver [:redshift :databricks :presto-jdbc]](defmethod routed-dataset-name driver [_driver] "db-routing-data"))(deftest db-routing-e2e-test@@ -260,3 +260,47 @@(->> (mt/query t)(mt/process-query)(mt/formatted-rows [int str])))))))))))))))))++(deftest athena-region-bucket-routing-test+ (mt/test-driver :athena+ (mt/with-premium-features #{:database-routing}+ (binding [tx/*use-routing-details* true]+ (mt/dataset (mt/dataset-definition "db-routing-data"+ [["t_0"+ [{:field-name "f", :base-type :type/Text}]+ [["us-east-2-foo"]+ ["us-east-2-bar"]]]])+ (let [routed (mt/db)]+ (binding [tx/*use-routing-details* false]+ (mt/dataset (mt/dataset-definition "db-routing-data"+ [["t_0"+ [{:field-name "f", :base-type :type/Text}]+ [["us-east-1-foo"]+ ["us-east-1-bar"]]]])+ (let [router (mt/db)]+ (t2/update! :model/Database (u/the-id routed)+ {:details (assoc (:details routed)+ :dbname nil+ :s3_staging_dir (tx/db-test-env-var-or-throw :athena :s3-staging-dir-routing)+ :region (tx/db-test-env-var-or-throw :athena :region-routing))})+ (t2/update! :model/Database (u/the-id router)+ {:details (assoc (:details router)+ :dbname nil)})+ (let [router (t2/select-one :model/Database :id (u/the-id router))+ routed (t2/select-one :model/Database :id (u/the-id routed))]+ (sync/sync-database! router {:scan :schema})+ (sync/sync-database! routed {:scan :schema})+ (wire-routing {:parent router :children [routed]})+ (mt/with-temp [:model/DatabaseRouter _ {:database_id (u/the-id router)+ :user_attribute "db_name"}]+ (met/with-user-attributes! :rasta {"db_name" (:name routed)}+ (mt/with-current-user (mt/user->id :crowberto)+ (is (= [[1 "us-east-1-foo"] [2 "us-east-1-bar"]]+ (->> (mt/query t_0)+ (mt/process-query)+ (mt/formatted-rows [int str])))))+ (mt/with-current-user (mt/user->id :rasta)+ (is (= [[1 "us-east-2-foo"] [2 "us-east-2-bar"]]+ (->> (mt/query t_0)+ (mt/process-query)+ (mt/formatted-rows [int str])))))))))))))))))diff --git a/modules/drivers/athena/resources/metabase-plugin.yaml b/modules/drivers/athena/resources/metabase-plugin.yamlindex 14524936519..bb537ec3ee3 100644--- a/modules/drivers/athena/resources/metabase-plugin.yaml+++ b/modules/drivers/athena/resources/metabase-plugin.yaml@@ -36,6 +36,9 @@ driver:- name: secret_keydisplay-name: Secret keyhelper-text: Leave this empty to authorize using AWS Credentials Provider Chain (Instance Profiles or IAM Roles for Tasks)+ - name: dbname+ display-name: Specific database+ helper-text: Specify a single database to enable features like DB routing- advanced-options-start- merge:- additional-optionsdiff --git a/modules/drivers/athena/src/metabase/driver/athena.clj b/modules/drivers/athena/src/metabase/driver/athena.cljindex 5e35c8747f3..0c230bfa93d 100644--- a/modules/drivers/athena/src/metabase/driver/athena.clj+++ b/modules/drivers/athena/src/metabase/driver/athena.clj@@ -50,6 +50,10 @@:database-routing true}](defmethod driver/database-supports? [:athena feature] [_driver _feature _db] supported?))+(defmethod driver/database-supports? [:athena :schemas]+ [_driver _feature db]+ (not (seq (:dbname (:details db)))))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | metabase.driver.sql-jdbc method impls |;;; +----------------------------------------------------------------------------------------------------------------+@@ -64,7 +68,7 @@:else ".amazonaws.com"))(defmethod sql-jdbc.conn/connection-details->spec :athena- [_driver {:keys [region access_key secret_key s3_staging_dir workgroup catalog], :as details}]+ [_driver {:keys [region access_key secret_key s3_staging_dir workgroup catalog dbname], :as details}](-> (merge{:classname "com.amazon.athena.jdbc.AthenaDriver":subprotocol "athena"@@ -74,18 +78,17 @@:OutputLocation s3_staging_dir:WorkGroup workgroup:Region region}+ (when dbname+ {:database dbname})(when (and (not (driver-api/is-hosted?)) (str/blank? access_key)){:CredentialsProvider "DefaultChain"})(when-not (str/blank? catalog){:MetadataRetrievalMethod "ProxyAPI":Catalog catalog})(dissoc details- ;; `:metabase.driver.athena/schema` is just a gross hack for testing so we can treat multiple tests datasets as- ;; different DBs -- see [[metabase.driver.athena/fast-active-tables]]. Not used outside of tests. -- Cam- :db :catalog :metabase.driver.athena/schema- ;; Remove 2.x jdbc driver version options from details. Those are mapped to appropriate 3.x keys few- ;; on preceding lines- :region :access_key :secret_key :s3_staging_dir :workgroup))+ ;; Remove 2.x jdbc driver version options from details.+ ;; They are mapped to appropriate 3.x keys on preceding lines+ :db :dbname :catalog :region :access_key :secret_key :s3_staging_dir :workgroup))(sql-jdbc.common/handle-additional-options details, :seperator-style :semicolon)))(defmethod sql-jdbc.conn/data-source-name :athena@@ -415,25 +418,26 @@(defn describe-table-fields"Returns a set of column metadata for `schema` and `table-name` using `metadata`. "- [^DatabaseMetaData metadata database driver {^String schema :schema, ^String table-name :name} catalog]- (try- (let [columns (get-columns metadata catalog schema table-name)]- (when (empty? columns)- (log/trace "Falling back to DESCRIBE due to #43980"))- (if (or (table-has-nested-fields? columns)- ; If `.getColumns` returns an empty result, try to use DESCRIBE, which is slower- ; but doesn't suffer from the bug in the JDBC driver as metabase#43980- (empty? columns))- (describe-table-fields-with-nested-fields database schema table-name)- (describe-table-fields-without-nested-fields driver schema table-name columns)))- (catch Throwable e- (log/errorf e "Error retreiving fields for DB %s.%s" schema table-name)- (throw e))))+ [^DatabaseMetaData metadata database driver {^String schema :schema, ^String table-name :name} catalog dbname]+ (let [schema (or schema dbname)]+ (try+ (let [columns (get-columns metadata catalog schema table-name)]+ (when (empty? columns)+ (log/trace "Falling back to DESCRIBE due to #43980"))+ (if (or (table-has-nested-fields? columns)+ ; If `.getColumns` returns an empty result, try to use DESCRIBE, which is slower+ ; but doesn't suffer from the bug in the JDBC driver as metabase#43980+ (empty? columns))+ (describe-table-fields-with-nested-fields database schema table-name)+ (describe-table-fields-without-nested-fields driver schema table-name columns)))+ (catch Throwable e+ (log/errorf e "Error retreiving fields for DB %s.%s" schema table-name)+ (throw e)))));; Becuse describe-table-fields might fail, we catch the error here and return an empty set of columns(defmethod driver/describe-table :athena- [driver {{:keys [catalog]} :details, :as database} table]+ [driver {{:keys [catalog dbname]} :details, :as database} table](sql-jdbc.execute/do-with-connection-with-optionsdriverdatabase@@ -442,7 +446,7 @@(let [metadata (.getMetaData conn)](assoc (select-keys table [:name :schema]):fields (try- (describe-table-fields metadata database driver table catalog)+ (describe-table-fields metadata database driver table catalog dbname)(catch Throwable _(set nil))))))))(defn- get-tables@@ -479,36 +483,25 @@[columns rows])))))(defn- fast-active-tables- "Required because we're calling our own custom private get-tables method to support Athena.-- `:metabase.driver.athena/schema` is an icky hack that's in here to force it to only try to sync a single schema,- used by the tests when loading test data. We're not expecting users to specify it at this point in time. I'm not- really sure how this is really different than `catalog`, which they can specify -- in the future when we understand- Athena better maybe we can have a better way to do this -- Cam."- [driver ^DatabaseMetaData metadata {:keys [catalog], ::keys [schema]}]+ "Required because we're calling our own custom private get-tables method to support Athena."+ [driver ^DatabaseMetaData metadata {:keys [catalog dbname]}];; TODO: Catch errors here so a single exception doesn't fail the entire schema- ;;;; Also we're creating a set here, so even if we set "ProxyAPI", we'll miss dupe database names(with-open [rs (if catalog (.getSchemas metadata catalog "%") (.getSchemas metadata))];; it seems like `table_catalog` is ALWAYS `AwsDataCatalog`. `table_schem` seems to correspond to the Database name,;; at least for stuff we create with the test data extensions?? :thinking_face:(let [all-schemas (set (cond->> (jdbc/metadata-result rs)catalog (filter #(= (:table_catalog %) catalog))- schema (filter #(= (:table_schem %) schema))))+ dbname (filter #(= (:table_schem %) dbname))))schemas (set/difference all-schemas (sql-jdbc.sync/excluded-schemas driver))](set (for [schema schemastable (get-tables metadata (:table_schem schema) (:table_catalog schema))](let [remarks (:remarks table)]{:name (:table_name table)- :schema (:table_schem schema)+ :schema (when-not dbname (:table_schem schema)):description (when-not (str/blank? remarks)remarks)}))))))-;; You may want to exclude a specific database - this can be done here-; (defmethod sql-jdbc.sync/excluded-schemas :athena [_]-; #{"database_name"})--; If we want to limit the initial connection to a specific database/schema, I think we'd have to do that here...(defmethod driver/describe-database* :athena[driver {details :details, :as database}](sql-jdbc.execute/do-with-connection-with-optionsdiff --git a/modules/drivers/athena/test/metabase/driver/athena_test.clj b/modules/drivers/athena/test/metabase/driver/athena_test.cljindex f949f1aa7ba..c0c79a8b82d 100644--- a/modules/drivers/athena/test/metabase/driver/athena_test.clj+++ b/modules/drivers/athena/test/metabase/driver/athena_test.clj@@ -393,3 +393,47 @@first(zipmap units))))](qp-test.date-time-zone-functions-test/run-datetime-diff-time-zone-tests! diffs))))))++(deftest ^:parallel database-supports-schemas-test+ (doseq [[schemas-supported? details] [[true? {}]+ [true? {:dbname nil}]+ [true? {:dbname ""}]+ [false? {:dbname "db_name"}]]]+ (is (schemas-supported? (driver/database-supports? :athena :schemas {:details details})))))++(deftest ^:parallel athena-describe-database+ (mt/test-driver :athena+ (testing "when the dbname is specified describe-database only returns tables from that database and does not include the schema"+ (is (= {:tables #{{:name "users", :schema nil, :description nil}+ {:name "venues", :schema nil, :description nil}+ {:name "categories", :schema nil, :description nil}+ {:name "checkins", :schema nil, :description nil}+ {:name "orders", :schema nil, :description nil}+ {:name "people", :schema nil, :description nil}+ {:name "products", :schema nil, :description nil}+ {:name "reviews", :schema nil, :description nil}}}+ (driver/describe-database driver/*driver* (mt/db)))))+ (testing "when the dbname is not specified describe-database returns tables from all databases and does include the schema"+ (mt/with-temp [:model/Database db {:engine :athena,+ :details (dissoc (:details (mt/db)) :dbname)}]+ (let [tables (driver/describe-database driver/*driver* db)+ ;; athena CI has many (possibly changing) databases so we'll just filter for a few+ filter-dbs #{"v3_test_data" "airports" "db_router_data" "db_routed_data" "diff_time_zones_athena_cases"}+ filtered-tables {:tables (set (filter (comp filter-dbs :schema) (:tables tables)))}]+ (is (= {:tables #{{:name "venues", :schema "v3_test_data", :description nil}+ {:name "users", :schema "v3_test_data", :description nil}+ {:name "categories", :schema "v3_test_data", :description nil}+ {:name "people", :schema "v3_test_data", :description nil}+ {:name "reviews", :schema "v3_test_data", :description nil}+ {:name "checkins", :schema "v3_test_data", :description nil}+ {:name "products", :schema "v3_test_data", :description nil}+ {:name "orders", :schema "v3_test_data", :description nil}+ {:name "continent", :schema "airports", :description nil}+ {:name "country", :schema "airports", :description nil}+ {:name "region", :schema "airports", :description nil}+ {:name "airport", :schema "airports", :description nil}+ {:name "municipality", :schema "airports", :description nil}+ {:name "t", :schema "db_routed_data", :description nil}+ {:name "t", :schema "db_router_data", :description nil}+ {:name "times", :schema "diff_time_zones_athena_cases", :description nil}}}+ filtered-tables)))))))diff --git a/modules/drivers/athena/test/metabase/test/data/athena.clj b/modules/drivers/athena/test/metabase/test/data/athena.cljindex fc4dd249f9d..f48f74ec6bb 100644--- a/modules/drivers/athena/test/metabase/test/data/athena.clj+++ b/modules/drivers/athena/test/metabase/test/data/athena.clj@@ -43,19 +43,13 @@(defmethod tx/dbdef->connection-details :athena[driver _context {:keys [database-name], :as _dbdef}]- {:region (if tx/*use-routing-details*- (tx/db-test-env-var-or-throw :athena :region-routing)- (tx/db-test-env-var-or-throw :athena :region))+ {:region (tx/db-test-env-var-or-throw :athena :region):access_key (tx/db-test-env-var-or-throw :athena :access-key):secret_key (tx/db-test-env-var-or-throw :athena :secret-key)- :s3_staging_dir (if tx/*use-routing-details*- (tx/db-test-env-var-or-throw :athena :s3-staging-dir-routing)- (tx/db-test-env-var-or-throw :athena :s3-staging-dir))+ :s3_staging_dir (tx/db-test-env-var-or-throw :athena :s3-staging-dir)+ :dbname (some->> database-name (ddl.i/format-name driver)):catalog "AwsDataCatalog"- :workgroup "primary"- ;; HACK -- this is here so the Athena driver sync code only syncs the database in question -- see documentation- ;; for [[metabase.driver.athena/fast-active-tables]] for more information.- :metabase.driver.athena/schema (some->> database-name (ddl.i/format-name driver))})+ :workgroup "primary"});; TODO: We need a better way to have an isolated test environment for Athena;; If other tables exist, the tests start to query them for some reason,