Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Revoke schema-level grants when destroying Redshift workspace isolation (#78094)

Alexander Polyankin9c2758cc0d81
diff --git a/enterprise/backend/test/metabase_enterprise/workspaces/driver_isolation_test.clj b/enterprise/backend/test/metabase_enterprise/workspaces/driver_isolation_test.clj
index feb6407b690..4afc97080c1 100644
--- a/enterprise/backend/test/metabase_enterprise/workspaces/driver_isolation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/workspaces/driver_isolation_test.clj
@@ -1059,15 +1059,16 @@
:when (some? pw)]
(is (not (str/includes? text pw))
(str "workspace password leaked into exception text:\n" text)))
- ;; pgjdbc (and redshift's fork of it) echoes the aborted
- ;; statement in the batch exception message; requiring the
- ;; redaction marker proves this test reached the CREATE USER
- ;; echo rather than failing earlier and passing vacuously.
- ;; Only these two drivers get the database-level CREATE
- ;; grant that lets execution reach CREATE USER.
+ ;; init unwraps the JDBC batch envelope (which echoed the
+ ;; aborted CREATE USER statement) and rethrows the scrubbed
+ ;; server error. Requiring the create-role permission error
+ ;; proves this test reached CREATE USER rather than failing
+ ;; earlier and passing vacuously. Only these two drivers get
+ ;; the database-level CREATE grant that lets execution reach
+ ;; CREATE USER.
(when (#{:postgres :redshift} driver)
- (is (str/includes? text "****")
- (str "expected redacted CREATE USER echo in exception text:\n" text)))))))
+ (is (re-find #"(?i)permission denied|must be superuser|not authorized|privilege" text)
+ (str "expected the CREATE USER permission error in exception text:\n" text)))))))
(finally
;; If init for ws-b unexpectedly succeeded (isolation regression),
;; a user with a live password exists — tear it down too. Also
@@ -1129,3 +1130,31 @@
(catch Throwable t
(log/warnf t "destroy-workspace-isolation! failed for %s during password-reset test cleanup"
driver)))))))))
+
+(deftest ^:synchronized grant-failure-is-not-a-batch-envelope-test
+ ;; Every SQL-JDBC grant-workspace-read-access! impl batches its statements
+ ;; and rethrows the per-statement exception via `driver.u/batch-exception`,
+ ;; so a failed grant reads as the plain server error instead of "Batch entry
+ ;; N ... Call getNextException to see other errors in the batch."
+ (mt/test-drivers (filter #(isa? driver/hierarchy % :sql-jdbc) (mt/normal-drivers-with-feature :workspace))
+ (testing "a failed grant! surfaces the underlying server error, not a JDBC batch envelope"
+ (let [schema (case driver/*driver*
+ :postgres "public"
+ :h2 "PUBLIC"
+ "nonexistent_input_schema")
+ workspace {:id (rand-int Integer/MAX_VALUE)
+ :name "ws-grant-envelope"
+ :database_details {:user "mb_no_such_user_x1"
+ :role "mb_no_such_role_x1"}}
+ thrown (try
+ (driver/grant-workspace-read-access! driver/*driver* (mt/db) workspace [schema])
+ nil
+ (catch Throwable t t))]
+ (is (some? thrown)
+ "granting to a nonexistent user should have thrown")
+ (when thrown
+ (let [sql-ex (find-sql-exception thrown)]
+ (when sql-ex
+ (is (not (re-find #"Batch entry|getNextException" (str (ex-message sql-ex))))
+ (str "the JDBC batch envelope wording should not leak into the message:\n"
+ (ex-message sql-ex))))))))))
diff --git a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj
index c56a18aa28b..caa8344085d 100644
--- a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj
+++ b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj
@@ -551,6 +551,7 @@
(let [db-name (:schema workspace)
canonical-db (:db (driver.conn/effective-details database))
read-user (:database_details workspace)
+ escaped-password (sql.u/escape-sql (:password read-user) :ansi)
quoted-db (quote-schema db-name)
quoted-user (quote-field (:user read-user))
quoted-canonical-db (when-not (str/blank? canonical-db)
@@ -563,11 +564,11 @@
(with-open [stmt (.createStatement conn)]
(doseq [sql (cond-> [(format "CREATE DATABASE IF NOT EXISTS %s" quoted-db)
(format "CREATE USER IF NOT EXISTS %s IDENTIFIED BY '%s'"
- quoted-user (:password read-user))
+ quoted-user escaped-password)
;; the user may survive a failed teardown; without this it would keep
;; its old password while the new one gets persisted
(format "ALTER USER %s IDENTIFIED BY '%s'"
- quoted-user (:password read-user))
+ quoted-user escaped-password)
;; Least-privilege grant on the workspace's own DB (ClickHouse has no
;; owner auto-privileges, so grant each verb explicitly):
;; SELECT - read its own tables
@@ -584,7 +585,7 @@
(try
(.executeBatch ^Statement stmt)
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [(:password read-user)])))))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [(:password read-user) escaped-password])))))))
nil))
(defmethod driver/grant-workspace-read-access! :clickhouse
@@ -610,7 +611,10 @@
(with-open [stmt (.createStatement conn)]
(doseq [sql sqls]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt)))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))))
(defmethod driver/destroy-workspace-isolation! :clickhouse
[driver database workspace]
@@ -626,7 +630,10 @@
(format "DROP DATABASE IF EXISTS %s" quoted-db)
(format "DROP USER IF EXISTS %s" quoted-user)]]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
(defmethod driver/llm-sql-dialect-resource :clickhouse [_]
"metabot/prompts/dialects/clickhouse.md")
diff --git a/modules/drivers/redshift/src/metabase/driver/redshift.clj b/modules/drivers/redshift/src/metabase/driver/redshift.clj
index a3cc9b8ff6a..4664ac1b465 100644
--- a/modules/drivers/redshift/src/metabase/driver/redshift.clj
+++ b/modules/drivers/redshift/src/metabase/driver/redshift.clj
@@ -1003,14 +1003,15 @@
(defmethod driver/init-workspace-isolation! :redshift
[_driver database workspace]
- (let [schema-name (:schema workspace)
- read-user (:database_details workspace)
- quoted-schema (quote-schema schema-name)
- quoted-user (quote-field (:user read-user))]
+ (let [schema-name (:schema workspace)
+ read-user (:database_details workspace)
+ escaped-password (sql.u/escape-sql (:password read-user) :ansi)
+ quoted-schema (quote-schema schema-name)
+ quoted-user (quote-field (:user read-user))]
(jdbc/with-db-transaction [t-conn (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
(let [user-sql (if (user-exists? t-conn (:user read-user))
- (format "ALTER USER %s WITH PASSWORD '%s'" quoted-user (:password read-user))
- (format "CREATE USER %s WITH PASSWORD '%s'" quoted-user (:password read-user)))]
+ (format "ALTER USER %s WITH PASSWORD '%s'" quoted-user escaped-password)
+ (format "CREATE USER %s WITH PASSWORD '%s'" quoted-user escaped-password))]
(with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]
;; Schema-level grant only (Redshift's two schema privileges):
;; USAGE - access the schema
@@ -1025,7 +1026,7 @@
(try
(.executeBatch ^Statement stmt)
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [(:password read-user)])))))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [(:password read-user) escaped-password])))))))
nil))
(defmethod driver/grant-workspace-read-access! :redshift
@@ -1051,20 +1052,27 @@
(doseq [s source-schemas]
(assert-no-public-create-grant! check-conn s)
(assert-can-alter-default-privileges! check-conn s)))))
- ;; Grants run as auto-commit per statement so privileges are immediately
- ;; observable to a subsequent describe-database from a different connection.
- (doseq [s source-schemas
- :let [quoted-schema (quote-schema s)]
- sql [(format "GRANT USAGE ON SCHEMA %s TO %s" quoted-schema quoted-user)
- (format "REVOKE CREATE ON SCHEMA %s FROM %s" quoted-schema quoted-user)
- (format "REVOKE INSERT, UPDATE, DELETE, REFERENCES ON ALL TABLES IN SCHEMA %s FROM %s"
- quoted-schema quoted-user)
- ;; Schema-wide SELECT — workspace-scoped users receive whole-schema access.
- ;; Per-table granularity intentionally discarded (API contract is namespace-grained).
- (format "GRANT SELECT ON ALL TABLES IN SCHEMA %s TO %s" quoted-schema quoted-user)
- (format "ALTER DEFAULT PRIVILEGES IN SCHEMA %s GRANT SELECT ON TABLES TO %s"
- quoted-schema quoted-user)]]
- (jdbc/execute! spec [sql]))))
+ ;; Grants run as one batched transaction; it commits before this fn
+ ;; returns, so a subsequent describe-database from a different connection
+ ;; still observes the privileges.
+ (jdbc/with-db-transaction [t-conn spec]
+ (with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]
+ (doseq [s source-schemas
+ :let [quoted-schema (quote-schema s)]
+ sql [(format "GRANT USAGE ON SCHEMA %s TO %s" quoted-schema quoted-user)
+ (format "REVOKE CREATE ON SCHEMA %s FROM %s" quoted-schema quoted-user)
+ (format "REVOKE INSERT, UPDATE, DELETE, REFERENCES ON ALL TABLES IN SCHEMA %s FROM %s"
+ quoted-schema quoted-user)
+ ;; Schema-wide SELECT — workspace-scoped users receive whole-schema access.
+ ;; Per-table granularity intentionally discarded (API contract is namespace-grained).
+ (format "GRANT SELECT ON ALL TABLES IN SCHEMA %s TO %s" quoted-schema quoted-user)
+ (format "ALTER DEFAULT PRIVILEGES IN SCHEMA %s GRANT SELECT ON TABLES TO %s"
+ quoted-schema quoted-user)]]
+ (.addBatch ^Statement stmt ^String sql))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))
(defn- schema-exists?
"Check if a schema exists in Redshift."
@@ -1072,14 +1080,22 @@
(seq (jdbc/query conn ["SELECT 1 FROM pg_namespace WHERE nspname = ?" schema-name])))
(defn- schemas-with-user-grants
- "Query Redshift to find schemas where the user has been granted relation-level privileges.
- `svv_relation_privileges` only surfaces actual GRANTs on existing relations -- it does NOT
- list ALTER DEFAULT PRIVILEGES entries. See [[default-acl-grants-for-user]] for those."
+ "Query Redshift to find schemas where the user has been granted schema-level
+ (USAGE/CREATE) or relation-level privileges. Both views are needed:
+ `svv_relation_privileges` only surfaces GRANTs on existing relations, so a
+ granted schema with no tables (or whose tables were dropped later) only
+ shows up in `svv_schema_privileges` — missing it leaves a USAGE grant behind
+ and `DROP USER` then fails with `user ... has a privilege on some object`.
+ Neither view lists ALTER DEFAULT PRIVILEGES entries; see
+ [[default-acl-grants-for-user]] for those."
[conn username]
(->> (jdbc/query conn
["SELECT DISTINCT namespace_name FROM svv_relation_privileges
- WHERE identity_name = ? AND identity_type = 'user'"
- username])
+ WHERE identity_name = ? AND identity_type = 'user'
+ UNION
+ SELECT DISTINCT namespace_name FROM svv_schema_privileges
+ WHERE identity_name = ? AND identity_type = 'user'"
+ username username])
(keep :namespace_name)))
(defn- escape-like-pattern
@@ -1135,23 +1151,12 @@
quoted-user (quote-field username)
quoted-schema (quote-schema schema-name)
spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
- ;; Foreign-grantor default-priv REVOKEs run first, each in its own autocommit
- ;; statement. Redshift has no SAVEPOINT and aborts the entire transaction on
- ;; the first error, so these cannot share a transaction with the main cleanup
- ;; batch: one stale row (schema dropped between discovery and execution) would
- ;; otherwise poison DROP USER. Autocommit + per-statement catch is what
- ;; actually lets the rest proceed.
- (when (user-exists? spec username)
- (doseq [{:keys [grantor schema]} (default-acl-grants-for-user spec username)
- :let [sql (format "ALTER DEFAULT PRIVILEGES FOR USER %s IN SCHEMA %s REVOKE ALL ON TABLES FROM %s"
- (quote-field grantor) (quote-schema schema) quoted-user)]]
- (try
- (jdbc/execute! spec [sql])
- (catch Throwable t
- (log/warnf t "Failed to revoke default-priv (%s, %s) referencing iso-user %s; continuing"
- grantor schema username)))))
- ;; Main batch stays transactional: relation revokes, iso-schema bare REVOKE,
- ;; DROP SCHEMA, DROP USER -- the cleanup we want atomic.
+ ;; One transactional batch: foreign-grantor default-priv revokes, relation
+ ;; revokes, iso-schema bare REVOKE, DROP SCHEMA, DROP USER. Redshift has no
+ ;; SAVEPOINT and aborts the whole transaction on the first error, so a
+ ;; stale row (e.g. a schema dropped between discovery and execution) fails
+ ;; the entire destroy — that's fine: the workspace layer records the
+ ;; failure and the deprovision is retried, re-discovering fresh state.
(jdbc/with-db-transaction [t-conn spec]
(let [user-exists (user-exists? t-conn username)
schema-exists (schema-exists? t-conn schema-name)
@@ -1159,6 +1164,12 @@
(schemas-with-user-grants t-conn username))]
(with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]
(when user-exists
+ ;; Foreign-grantor default-priv rows must be revoked FOR USER their
+ ;; grantor before DROP USER (GHY-3709); Redshift has no DROP OWNED BY.
+ (doseq [{:keys [grantor schema]} (default-acl-grants-for-user t-conn username)]
+ (.addBatch ^Statement stmt
+ ^String (format "ALTER DEFAULT PRIVILEGES FOR USER %s IN SCHEMA %s REVOKE ALL ON TABLES FROM %s"
+ (quote-field grantor) (quote-schema schema) quoted-user)))
(doseq [schema granted-schemas
:let [quoted-granted-schema (quote-schema schema)]]
(.addBatch ^Statement stmt
@@ -1169,8 +1180,7 @@
quoted-granted-schema quoted-user)))
;; Iso-namespace default-priv was issued by the connection user at init time, so a
;; no-FOR-USER REVOKE is correct here. Guarded on schema existence to avoid
- ;; erroring on a schema that was dropped manually. Coverage for foreign-grantor
- ;; default-priv rows is handled above by the per-grantor autocommit loop.
+ ;; erroring on a schema that was dropped manually.
(when schema-exists
(.addBatch ^Statement stmt
^String (format "ALTER DEFAULT PRIVILEGES IN SCHEMA %s REVOKE ALL ON TABLES FROM %s"
@@ -1180,7 +1190,10 @@
^String (format "DROP SCHEMA IF EXISTS %s CASCADE" quoted-schema))
(.addBatch ^Statement stmt
^String (format "DROP USER IF EXISTS %s" quoted-user))
- (.executeBatch ^Statement stmt))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
(defmethod driver/llm-sql-dialect-resource :redshift [_]
"metabot/prompts/dialects/redshift.md")
diff --git a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
index 927fcb8a10f..a10f93a3429 100644
--- a/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
+++ b/modules/drivers/redshift/test/metabase/driver/redshift_test.clj
@@ -917,3 +917,35 @@
(try-execute! admin-spec (format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" schema))
(try-execute! admin-spec (format "DROP OWNED BY \"%s\"" grantor))
(try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" grantor)))))))
+
+(deftest ^:synchronized workspace-destroy-revokes-schema-only-grants-test
+ ;; `DROP USER` fails with `user ... cannot be dropped because the user has a
+ ;; privilege on some object` when the iso-user holds a schema-level USAGE
+ ;; grant on a schema with no relations: destroy used to discover schemas to
+ ;; revoke via `svv_relation_privileges` only, which cannot surface
+ ;; schema-level grants when the schema has no tables. The production grant
+ ;; path (`grant-workspace-read-access!`) issues `GRANT USAGE` per input
+ ;; schema, so any input schema without tables (or whose tables were dropped
+ ;; after provisioning) reproduces this.
+ (mt/test-driver :redshift
+ (let [admin-spec (sql-jdbc.conn/connection-details->spec :redshift (tx/dbdef->connection-details :redshift))
+ suffix (u/lower-case-en (mt/random-name))
+ schema (str "ws_empty_schema_" suffix)
+ workspace {:id (rand-int Integer/MAX_VALUE)
+ :name (str "wsd-dest-empty-" suffix)}]
+ (try
+ (execute! (format "CREATE SCHEMA \"%s\"" schema))
+ (let [workspace (merge workspace (driver/workspace-isolation-details :redshift (mt/db) workspace))
+ _ (driver/init-workspace-isolation! :redshift (mt/db) workspace)
+ iso-user (-> workspace :database_details :user)]
+ (try
+ (jdbc/execute! admin-spec [(format "GRANT USAGE ON SCHEMA \"%s\" TO \"%s\"" schema iso-user)])
+ (testing "destroy completes despite a schema-level-only grant on an empty schema"
+ (is (some? (driver/destroy-workspace-isolation! :redshift (mt/db) workspace))))
+ (testing "iso-user is gone from pg_user after destroy"
+ (is (empty? (jdbc/query admin-spec ["SELECT 1 FROM pg_user WHERE usename = ?" iso-user]))))
+ (finally
+ (try-execute! admin-spec (format "DROP OWNED BY \"%s\"" iso-user))
+ (try-execute! admin-spec (format "DROP USER IF EXISTS \"%s\"" iso-user)))))
+ (finally
+ (try-execute! admin-spec (format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" schema)))))))
diff --git a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
index ceae92dfac9..217ffbbc786 100644
--- a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
+++ b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj
@@ -43,7 +43,7 @@
(:import
(java.io File)
(java.net URI URLDecoder)
- (java.sql Connection DatabaseMetaData ResultSet ResultSetMetaData Types)
+ (java.sql Connection DatabaseMetaData ResultSet ResultSetMetaData Statement Types)
(java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)
(net.snowflake.client.api.exception SnowflakeSQLException)))
@@ -1177,14 +1177,14 @@
:use-password true)))
(defmethod driver/init-workspace-isolation! :snowflake
- [_driver database workspace]
+ [driver database workspace]
(let [details (driver.conn/effective-details database)
schema-name (:schema workspace)
db-name (:db details)
warehouse (:warehouse details)
role-name (-> workspace :database_details :role)
read-user (select-keys (:database_details workspace) [:user :password])
- conn-spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
+ escaped-password (sql.u/escape-sql (:password read-user) :ansi)]
(when-not db-name
(throw (ex-info (tru "Cannot initialize workspace. Snowflake connection details must include a ''db'' (database name). Set it in the database connection and retry.")
{:database-id (:id database) :step :init})))
@@ -1199,33 +1199,37 @@
quoted-user (quote-field (:user read-user))]
;; Snowflake RBAC: create schema -> create role -> grant privileges to role -> create user -> grant role to user
(try
- (doseq [sql [(format "CREATE SCHEMA IF NOT EXISTS %s" qualified-schema)
- (format "CREATE ROLE IF NOT EXISTS %s" quoted-role)
- (format "GRANT USAGE ON DATABASE %s TO ROLE %s" quoted-db quoted-role)
- (format "GRANT USAGE ON WAREHOUSE %s TO ROLE %s" quoted-warehouse quoted-role)
- (format "GRANT USAGE ON SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
- (format "GRANT ALL PRIVILEGES ON SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
- (format "GRANT ALL ON FUTURE TABLES IN SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
- (format "CREATE USER IF NOT EXISTS %s PASSWORD = '%s' MUST_CHANGE_PASSWORD = FALSE DEFAULT_ROLE = %s"
- quoted-user (:password read-user) quoted-role)
- ;; the user may survive a failed teardown; without this it would keep
- ;; its old password while the new one gets persisted
- (format "ALTER USER %s SET PASSWORD = '%s'"
- quoted-user (:password read-user))
- (format "GRANT ROLE %s TO USER %s" quoted-role quoted-user)]]
- (jdbc/execute! conn-spec [sql]))
+ (sql-jdbc.execute/do-with-connection-with-options
+ driver database {:write? true}
+ (fn [^Connection conn]
+ (with-open [^Statement stmt (.createStatement conn)]
+ (doseq [sql [(format "CREATE SCHEMA IF NOT EXISTS %s" qualified-schema)
+ (format "CREATE ROLE IF NOT EXISTS %s" quoted-role)
+ (format "GRANT USAGE ON DATABASE %s TO ROLE %s" quoted-db quoted-role)
+ (format "GRANT USAGE ON WAREHOUSE %s TO ROLE %s" quoted-warehouse quoted-role)
+ (format "GRANT USAGE ON SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
+ (format "GRANT ALL PRIVILEGES ON SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
+ (format "GRANT ALL ON FUTURE TABLES IN SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
+ (format "CREATE USER IF NOT EXISTS %s PASSWORD = '%s' MUST_CHANGE_PASSWORD = FALSE DEFAULT_ROLE = %s"
+ quoted-user escaped-password quoted-role)
+ ;; the user may survive a failed teardown; without this it would keep
+ ;; its old password while the new one gets persisted
+ (format "ALTER USER %s SET PASSWORD = '%s'"
+ quoted-user escaped-password)
+ (format "GRANT ROLE %s TO USER %s" quoted-role quoted-user)]]
+ (.addBatch ^Statement stmt ^String sql))
+ (.executeBatch ^Statement stmt))))
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [(:password read-user)])))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [(:password read-user) escaped-password])))))
nil))
(defmethod driver/destroy-workspace-isolation! :snowflake
- [_driver database workspace]
+ [driver database workspace]
(let [details (driver.conn/effective-details database)
schema-name (:schema workspace)
db-name (:db details)
role-name (-> workspace :database_details :role)
- username (-> workspace :database_details :user)
- conn-spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
+ username (-> workspace :database_details :user)]
(when-not db-name
(throw (ex-info (tru "Cannot destroy workspace. Snowflake connection details must include a ''db'' (database name). Set it in the database connection and retry.")
{:database-id (:id database) :step :destroy})))
@@ -1233,15 +1237,22 @@
quoted-user (quote-field username)
quoted-role (quote-field role-name)]
;; Drop in reverse order of creation: schema (CASCADE handles tables) -> user -> role
- (doseq [sql [(format "DROP SCHEMA IF EXISTS %s CASCADE" qualified-schema)
- (format "DROP USER IF EXISTS %s" quoted-user)
- (format "DROP ROLE IF EXISTS %s" quoted-role)]]
- (jdbc/execute! conn-spec [sql])))))
+ (sql-jdbc.execute/do-with-connection-with-options
+ driver database {:write? true}
+ (fn [^Connection conn]
+ (with-open [^Statement stmt (.createStatement conn)]
+ (doseq [sql [(format "DROP SCHEMA IF EXISTS %s CASCADE" qualified-schema)
+ (format "DROP USER IF EXISTS %s" quoted-user)
+ (format "DROP ROLE IF EXISTS %s" quoted-role)]]
+ (.addBatch ^Statement stmt ^String sql))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))))
(defmethod driver/grant-workspace-read-access! :snowflake
- [_driver database workspace schemas]
- (let [conn-spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))
- db-name (:db (driver.conn/effective-details database))
+ [driver database workspace schemas]
+ (let [db-name (:db (driver.conn/effective-details database))
role-name (-> workspace :database_details :role)]
(when-not role-name
(throw (ex-info (tru "Cannot grant workspace read access. Workspace details have no role — initialization may have failed. Re-run workspace initialization and retry.")
@@ -1257,15 +1268,24 @@
(doseq [schema schemas]
(when (str/blank? schema)
(throw (ex-info (tru "Cannot grant workspace read access. Input schema name is blank. Remove the blank entry from the workspace input schemas and retry.")
- {:database-id (:id database) :step :grant})))
- (let [qualified-schema (str quoted-db "." (quote-schema schema))]
- (doseq [sql [(format "GRANT USAGE ON DATABASE %s TO ROLE %s" quoted-db quoted-role)
- (format "GRANT USAGE ON SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
- (format "GRANT SELECT ON ALL TABLES IN SCHEMA %s TO ROLE %s"
- qualified-schema quoted-role)
- (format "GRANT SELECT ON FUTURE TABLES IN SCHEMA %s TO ROLE %s"
- qualified-schema quoted-role)]]
- (jdbc/execute! conn-spec [sql])))))))
+ {:database-id (:id database) :step :grant}))))
+ (sql-jdbc.execute/do-with-connection-with-options
+ driver database {:write? true}
+ (fn [^Connection conn]
+ (with-open [^Statement stmt (.createStatement conn)]
+ (doseq [schema schemas
+ :let [qualified-schema (str quoted-db "." (quote-schema schema))]
+ sql [(format "GRANT USAGE ON DATABASE %s TO ROLE %s" quoted-db quoted-role)
+ (format "GRANT USAGE ON SCHEMA %s TO ROLE %s" qualified-schema quoted-role)
+ (format "GRANT SELECT ON ALL TABLES IN SCHEMA %s TO ROLE %s"
+ qualified-schema quoted-role)
+ (format "GRANT SELECT ON FUTURE TABLES IN SCHEMA %s TO ROLE %s"
+ qualified-schema quoted-role)]]
+ (.addBatch ^Statement stmt ^String sql))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))))
(defmethod driver/llm-sql-dialect-resource :snowflake [_]
"metabot/prompts/dialects/snowflake.md")
diff --git a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
index a14b2116c0e..9201cbfb68f 100644
--- a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
+++ b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
@@ -38,7 +38,7 @@
[metabase.util.performance :as perf :refer [mapv get-in not-empty]]
[next.jdbc :as next.jdbc])
(:import
- (java.sql Connection DatabaseMetaData PreparedStatement ResultSet Time)
+ (java.sql Connection DatabaseMetaData PreparedStatement ResultSet Statement Time)
(java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)
(java.time.format DateTimeFormatter)
(java.util UUID)))
@@ -1165,7 +1165,7 @@
;;; +----------------------------------------------------------------------------------------------------------------+
(defmethod driver/init-workspace-isolation! :sqlserver
- [_driver database workspace]
+ [driver database workspace]
(let [schema-name (:schema workspace)
{:keys [user password]} (:database_details workspace)
username user
@@ -1173,67 +1173,79 @@
escaped-username (sql.u/escape-sql username :ansi)
escaped-schema (sql.u/escape-sql schema-name :ansi)
quoted-user (quote-field username)
- quoted-schema (quote-schema schema-name)
- conn-spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
+ quoted-schema (quote-schema schema-name)]
;; SQL Server: create login (server level), then user (database level), then schema
(try
- (doseq [sql [(format (str "IF NOT EXISTS (SELECT name FROM master.sys.server_principals WHERE name = '%s') "
- "CREATE LOGIN %s WITH PASSWORD = N'%s'")
- escaped-username quoted-user escaped-password)
- ;; the login may survive a failed teardown; without this it would keep
- ;; its old password while the new one gets persisted
- (format "ALTER LOGIN %s WITH PASSWORD = N'%s'" quoted-user escaped-password)
- (format "IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = '%s') CREATE USER %s FOR LOGIN %s"
- escaped-username quoted-user quoted-user)
- (format "IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = '%s') EXEC('CREATE SCHEMA %s')"
- escaped-schema quoted-schema)
- ;; Least-privilege grant on the workspace's own schema (vs. the old GRANT
- ;; CONTROL, dropping EXECUTE, VIEW DEFINITION, REFERENCES, and re-grant rights):
- ;; ALTER - create/drop/sp_rename objects in the schema
- ;; SELECT, INSERT, UPDATE, DELETE - full DML (SQL Server, unlike Postgres,
- ;; does not confer DML from ALTER/ownership, so grant it explicitly)
- (format "GRANT ALTER, SELECT, INSERT, UPDATE, DELETE ON SCHEMA::%s TO %s"
- quoted-schema quoted-user)
- ;; db-level CREATE TABLE: SELECT INTO (transform materialization) needs it too
- (format "GRANT CREATE TABLE TO %s" quoted-user)]]
- (jdbc/execute! conn-spec [sql]))
+ (sql-jdbc.execute/do-with-connection-with-options
+ driver database {:write? true}
+ (fn [^Connection conn]
+ (with-open [^Statement stmt (.createStatement conn)]
+ (doseq [sql [(format (str "IF NOT EXISTS (SELECT name FROM master.sys.server_principals WHERE name = '%s') "
+ "CREATE LOGIN %s WITH PASSWORD = N'%s'")
+ escaped-username quoted-user escaped-password)
+ ;; the login may survive a failed teardown; without this it would keep
+ ;; its old password while the new one gets persisted
+ (format "ALTER LOGIN %s WITH PASSWORD = N'%s'" quoted-user escaped-password)
+ (format "IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = '%s') CREATE USER %s FOR LOGIN %s"
+ escaped-username quoted-user quoted-user)
+ (format "IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = '%s') EXEC('CREATE SCHEMA %s')"
+ escaped-schema quoted-schema)
+ ;; Least-privilege grant on the workspace's own schema (vs. the old GRANT
+ ;; CONTROL, dropping EXECUTE, VIEW DEFINITION, REFERENCES, and re-grant rights):
+ ;; ALTER - create/drop/sp_rename objects in the schema
+ ;; SELECT, INSERT, UPDATE, DELETE - full DML (SQL Server, unlike Postgres,
+ ;; does not confer DML from ALTER/ownership, so grant it explicitly)
+ (format "GRANT ALTER, SELECT, INSERT, UPDATE, DELETE ON SCHEMA::%s TO %s"
+ quoted-schema quoted-user)
+ ;; db-level CREATE TABLE: SELECT INTO (transform materialization) needs it too
+ (format "GRANT CREATE TABLE TO %s" quoted-user)]]
+ (.addBatch ^Statement stmt ^String sql))
+ (.executeBatch ^Statement stmt))))
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [password escaped-password]))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [password escaped-password]))))
nil))
(defmethod driver/destroy-workspace-isolation! :sqlserver
- [_driver database workspace]
+ [driver database workspace]
(let [schema-name (:schema workspace)
username (-> workspace :database_details :user)
escaped-schema (sql.u/escape-sql schema-name :ansi)
escaped-username (sql.u/escape-sql username :ansi)
quoted-schema (quote-schema schema-name)
- quoted-user (quote-field username)
- conn-spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
- (doseq [sql [(format (str "DECLARE @sql NVARCHAR(MAX) = ''; "
- "SELECT @sql += 'DROP TABLE %s.[' + name + ']; ' "
- "FROM sys.tables WHERE schema_id = SCHEMA_ID('%s'); "
- "EXEC sp_executesql @sql")
- quoted-schema escaped-schema)
- (format "IF EXISTS (SELECT * FROM sys.schemas WHERE name = '%s') DROP SCHEMA %s"
- escaped-schema quoted-schema)
- (format "IF EXISTS (SELECT * FROM sys.database_principals WHERE name = '%s') DROP USER %s"
- escaped-username quoted-user)
- ;; Kill all sessions using this login before dropping it
- (format (str "DECLARE @sql NVARCHAR(MAX) = ''; "
- "SELECT @sql += 'KILL ' + CAST(session_id AS VARCHAR(10)) + '; ' "
- "FROM sys.dm_exec_sessions WHERE login_name = '%s'; "
- "EXEC sp_executesql @sql")
- escaped-username)
- (format "IF EXISTS (SELECT * FROM master.sys.server_principals WHERE name = '%s') DROP LOGIN %s"
- escaped-username quoted-user)]]
- (jdbc/execute! conn-spec [sql]))))
+ quoted-user (quote-field username)]
+ (sql-jdbc.execute/do-with-connection-with-options
+ driver database {:write? true}
+ (fn [^Connection conn]
+ (with-open [^Statement stmt (.createStatement conn)]
+ ;; mssql-jdbc runs the whole batch in one T-SQL scope, so DECLAREd
+ ;; variable names must be unique across the batch entries.
+ (doseq [sql [(format (str "DECLARE @drop_tables_sql NVARCHAR(MAX) = ''; "
+ "SELECT @drop_tables_sql += 'DROP TABLE %s.[' + name + ']; ' "
+ "FROM sys.tables WHERE schema_id = SCHEMA_ID('%s'); "
+ "EXEC sp_executesql @drop_tables_sql")
+ quoted-schema escaped-schema)
+ (format "IF EXISTS (SELECT * FROM sys.schemas WHERE name = '%s') DROP SCHEMA %s"
+ escaped-schema quoted-schema)
+ (format "IF EXISTS (SELECT * FROM sys.database_principals WHERE name = '%s') DROP USER %s"
+ escaped-username quoted-user)
+ ;; Kill all sessions using this login before dropping it
+ (format (str "DECLARE @kill_sessions_sql NVARCHAR(MAX) = ''; "
+ "SELECT @kill_sessions_sql += 'KILL ' + CAST(session_id AS VARCHAR(10)) + '; ' "
+ "FROM sys.dm_exec_sessions WHERE login_name = '%s'; "
+ "EXEC sp_executesql @kill_sessions_sql")
+ escaped-username)
+ (format "IF EXISTS (SELECT * FROM master.sys.server_principals WHERE name = '%s') DROP LOGIN %s"
+ escaped-username quoted-user)]]
+ (.addBatch ^Statement stmt ^String sql))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
(defmethod driver/grant-workspace-read-access! :sqlserver
- [_driver database workspace schemas]
- (let [conn-spec (sql-jdbc.conn/db->pooled-connection-spec (:id database))
- username (-> workspace :database_details :user)
- db-name (:db (:details database))]
+ [driver database workspace schemas]
+ (let [username (-> workspace :database_details :user)
+ db-name (:db (:details database))]
(when-not username
(throw (ex-info (tru "Cannot grant workspace read access. Workspace details have no read user — initialization may have failed. Re-run workspace initialization and retry.")
{:workspace-id (:id workspace) :step :grant})))
@@ -1246,11 +1258,20 @@
(doseq [schema schemas]
(when (str/blank? schema)
(throw (ex-info (tru "Cannot grant workspace read access. Input schema name is blank. Remove the blank entry from the workspace input schemas and retry.")
- {:database-id (:id database) :step :grant})))
- (jdbc/execute! conn-spec
- [(format "GRANT SELECT ON SCHEMA::%s TO %s"
- (quote-schema schema)
- quoted-user)])))))
+ {:database-id (:id database) :step :grant}))))
+ (sql-jdbc.execute/do-with-connection-with-options
+ driver database {:write? true}
+ (fn [^Connection conn]
+ (with-open [^Statement stmt (.createStatement conn)]
+ (doseq [schema schemas]
+ (.addBatch ^Statement stmt
+ ^String (format "GRANT SELECT ON SCHEMA::%s TO %s"
+ (quote-schema schema)
+ quoted-user)))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Indexes (Index Manager) |
diff --git a/src/metabase/driver/h2.clj b/src/metabase/driver/h2.clj
index 30af1f799af..a514acd1a2a 100644
--- a/src/metabase/driver/h2.clj
+++ b/src/metabase/driver/h2.clj
@@ -762,7 +762,8 @@
[driver database workspace]
(let [schema-name (:schema workspace)
[_file {username "USER" password "PASSWORD"}]
- (connection-string->file+options (-> workspace :database_details :db))]
+ (connection-string->file+options (-> workspace :database_details :db))
+ escaped-password (sql.u/escape-sql password :ansi)]
;; No transaction: H2 DDL (CREATE USER/SCHEMA, GRANT) commits any open
;; transaction, so a wrapper would be decorative. Failure recovery is
;; compensation via the idempotent destroy, not rollback.
@@ -770,17 +771,17 @@
driver database {:write? true}
(fn [^Connection conn]
(with-open [^Statement stmt (.createStatement conn)]
- (doseq [sql [(format "CREATE USER IF NOT EXISTS \"%s\" PASSWORD '%s'" username password)
+ (doseq [sql [(format "CREATE USER IF NOT EXISTS \"%s\" PASSWORD '%s'" username escaped-password)
;; the user may survive a failed teardown; without this it would keep
;; its old password while the new one gets persisted
- (format "ALTER USER \"%s\" SET PASSWORD '%s'" username password)
+ (format "ALTER USER \"%s\" SET PASSWORD '%s'" username escaped-password)
(format "CREATE SCHEMA IF NOT EXISTS \"%s\" AUTHORIZATION \"%s\"" schema-name username)
(format "GRANT ALL ON SCHEMA \"%s\" TO \"%s\"" schema-name username)]]
(.addBatch ^Statement stmt ^String sql))
(try
(.executeBatch ^Statement stmt)
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [password])))))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [password escaped-password])))))))
nil))
(defmethod driver/destroy-workspace-isolation! :h2
@@ -795,7 +796,10 @@
(format "DROP SCHEMA IF EXISTS \"%s\" CASCADE" schema-name)
(format "DROP USER IF EXISTS \"%s\"" username)]]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
(defmethod driver/grant-workspace-read-access! :h2
[driver database workspace schemas]
@@ -813,7 +817,10 @@
(.addBatch ^Statement stmt
^String (format "GRANT SELECT ON SCHEMA %s TO %s"
(sql.u/quote-name :h2 :schema schema) qu)))
- (.executeBatch ^Statement stmt))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
(defmethod driver/llm-sql-dialect-resource :h2 [_]
"metabot/prompts/dialects/h2.md")
diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.clj
index 6531240fcc3..439ec2333cd 100644
--- a/src/metabase/driver/mysql.clj
+++ b/src/metabase/driver/mysql.clj
@@ -1348,7 +1348,7 @@
(try
(.executeBatch ^Statement stmt)
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [password escaped-password]))))))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [password escaped-password]))))))))
nil))
(defmethod driver/destroy-workspace-isolation! :mysql
@@ -1365,7 +1365,10 @@
(mysql-user-exists? {:connection conn} username)
(conj (format "DROP USER IF EXISTS %s@'%%'" quoted-user)))]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
(defn- grant-workspace-read-access-sqls
"Build SQL statements that grant `username` SELECT on all tables in each database
@@ -1395,7 +1398,10 @@
(with-open [^Statement stmt (.createStatement conn)]
(doseq [sql sqls]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt))))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Indexes (Index Manager) |
diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.clj
index c93fc0ae26f..6bc5e72f2fd 100644
--- a/src/metabase/driver/postgres.clj
+++ b/src/metabase/driver/postgres.clj
@@ -1668,16 +1668,17 @@
(defmethod driver/init-workspace-isolation! :postgres
[_driver database workspace]
- (let [schema-name (:schema workspace)
- read-user (:database_details workspace)
- quoted-schema (quote-schema schema-name)
- quoted-user (quote-field (:user read-user))]
+ (let [schema-name (:schema workspace)
+ read-user (:database_details workspace)
+ escaped-password (sql.u/escape-sql (:password read-user) :ansi)
+ quoted-schema (quote-schema schema-name)
+ quoted-user (quote-field (:user read-user))]
(jdbc/with-db-transaction [t-conn (sql-jdbc.conn/db->pooled-connection-spec (:id database))]
;; Create user if not exists, otherwise update password
;; PostgreSQL doesn't support CREATE USER IF NOT EXISTS, so we need to check first
(let [user-sql (if (user-exists? t-conn (:user read-user))
- (format "ALTER USER %s WITH PASSWORD '%s'" quoted-user (:password read-user))
- (format "CREATE USER %s WITH PASSWORD '%s'" quoted-user (:password read-user)))]
+ (format "ALTER USER %s WITH PASSWORD '%s'" quoted-user escaped-password)
+ (format "CREATE USER %s WITH PASSWORD '%s'" quoted-user escaped-password))]
(with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]
(doseq [sql [;; PostgreSQL supports IF NOT EXISTS for schemas
(format "CREATE SCHEMA IF NOT EXISTS %s" quoted-schema)
@@ -1693,7 +1694,7 @@
(try
(.executeBatch ^Statement stmt)
(catch Throwable t
- (throw (driver.u/scrub-exceptions t [(:password read-user)])))))))
+ (throw (driver.u/scrub-exceptions (driver.u/batch-exception t) [(:password read-user) escaped-password])))))))
nil))
(defmethod driver/destroy-workspace-isolation! :postgres
@@ -1709,7 +1710,10 @@
(into [(format "DROP OWNED BY %s" quoted-user)
(format "DROP USER IF EXISTS %s" quoted-user)]))]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt)))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))
(defn- grant-workspace-read-access-sqls
"Build the sequence of SQL statements that grant `username` read access to every
@@ -1752,7 +1756,10 @@
(with-open [^Statement stmt (.createStatement ^Connection (:connection t-conn))]
(doseq [sql sqls]
(.addBatch ^Statement stmt ^String sql))
- (.executeBatch ^Statement stmt)))))
+ (try
+ (.executeBatch ^Statement stmt)
+ (catch Throwable t
+ (throw (driver.u/batch-exception t))))))))
(defmethod driver/llm-sql-dialect-resource :postgres [_]
"metabot/prompts/dialects/postgresql.md")
diff --git a/src/metabase/driver/util.clj b/src/metabase/driver/util.clj
index 7f6691b4c2f..9970ff3c358 100644
--- a/src/metabase/driver/util.clj
+++ b/src/metabase/driver/util.clj
@@ -851,6 +851,25 @@
[msg secrets]
(reduce (fn [s secret] (str/replace s secret "****")) (or msg "") secrets))
+(defn batch-exception
+ "The per-statement exception hiding inside a `java.sql.BatchUpdateException`,
+ or `t` itself for any other throwable. Rethrow this instead of the raw batch
+ exception so failures read as the plain server error rather than `Batch
+ entry N ... was aborted: ... Call getNextException to see other errors in
+ the batch.`
+
+ Connectors chain the underlying exception differently: pgjdbc (and its
+ Redshift fork) via `.getNextException`, the MariaDB connector via
+ `.getCause`. Connectors that chain nothing (e.g. mssql-jdbc) don't wrap the
+ message in the first place, so the batch exception is returned as is."
+ ^Throwable [^Throwable t]
+ (if (instance? java.sql.BatchUpdateException t)
+ (let [^java.sql.BatchUpdateException bue t]
+ (or (.getNextException bue)
+ (.getCause bue)
+ bue))
+ t))
+
(defn scrub-exceptions
"Scrub `secrets` from the exception message and cause chain of `t`. Returns a new
exception with every occurrence of each secret replaced by `****`. Use this to prevent
diff --git a/test/metabase/driver/util_test.clj b/test/metabase/driver/util_test.clj
index 54f47c5d809..052caa2f92e 100644
--- a/test/metabase/driver/util_test.clj
+++ b/test/metabase/driver/util_test.clj
@@ -654,3 +654,33 @@
trace (.getStackTrace original)
e (driver.u/scrub-exceptions original ["s3cret"])]
(is (= (seq trace) (seq (.getStackTrace ^Exception e)))))))
+
+(deftest batch-exception-scrub-test
+ (testing "unwrapping the batch envelope composes with password scrubbing (the init-workspace-isolation! shape)"
+ (let [inner (java.sql.SQLException. "ERROR: syntax error in CREATE USER \"u\" PASSWORD 's3cret'")
+ batch (doto (java.sql.BatchUpdateException. "Batch entry 0 CREATE USER ... PASSWORD 's3cret' was aborted" (int-array 0))
+ (.setNextException inner))
+ scrubbed (driver.u/scrub-exceptions (driver.u/batch-exception batch) ["s3cret"])]
+ (is (not (instance? java.sql.BatchUpdateException scrubbed))
+ "the batch envelope is gone")
+ (is (not (str/includes? (ex-message scrubbed) "s3cret"))
+ "the password is gone from the message")
+ (is (str/includes? (ex-message scrubbed) "****")
+ "the password is redacted, not silently dropped"))))
+
+(deftest batch-exception-test
+ (testing "unwraps the underlying per-statement exception of a BatchUpdateException"
+ (let [inner (java.sql.SQLException. "user cannot be dropped")
+ batch (doto (java.sql.BatchUpdateException. "Batch entry 18 ..." (int-array 0))
+ (.setNextException inner))]
+ (is (identical? inner (driver.u/batch-exception batch)))))
+ (testing "the MariaDB-connector shape chains the real exception via the cause"
+ (let [inner (java.sql.SQLException. "You are not allowed to create a user with GRANT")
+ batch (java.sql.BatchUpdateException. "envelope" nil 0 (int-array 0) inner)]
+ (is (identical? inner (driver.u/batch-exception batch)))))
+ (testing "the mssql-jdbc shape (no next exception, no cause) passes through — its message is already the plain server error"
+ (let [batch (java.sql.BatchUpdateException. "Cannot find the schema 'x'" "S0001" 208 (int-array 0))]
+ (is (identical? batch (driver.u/batch-exception batch)))))
+ (testing "non-batch throwables pass through"
+ (let [e (ex-info "boom" {})]
+ (is (identical? e (driver.u/batch-exception e))))))