refactor: db ident generation with tests

Add tests for recent db ident fixes. Add check that backup keyword is valid
edn. Also generate correct keyword for cases like logseq/db-test#4 as
catch should be relied only for unexpected cases
pull/11483/head
Gabriel Horner 2024-08-19 15:13:06 -04:00
parent 658ea25a21
commit eff0d5e7d4
2 changed files with 29 additions and 15 deletions

View File

@ -52,20 +52,26 @@
(string/replace #"\s*:\s*$" "")
(string/replace-first #"^\d+" "")
(string/replace " " "-")
(string/replace "#" "")
;; '/' cannot be in name - https://clojure.org/reference/reader
(string/replace "/" "-")
(string/trim))]
(try
(when-not (seq n)
(throw (ex-info "name is not empty" {:n n})))
(let [k (keyword user-namespace n)]
(when-not (= k (edn/read-string (str k)))
(throw (ex-info "illegal keyword" {:k k})))
k)
(catch :default _e
(let [n (->> (filter #(re-find #"[0-9a-zA-Z-]{1}" %) (seq n))
(apply str))]
(if (seq n)
(string/replace #"[#()]" "")
(string/trim))
;; Similar check to common-util/valid-edn-keyword?. Consider merging the two use cases
keyword-is-valid-edn! (fn keyword-is-valid-edn! [k]
(when-not (= k (edn/read-string (str k)))
(throw (ex-info "Keyword is not valid edn" {:keyword k}))))
k (if (seq n)
(keyword user-namespace n)
(keyword user-namespace (nano-id 8))))))))
(keyword user-namespace (nano-id 8)))]
(try
(keyword-is-valid-edn! k)
k
(catch :default _e
(js/console.error "Generating backup db-ident for keyword" (str k))
(let [n (->> (filter #(re-find #"[0-9a-zA-Z-]{1}" %) (seq n))
(apply str))
k (if (seq n)
(keyword user-namespace n)
(keyword user-namespace (nano-id 8)))]
(keyword-is-valid-edn! k)
k)))))

View File

@ -6,4 +6,12 @@
(is (= "Whiteboard-Object"
;; Example from docs graph
(name (db-ident/create-db-ident-from-name "user.class" "Whiteboard/Object")))
"ident names must not have '/' because it is a special symbol for the reader"))
"ident names must not have '/' because it is a special symbol for the reader")
;; https://github.com/logseq/db-test/issues/4
(is (= "Deep-Neural-Networks-DNN"
(name (db-ident/create-db-ident-from-name "user.class" "Deep Neural Networks (DNN)")))
"ident names don't fail on special characters like parenthesis")
(is (seq (name (db-ident/create-db-ident-from-name "user.class" "123")))
"ident names can only have numbers"))