From e2547454b5a5b808ca38ac9dfb264a07d2848676 Mon Sep 17 00:00:00 2001 From: Ngoc Khuat Date: Tue, 28 Mar 2023 00:53:25 +0700 Subject: [PATCH] Fix insert transform only keys in first row (#138) * fix insert transform only keys that are in first row * a better approach? * adds a test description --- src/toucan2/tools/transformed.clj | 19 +++++++------------ test/toucan2/tools/transformed_test.clj | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/src/toucan2/tools/transformed.clj b/src/toucan2/tools/transformed.clj index 8b267fd..5759c8b 100644 --- a/src/toucan2/tools/transformed.clj +++ b/src/toucan2/tools/transformed.clj @@ -281,20 +281,15 @@ ;;;; before insert -;;; TODO -- this shares a lot of code with [[transform-update-changes]] (defn- transform-insert-rows [[first-row :as rows] k->transform] {:pre [(map? first-row) (map? k->transform)]} - ;; all rows should have the same keys, so we just need to look at the keys in the first row - (let [row-xforms (for [k (keys first-row) - :let [xform (get k->transform k)] - :when xform] - (fn [row] - (update row k (fn [v] - (if (some? v) - (xform v) - v))))) - row-xform (apply comp row-xforms)] - (map row-xform rows))) + (let [x-forms (for [[k transform] k->transform] + (fn [row] + (if (some? (get row k)) + (update row k transform) + row))) + x-form (apply comp x-forms)] + (map x-form rows))) (m/defmethod pipeline/build [#_query-type :toucan.query-type/insert.* #_model ::transformed.model diff --git a/test/toucan2/tools/transformed_test.clj b/test/toucan2/tools/transformed_test.clj index f1263e2..6d498b6 100644 --- a/test/toucan2/tools/transformed_test.clj +++ b/test/toucan2/tools/transformed_test.clj @@ -543,3 +543,20 @@ (is (= 'transforms-primary-method-model-2 (generated-name `(transformed/deftransforms :model-2 {:x {:in ~'inc}}))))))) + +(derive ::venues.edn-category ::test/venues) + +(transformed/deftransforms ::venues.edn-category + {:category {:in pr-str + :out (fn [s] + (binding [*read-eval* false] + (read-string s)))}}) + +(deftest ^:parallel transform-insert-rows-test + (testing "insert multiple rows in which each row has different key set will still do transformation properly (#130)" + (is (= [{:name "Venue 1"} + {:name "Venue 2", :category "{:name \"Category 2\"}"}] + (#'toucan2.tools.transformed/transform-insert-rows + '[{:name "Venue 1"} + {:name "Venue 2", :category {:name "Category 2"}}] + (#'toucan2.tools.transformed/in-transforms ::venues.edn-category))))))