Skip to content

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

Allow impersonated set operations like union, intersect, and except (#73873)

Riley Thompsonb4270a134719
diff --git a/resources/python-sources/sql_tools.py b/resources/python-sources/sql_tools.py
index 40959410aae..faf2e4cd778 100644
--- a/resources/python-sources/sql_tools.py
+++ b/resources/python-sources/sql_tools.py
@@ -1615,7 +1615,8 @@ def is_single_stmt_of_type(sql: str, stmt_type: str = "read", dialect: str = Non
result = {"is_single_stmt?": False}
try:
stmts = sqlglot.parse(sql, read=dialect)
- allowed_types = (exp.Select,) if stmt_type == "read" else (exp.Update, exp.Insert, exp.Delete)
+ allowed_types = (exp.Select, exp.SetOperation)
+ if stmt_type != "read": allowed_types = (exp.Update, exp.Insert, exp.Delete)
if len(stmts) == 1 and isinstance(stmts[0], allowed_types):
result["is_single_stmt?"] = True
result["sql"] = stmts[0].sql(dialect=dialect) if dialect else stmts[0].sql()
diff --git a/test/metabase/sql_tools/core_test.clj b/test/metabase/sql_tools/core_test.clj
index e685c689404..e6374c6e497 100644
--- a/test/metabase/sql_tools/core_test.clj
+++ b/test/metabase/sql_tools/core_test.clj
@@ -215,4 +215,18 @@
"UPDATE table SET column = 1; SELECT 1"
"DELETE FROM table WHERE id = 1; SELECT 1"
"SET ROLE NONE; INSERT INTO table VALUES (1)"
- "SELECT set_config('role', 'none', false); DELETE FROM table WHERE id = 1"))))
+ "SELECT set_config('role', 'none', false); DELETE FROM table WHERE id = 1"))
+ (testing "A single set operation statement returns true and the reconstructed SQL"
+ (doseq [op ["UNION ALL" "INTERSECT ALL" "EXCEPT ALL"]
+ ts [["foo" "bar"] ["foo" "bar" "baz"]]
+ :let [sql (str/join (str " " op " ") (map #(str "SELECT * FROM " %) ts))]]
+ (is (=? {:is-single-stmt? true, :sql string?}
+ (sql-tools/is-single-stmt-of-type? driver/*driver* sql "read"))))
+ (are [sql] (=? {:is-single-stmt? true, :sql string?}
+ (sql-tools/is-single-stmt-of-type? driver/*driver* sql "read"))
+ "SELECT * FROM foo UNION ALL SELECT * FROM bar INTERSECT ALL SELECT * FROM baz"
+ "SELECT * FROM foo UNION ALL SELECT * FROM bar EXCEPT ALL SELECT * FROM baz"
+ "SELECT * FROM foo INTERSECT ALL SELECT * FROM bar UNION ALL SELECT * FROM baz"
+ "SELECT * FROM foo INTERSECT ALL SELECT * FROM bar EXCEPT ALL SELECT * FROM baz"
+ "SELECT * FROM foo EXCEPT ALL SELECT * FROM bar UNION ALL SELECT * FROM baz"
+ "SELECT * FROM foo EXCEPT ALL SELECT * FROM bar INTERSECT ALL SELECT * FROM baz"))))