Skip to content

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

Disambiguate conflicting custom column names (#84194)

technomancy201131a03413
diff --git a/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js b/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js
index 39796ef966e..50c6b9ccbb3 100644
--- a/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js
+++ b/e2e/test/scenarios/custom-column/custom-column-reproductions-1.cy.spec.js
@@ -523,7 +523,9 @@ describe("issue 21135", () => {
cy.findByTestId("preview-root").within(() => {
cy.findByText("Rustic Paper Wallet");
- cy.findAllByText("Price").should("have.length", 2);
+ // Make sure we see both the original column and the custom column
+ cy.findAllByText("Price").should("have.length", 1);
+ cy.findAllByText("Price (1)").should("have.length", 1);
cy.findByText("29.46"); // actual Price column
cy.findByText("31.46"); // custom column
@@ -531,59 +533,6 @@ describe("issue 21135", () => {
});
});
-describe("issue 40064", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsNormalUser();
- });
-
- it("should be able to edit a custom column with the same name as one of the columns used in the expression (metabase#40064)", () => {
- H.createQuestion(
- {
- query: {
- "source-table": ORDERS_ID,
- expressions: {
- Tax: ["*", ["field", ORDERS.TAX, { "base-type": "type/Float" }], 2],
- },
- limit: 1,
- },
- },
- { visitQuestion: true },
- );
-
- cy.log("check the initial expression value");
- H.tableInteractive().findByText("4.14").should("be.visible");
-
- cy.log("update the expression and check the value");
- H.openNotebook();
- H.getNotebookStep("expression").findByText("Tax").click();
- H.enterCustomColumnDetails({ formula: "[Tax] * 3", blur: true });
- H.popover().button("Update").click();
- H.visualize();
- H.tableInteractive().findByText("6.21").should("be.visible");
-
- cy.log("rename the expression and make sure you cannot create a cycle");
- H.openNotebook();
- H.getNotebookStep("expression").findByText("Tax").click();
- H.enterCustomColumnDetails({
- formula: "[Tax] * 3",
- name: "Tax3",
- blur: true,
- });
- H.popover().button("Update").should("not.be.disabled").click();
- H.getNotebookStep("expression").findByText("Tax3").click();
- H.enterCustomColumnDetails({
- formula: "[Tax3] * 3",
- name: "Tax3",
- blur: true,
- });
- H.popover().within(() => {
- cy.findByText("Unknown column: Tax3").should("be.visible");
- cy.button("Update").should("be.disabled");
- });
- });
-});
-
describe("issue 21513", () => {
beforeEach(() => {
H.restore();
diff --git a/frontend/src/metabase-lib/v1/queries/utils/expression.ts b/frontend/src/metabase-lib/v1/queries/utils/expression.ts
index 98ff7bef029..50b406e5302 100644
--- a/frontend/src/metabase-lib/v1/queries/utils/expression.ts
+++ b/frontend/src/metabase-lib/v1/queries/utils/expression.ts
@@ -1,5 +1,5 @@
-import { unique_expression_name } from "cljs/metabase.xrays.domain_entities.queries.util";
-import type { ExpressionClause } from "metabase-types/api";
+import { unique_expression_name } from "cljs/metabase.lib.js";
+import type * as Lib from "metabase-lib";
/**
* Ensures expression's name uniqueness
@@ -12,8 +12,9 @@ import type { ExpressionClause } from "metabase-types/api";
* If the original name is already unique, the fn just returns it
*/
export function getUniqueExpressionName(
- expressions: ExpressionClause,
- originalName: string,
+ query: Lib.Query,
+ stageIndex: number,
+ name: string,
): string {
- return unique_expression_name(expressions, originalName);
+ return unique_expression_name(query, stageIndex, name);
}
diff --git a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx
index 2c7799403d9..5c89ce04189 100644
--- a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx
+++ b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.tsx
@@ -160,17 +160,13 @@ const getUniqueClauseName = (
clause: Lib.ExpressionClause | undefined,
name: string,
) => {
- const isUpdate = clause != null;
// exclude the current clause so that it can be updated without renaming
- const queryWithoutCurrentClause = isUpdate
- ? Lib.removeClause(query, stageIndex, clause)
- : query;
- const expressions = Lib.expressions(queryWithoutCurrentClause, stageIndex);
- const expressionsObject = Object.fromEntries(
- expressions.map((expression) => [
- Lib.displayInfo(query, stageIndex, expression).displayName,
- ]),
+ const queryWithoutCurrentClause =
+ clause != null ? Lib.removeClause(query, stageIndex, clause) : query;
+ const uniqueName = getUniqueExpressionName(
+ queryWithoutCurrentClause,
+ stageIndex,
+ name,
);
- const uniqueName = getUniqueExpressionName(expressionsObject, name);
return uniqueName;
};
diff --git a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx
index 796956d2e8a..1cbe1f02100 100644
--- a/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx
+++ b/frontend/src/metabase/querying/notebook/components/ExpressionStep/ExpressionStep.unit.spec.tsx
@@ -168,7 +168,7 @@ describe("Notebook Editor > Expression Step", () => {
const expressions = Lib.expressions(recentQuery, 0);
expect(expressions).toHaveLength(1);
expect(Lib.displayInfo(recentQuery, 0, expressions[0]).displayName).toBe(
- "Total",
+ "Total (1)",
);
});
});
diff --git a/shadow-cljs.edn b/shadow-cljs.edn
index af7ad5fb34f..472db8a92ba 100644
--- a/shadow-cljs.edn
+++ b/shadow-cljs.edn
@@ -34,8 +34,7 @@
metabase.util.formatting.constants
metabase.util.formatting.date
metabase.util.markdown.image
- metabase.util.time
- metabase.xrays.domain-entities.queries.util]}
+ metabase.util.time]}
:test
{:target :node-test
diff --git a/src/metabase/lib/expression.cljc b/src/metabase/lib/expression.cljc
index 2fcb6fc96a2..a330135784a 100644
--- a/src/metabase/lib/expression.cljc
+++ b/src/metabase/lib/expression.cljc
@@ -808,3 +808,25 @@
(not (lib.metadata/database-supports? query :expression-literals)))
{:message (i18n/tru "Standalone constants are not supported.")
:friendly true})))))
+
+(defn- unique-name [names original-name index]
+ (let [indexed-name (str original-name " (" index ")")]
+ (if (names indexed-name)
+ (recur names original-name (inc index))
+ indexed-name)))
+
+(defn unique-expression-name
+ "Generates an expression name that's unique in the query.
+ The current clause for the expression whose name has been suggested (if
+ applicable) has already been removed from the query here."
+ [query stage-number suggested-name]
+ (let [columns (lib.metadata.calculation/visible-columns query stage-number)
+ other-names (set (map :display-name columns))]
+ (if (not (other-names suggested-name))
+ suggested-name
+ (let [start (str suggested-name " (")
+ ;; can't use regexes here because js/RegExp.escape is too new
+ duplicates (into #{suggested-name}
+ (filter #(str/starts-with? % start) other-names))]
+ (unique-name duplicates suggested-name (count duplicates))))))
+str/replace
diff --git a/src/metabase/lib/js.cljs b/src/metabase/lib/js.cljs
index 5d6849d78dc..c105a43448d 100644
--- a/src/metabase/lib/js.cljs
+++ b/src/metabase/lib/js.cljs
@@ -2819,3 +2819,8 @@
(-> js-native-query-spec
(js->clj :keywordize-keys true)
(->> (lib.query.test-spec/test-native-query metadata-providerable))))
+
+(defn ^:export unique-expression-name
+ "Generates an expression name that's unique in the query."
+ [the-query stage-number suggested-name]
+ (lib.expression/unique-expression-name the-query stage-number suggested-name))
diff --git a/src/metabase/xrays/domain_entities/converters.cljs b/src/metabase/xrays/domain_entities/converters.cljs
deleted file mode 100644
index 9b89086fb25..00000000000
--- a/src/metabase/xrays/domain_entities/converters.cljs
+++ /dev/null
@@ -1,146 +0,0 @@
-(ns metabase.xrays.domain-entities.converters
- (:require
- [malli.core :as mc]
- [malli.transform :as mtx]
- [metabase.util :as u]))
-
-(defn- decode-map [schema _]
- (let [by-prop (into {} (for [[map-key props] (mc/children schema)]
- [(or (get props :js/prop)
- (u/->snake_case_en (u/qualified-name map-key)))
- {:map-key map-key}]))]
- {:enter (fn [x]
- (cond
- (map? x) x
- (object? x)
- (into {} (for [prop (js-keys x)
- :let [js-val (unchecked-get x prop)
- map-key (or (get-in by-prop [prop :map-key])
- (keyword (u/->kebab-case-en prop)))]]
- [map-key js-val]))))
- :leave (fn [x]
- (if (object? x)
- (throw (ex-info "decode-map leaving with a JS object not a CLJS map"
- {:value x
- :schema (mc/form schema)}))
- x))}))
-
-(defn- infer-child-decoder [schema _]
- (let [mapping (into {} (for [c (mc/children schema)]
- (if (keyword? c)
- [(name c) c]
- [c c])))]
- {:enter #(mapping % %)}))
-
-(defn- infer-child-encoder [schema _]
- (let [mapping (into {} (for [c (mc/children schema)]
- (if (keyword? c)
- [c (name c)]
- [c c])))]
- {:enter #(mapping % %)}))
-
-(defn- decode-map-of [keydec x]
- (cond
- (map? x) x
- (object? x) (into {} (for [prop (js/Object.keys x)]
- [(keydec prop) (unchecked-get x prop)]))))
-
-(defn- encode-map [x keyenc]
- (cond
- (object? x) x
- (map? x) (reduce-kv (fn [obj k v]
- (unchecked-set obj (keyenc k) v)
- obj)
- #js {}
- x)))
-
-(def ^:private identity-transformers
- (-> ['string? :string
- 'number? :number
- 'int? :int
- 'double? :double
- 'float? :float]
- (zipmap (repeat {:enter identity}))))
-
-(def js-transformer
- "Malli transformer for converting JavaScript data to and from CLJS data.
-
- This is a bit more flexible than a JSON transformer. In particular, it normalizes the keys of `:map`
- schema objects to `:kebab-case-keywords`, and restores them to strings with the original spelling when
- converting back.
-
- **On keyword conversion**
-
- Note that `\"snake_case\"` is the default spelling we expect in the JS data.
- This can be overridden with the `{:js/prop \"correctSpelling\"}` property on the schema, eg.
- ```
- [:map
- [:camel-case {:js/prop \"camelCase\"} string?]
- [:kebab-case {:js/prop \"kebab-case\"} number?]
- [:snake-case [:enum \"foo\" \"bar\"]]]
- ```
-
- Observe that `:snake-case` does not need a `:js/prop` setting, since that is the default.
-
- **On `:map-of`**
-
- Note that `:map-of` is not `:map`. The spelling of the keys in a `:map-of` is not changed. If the key
- schema is `keyword?`, they will be converted to keywords and back, but with the original spelling.
-
- **On sequences**
- `:tuple`, `:vector` and `:sequential` all get transformed into CLJS vectors. When converting back to JS,
- they are JS arrays."
- (mtx/transformer
- {:name :js
- :decoders
- (merge identity-transformers
- {:keyword keyword
- 'keyword? keyword
- :qualified-keyword keyword
- :uuid parse-uuid
- :vector {:enter #(and % (vec %))}
- :sequential {:enter #(and % (vec %))}
- :tuple {:enter #(and % (vec %))}
- :cat {:enter #(and % (vec %))}
- :catn {:enter #(and % (vec %))}
- :enum {:compile infer-child-decoder}
- := {:compile infer-child-decoder}
- :map {:compile decode-map}
- :map-of {:compile (fn [schema _]
- (let [[key-schema] (mc/children schema)
- keydec (mc/decoder key-schema js-transformer)]
- {:enter #(decode-map-of keydec %)}))}})
- :encoders
- (merge identity-transformers
- {:keyword name
- 'keyword? name
- :qualified-keyword #(str (namespace %) "/" (name %))
- :uuid str
- :vector {:leave clj->js}
- :sequential {:leave clj->js}
- :tuple {:leave clj->js}
- :enum {:compile infer-child-encoder}
- := {:compile infer-child-encoder}
- :map {:compile
- (fn [schema _]
- (let [js-props (into {} (for [[k props] (mc/children schema)
- :when (:js/prop props)]
- [k (:js/prop props)]))
- keyenc (fn [k] (or (get js-props k)
- (u/->snake_case_en (u/qualified-name k))))]
- {:leave #(encode-map % keyenc)}))}
- :map-of {:leave #(encode-map % name)}})}))
-
-(defn incoming
- "Returns a function for converting a JS value into CLJS data structures, based on a schema."
- [schema]
- ;; TODO This should be a mc/coercer that decodes and then validates, throwing if it doesn't match.
- ;; However, enabling that now breaks loads of tests that pass input data with lots of holes. The JS
- ;; tests (as opposed to TS) are particularly bad for this.
- ;; Don't forget the nested `mc/decoder` calls elsewhere in this file!
- (mc/decoder schema js-transformer))
-
-(defn outgoing
- "Returns a function for converting a CLJS value back into a plain JS one, based on its schema."
- [schema]
- (mc/encoder schema js-transformer))
diff --git a/src/metabase/xrays/domain_entities/queries/util.cljc b/src/metabase/xrays/domain_entities/queries/util.cljc
deleted file mode 100644
index 41e44e19793..00000000000
--- a/src/metabase/xrays/domain_entities/queries/util.cljc
+++ /dev/null
@@ -1,53 +0,0 @@
-(ns metabase.xrays.domain-entities.queries.util
- "Utility functions used by the Queries in metabase-lib."
- (:require
- #?@(:cljs ([metabase.xrays.domain-entities.converters :as converters]))
- [metabase.lib.schema.common :as lib.schema.common]
- [metabase.util.malli :as mu]))
-
-(def Expression
- "Schema for an Expression that's part of a query filter."
- ::lib.schema.common/possibly-unnormalized-clause)
-
-(def ExpressionMap
- "Malli schema for a map of expressions by name."
- [:map-of string? Expression])
-
-(def ExpressionList
- "Malli schema for a list of {:name :expression} maps."
- [:vector [:map [:name string?] [:expression Expression]]])
-
-(def ^:private ->expression-map
- #?(:cljs (converters/incoming ExpressionMap)
- :clj identity))
-
-(def ^:private expression-list->
- #?(:cljs (converters/outgoing ExpressionList)
- :clj identity))
-
-(mu/defn ^:export expressions-list :- ExpressionList
- "Turns a map of expressions by name into a list of `{:name name :expression expression}` objects."
- [expressions :- ExpressionMap]
- (->> expressions
- ->expression-map
- (mapv (fn [[name expr]] {:name name :expression expr}))
- expression-list->))
-
-(defn- unique-name [names original-name index]
- (let [indexed-name (str original-name " (" index ")")]
- (if (names indexed-name)
- (recur names original-name (inc index))
- indexed-name)))
-
-(mu/defn ^:export unique-expression-name :- string?
- "Generates an expression name that's unique in the given map of expressions."
- [expressions :- ExpressionMap
- original-name :- string?]
- (let [expression-names (-> expressions ->expression-map keys set)]
- (if (not (expression-names original-name))
- original-name
- (let [re-duplicates (re-pattern (str "^" original-name " \\([0-9]+\\)$"))
- duplicates (set (filter #(or (= % original-name)
- (re-matches re-duplicates %))
- expression-names))]
- (unique-name duplicates original-name (count duplicates))))))
diff --git a/test/metabase/lib/expression_test.cljc b/test/metabase/lib/expression_test.cljc
index 8d383b274d2..5ecff81a464 100644
--- a/test/metabase/lib/expression_test.cljc
+++ b/test/metabase/lib/expression_test.cljc
@@ -943,3 +943,25 @@
:lib/type :metadata/column
:metabase.lib.field.resolution/fallback-metadata? (symbol "nil #_\"key is not present.\"")}
(lib/metadata query -1 (lib/ref (meta/field-metadata :venues :name)))))))))
+
+(deftest ^:parallel unique-expression-name-test
+ (let [query (lib/query meta/metadata-provider (meta/table-metadata :people))]
+ (testing "a completely unrelated name"
+ (is (= "Channels" (lib.expression/unique-expression-name query 0 "Channels"))))
+ (testing "a custom column that conflicts with a source column name"
+ (is (= "Email (1)" (lib.expression/unique-expression-name query 0 "Email"))))
+ (testing "when a disambiguated custom column already exists"
+ (let [query2 (lib/expression query "Email (1)"
+ (lib/concat (meta/field-metadata :people :email) ".com"))]
+ (testing "and you add a new one"
+ (is (= "Email (2)" (lib.expression/unique-expression-name query2 0 "Email"))))))
+ (testing "when a column name needs escaping"
+ (let [query2 (lib/expression query "net.net"
+ (lib/concat (meta/field-metadata :people :email) ".net"))
+ query3 (lib/expression query "netxnet"
+ (lib/concat (meta/field-metadata :people :email) ".net"))
+ query4 (lib/expression query2 "netxnet (1)"
+ (lib/concat (meta/field-metadata :people :email) ".net"))]
+ (is (= "net.net (1)" (lib.expression/unique-expression-name query2 0 "net.net")))
+ (is (= "net.net" (lib.expression/unique-expression-name query3 0 "net.net")))
+ (is (= "net.net (1)" (lib.expression/unique-expression-name query4 0 "net.net")))))))
diff --git a/test/metabase/xrays/domain_entities/converters_test.cljs b/test/metabase/xrays/domain_entities/converters_test.cljs
deleted file mode 100644
index 21aaaef8700..00000000000
--- a/test/metabase/xrays/domain_entities/converters_test.cljs
+++ /dev/null
@@ -1,232 +0,0 @@
-(ns metabase.xrays.domain-entities.converters-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.test.util.js :as test.js]
- [metabase.xrays.domain-entities.converters :as converters]))
-
-(deftest ^:parallel incoming-basics-test
- (testing "simple values are not transformed"
- (is (= identity (converters/incoming number?)))
- (is (= identity (converters/incoming string?)))
- (is (= identity (converters/incoming nil?)))
- (is (= identity (converters/incoming boolean?)))))
-
-(deftest ^:parallel keywords-test
- (testing "plain keywords are transformed without changing their spelling"
- (let [->kw (converters/incoming keyword?)
- kw-> (converters/outgoing keyword?)
- pairs [[:foo "foo"]
- [:foo-bar "foo-bar"]
- [:foo_bar "foo_bar"]
- [:fooBar "fooBar"]]]
- (doseq [[kw s] pairs]
- (is (= kw (->kw s)))
- (is (= s (kw-> kw)))
- (is (= kw (-> kw kw-> ->kw)))
- (is (= s (-> s ->kw kw->)))))))
-
-(deftest ^:parallel keywords-test-2
- (testing "qualified keywords are transformed without changing their spelling"
- (let [->kw (converters/incoming :qualified-keyword)
- kw-> (converters/outgoing :qualified-keyword)
- pairs [[:my.ns/foo "my.ns/foo"]
- [:my.ns/foo-bar "my.ns/foo-bar"]
- [:my.ns/foo_bar "my.ns/foo_bar"]
- [:my.ns/fooBar "my.ns/fooBar"]]]
- (doseq [[kw s] pairs]
- (is (= kw (->kw s)))
- (is (= s (kw-> kw)))
- (is (= kw (-> kw kw-> ->kw)))
- (is (= s (-> s ->kw kw->)))))))
-
-(def ^:private HalfDeclared
- [:map
- [:declared-camel {:js/prop "declaredCamel"} string?]
- [:declared-snake string?]
- [:declared-kebab {:js/prop "declared-kebab"} string?]])
-
-(def ^:private ->half-declared
- (converters/incoming HalfDeclared))
-
-(deftest ^:parallel map-basics-test
- (testing "incoming maps"
- (testing "become CLJS maps"
- (is (map? ((converters/incoming [:map]) #js {}))))
- (testing "have both declared and undeclared keys normalized as :kebab-case-keywords"
- (is (= {:declared-camel "yes"
- :declared-snake "also"
- :declared-kebab "finally"
- :undeclared-camel 7
- :undeclared-snake 8
- :undeclared-kebab 9}
- (->half-declared #js {"declaredCamel" "yes"
- "declared_snake" "also"
- "declared-kebab" "finally"
- "undeclaredCamel" 7
- "undeclared_snake" 8
- "undeclared-kebab" 9}))))
- (testing "work like maps for their declared keys"
- (let [converted (->half-declared #js {"declaredCamel" "yes"
- "declared_snake" "also"
- "declared-kebab" "finally"})]
- (is (= "yes" (:declared-camel converted)))
- (is (= "also" (:declared-snake converted)))
- (is (= "finally" (:declared-kebab converted)))
- (is (= :not-found (:does-not-exist converted :not-found)))
- (is (= "yes" (converted :declared-camel)))
- (is (= "also" (converted :declared-snake)))
- (is (= "finally" (converted :declared-kebab)))
- (is (= :not-found (converted :does-not-exist :not-found)))
- (is (= #{:declared-camel :declared-snake :declared-kebab}
- (set (keys converted))))
- (is (= #{"yes" "also" "finally"}
- (set (vals converted))))
- (is (= 3 (count converted)))
- (let [native {:declared-camel "yes"
- :declared-snake "also"
- :declared-kebab "finally"}]
- (is (= native converted))
- (is (= converted native))))))
- (testing "outgoing maps"
- (let [input #js {"declaredCamel" "yes"
- "declared_snake" "also"
- "declared-kebab" "finally"
- "undeclaredCamel" 7
- "undeclared_snake" 8
- "undeclared-kebab" 9}
- obj (->half-declared input)]
- (testing "are converted per the schema by :js/prop; defaulting to snake_case"
- (let [adjusted (assoc obj :declared-camel "no")]
- (is (not (identical? obj adjusted)))
- (is (test.js/= #js {"declaredCamel" "no"
- "declared_snake" "also"
- "declared-kebab" "finally"
- "undeclared_camel" 7
- "undeclared_snake" 8
- "undeclared_kebab" 9}
- ((converters/outgoing HalfDeclared) adjusted))))))))
-
-(def Child
- [:map [:inner-value {:js/prop "innerValue"} string?]])
-
-(def Parent
- [:map [:child Child]])
-
-(def Grandparent
- [:map [:parent Parent]])
-
-(deftest ^:parallel nesting-test
- (testing "deeply nested maps"
- (let [input #js {"parent" #js {"child" #js {"innerValue" "asdf"}}}
- exp-clj {:parent {:child {:inner-value "asdf"}}}
- converted ((converters/incoming Grandparent) input)]
- (is (= exp-clj converted))
- (is (test.js/= input ((converters/outgoing Grandparent) converted)))))
- (testing "nesting kitchen sink"
- (let [schema [:map
- [:foo-bar {:js/prop "fooBar"}
- [:vector
- [:map-of
- keyword?
- [:sequential
- [:map
- [:kebab-case {:js/prop "kebab-case"} :qualified-keyword]
- ;; TODO: Can we get keyword enums?
- ;; Not out of the box, but probably with a :js/something override the decoders
- ;; can be taught to check for.
- [:snake-case [:enum "abc" "def"]]
- [:camel-case {:js/prop "camelCase"} number?]]]]]]]
- ->sink (converters/incoming schema)
- sink-> (converters/outgoing schema)
- input #js {"fooBar"
- #js [#js {"first_chunk"
- #js [#js {"kebab-case" "becomes/keyword"
- "snake_case" "def"
- "camelCase" 7}
- #js {"kebab-case" "a/plain-keyword"
- "snake_case" "abc"
- "camelCase" -7}
- #js {"kebab-case" "a/snake_keyword"
- "snake_case" "def"
- "camelCase" 0}]
-
- "emptyChunk" #js []
- "another-chunk" #js [#js {"kebab-case" "a/camelKeyword"
- "snake_case" "abc"
- "camelCase" -2}]}
- #js {"cousin_chunk"
- #js [#js {"kebab-case" "namespaced.with/all-punctuation_used"
- "snake_case" "abc"
- "camelCase" 2}]}]}
-
- exp {:foo-bar [{:first_chunk [{:kebab-case :becomes/keyword
- :snake-case "def"
- :camel-case 7}
- {:kebab-case :a/plain-keyword
- :snake-case "abc"
- :camel-case -7}
- {:kebab-case :a/snake_keyword
- :snake-case "def"
- :camel-case 0}]
- :emptyChunk []
- :another-chunk [{:kebab-case :a/camelKeyword
- :snake-case "abc"
- :camel-case -2}]}
- {:cousin_chunk [{:kebab-case :namespaced.with/all-punctuation_used
- :snake-case "abc"
- :camel-case 2}]}]}
- converted (->sink input)]
- (testing "converts to CLJS as expected"
- (is (map? converted))
- (is (= exp converted)))
- (testing "round-trips as expected"
- (is (test.js/= input (-> input ->sink sink->)))))))
-
-(deftest ^:parallel idempotency-test
- (testing "CLJS maps are not further converted"
- (let [->parent (converters/incoming Parent)
- input {:child {:inner-value "foo"}}]
- (is (identical? input (->parent input))))))
-
-(deftest ^:parallel opaque-any-test
- (testing ":any values are not touched, and round-trip as identical?"
- (let [schema [:map
- [:wrapper [:map
- [:inner :any]
- [:other number?]]]
- [:foo string?]]
- js-obj #js {"neverConverted" true}
- input #js {"wrapper" #js {"inner" js-obj
- "other" 7}
- "foo" "bar"}
- ->map (converters/incoming schema)
- map-> (converters/outgoing schema)
- converted (->map input)
- returned ^Object (map-> converted)]
- (is (map? (-> converted :wrapper)))
- (is (object? (-> converted :wrapper :inner)))
- (is (identical? js-obj (-> converted :wrapper :inner)))
- (is (identical? js-obj (let [^Object wrapper (.-wrapper returned)]
- (.-inner wrapper)))))))
-
-(deftest ^:parallel uuid-test
- (testing "UUIDs are converted to strings in JS and back to #uuid objects in CLJS"
- (let [uuid (random-uuid)]
- (is (= (str uuid)
- ((converters/outgoing :uuid) uuid)))
- (is (= uuid
- ((converters/incoming :uuid) (str uuid))))))
- (testing "UUIDs nested in maps work too"
- (let [uuid (random-uuid)
- schema [:map [:id :uuid]]]
- (is (test.js/= #js {:id (str uuid)}
- ((converters/outgoing schema) {:id uuid})))
- (is (= {:id uuid}
- ((converters/incoming schema) #js {:id (str uuid)})))))
- (testing "UUIDs nested in maps inside a map-of work too"
- (let [uuid (random-uuid)
- schema [:map-of :string [:map [:id :uuid]]]]
- (is (test.js/= #js{"abc" #js {:id (str uuid)}}
- ((converters/outgoing schema) {"abc" {:id uuid}})))
- (is (= {"abc" {:id uuid}}
- ((converters/incoming schema) #js {"abc" #js {:id (str uuid)}}))))))