Skip to content

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

Fix nested if statements (#69144)

Williambf3a0df461e0
diff --git a/src/metabase/lib/filter/desugar.cljc b/src/metabase/lib/filter/desugar.cljc
index d275944e8d5..5f8a8c3d319 100644
--- a/src/metabase/lib/filter/desugar.cljc
+++ b/src/metabase/lib/filter/desugar.cljc
@@ -161,10 +161,16 @@
(mu/defn- desugar-if :- ::clause
"Transform a `:if` expression to an `:case` expression."
[expr :- ::clause]
- (lib.util.match/replace expr
- [:if opts & args]
- (-> (apply lib.expression/case args)
- (merge-options opts))))
+ (letfn [(process-fragment [fragment]
+ (cond
+ (lib.util/clause? fragment) (desugar-if fragment)
+ (vector? fragment) (mapv process-fragment fragment)
+ :else fragment))]
+ (lib.util.match/replace expr
+ [:if opts & args]
+ (-> (map process-fragment args)
+ (->> (apply lib.expression/case))
+ (merge-options opts)))))
(mu/defn- desugar-in :- ::clause
"Transform `:in` and `:not-in` expressions to `:=` and `:!=` expressions."
diff --git a/test/metabase/lib/filter/desugar_test.cljc b/test/metabase/lib/filter/desugar_test.cljc
index ca288457fc1..3aecf89b1ec 100644
--- a/test/metabase/lib/filter/desugar_test.cljc
+++ b/test/metabase/lib/filter/desugar_test.cljc
@@ -194,6 +194,44 @@
[:if (opts :default 3)
[[[:< (opts) [:field (opts) 1] 1] 2]]])))))
+(deftest ^:parallel desugar-nested-if-test
+ (testing "Desugaring if produces expected [:case ..] expression"
+ (is (=? [:case {}
+ [[[:case {}
+ [[[:< {}
+ [:field {} 1]
+ 1]
+ [:< {}
+ [:field {} 2]
+ 2]]]
+ [:< {}
+ [:field {} 3]
+ 3]]
+ [:case {}
+ [[[:< {}
+ [:field {} 4]
+ 4]
+ 5]]]]]
+ [:case {}
+ [[[:< {}
+ [:field {} 6]
+ 6]
+ 7]]]]
+ (lib.filter.desugar/desugar-filter-clause
+ [:if (opts)
+ [[[:if (opts)
+ [[[:< (opts) [:field (opts) 1] 1]
+ [:< (opts) [:field (opts) 2] 2]]]
+ [:< (opts) [:field (opts) 3] 3]]
+ [:if (opts)
+ [[[:< (opts) [:field (opts) 4] 4]
+ 5]]]]]
+ [:if (opts)
+ [[[:< (opts)
+ [:field (opts) 6]
+ 6]
+ 7]]]])))))
+
(deftest ^:parallel desugar-if-with-default-value-test
(is (= [:case {:lib/uuid "00000000-0000-0000-0000-000000000000", :lib/expression-name "If"}
[[[:= {:lib/uuid "00000000-0000-0000-0000-000000000001"}