create_graph.cljs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. (ns create-graph
  2. "A script that creates or updates a DB graph given a sqlite.build EDN file.
  3. If the given graph already exists, the EDN file updates the graph."
  4. (:require ["fs" :as fs]
  5. ["path" :as node-path]
  6. [babashka.cli :as cli]
  7. [clojure.edn :as edn]
  8. [logseq.db :as ldb]
  9. [logseq.db.common.sqlite-cli :as sqlite-cli]
  10. [logseq.db.sqlite.export :as sqlite-export]
  11. [logseq.outliner.cli :as outliner-cli]
  12. [nbb.classpath :as cp]
  13. [nbb.core :as nbb]
  14. [validate-db]))
  15. (defn- resolve-path
  16. "If relative path, resolve with $ORIGINAL_PWD"
  17. [path]
  18. (if (node-path/isAbsolute path)
  19. path
  20. (node-path/join (or js/process.env.ORIGINAL_PWD ".") path)))
  21. (def spec
  22. "Options spec"
  23. {:help {:alias :h
  24. :desc "Print help"}
  25. :validate {:alias :v
  26. :desc "Validate db after creation"}
  27. :import {:alias :i
  28. :desc "Import edn file using sqlite-export"}})
  29. (defn -main [args]
  30. (let [{options :opts args' :args} (cli/parse-args args {:spec spec})
  31. [graph-dir edn-path] args'
  32. _ (when (or (nil? graph-dir) (nil? edn-path) (:help options))
  33. (println (str "Usage: $0 GRAPH-NAME EDN-PATH [OPTIONS]\nOptions:\n"
  34. (cli/format-opts {:spec spec})))
  35. (js/process.exit 1))
  36. init-conn-args (conj (sqlite-cli/->open-db-args graph-dir))
  37. sqlite-build-edn (merge (if (:import options) {} {:auto-create-ontology? true})
  38. (-> (resolve-path edn-path) fs/readFileSync str edn/read-string))
  39. graph-exists? (fs/existsSync (apply node-path/join init-conn-args))
  40. db-name (if (= 1 (count init-conn-args)) (first init-conn-args) (second init-conn-args))
  41. conn (apply outliner-cli/init-conn
  42. (conj init-conn-args {:classpath (cp/get-classpath) :import-type :cli/create-graph}))
  43. {:keys [init-tx block-props-tx misc-tx] :as _txs}
  44. (if (:import options)
  45. (sqlite-export/build-import sqlite-build-edn @conn {})
  46. (outliner-cli/build-blocks-tx sqlite-build-edn))]
  47. (println "Generating" (count (filter :block/name init-tx)) "pages and"
  48. (count (filter :block/title init-tx)) "blocks ...")
  49. ;; (fs/writeFileSync "txs.edn" (with-out-str (cljs.pprint/pprint _txs)))
  50. ;; (cljs.pprint/pprint _txs)
  51. (ldb/transact! conn init-tx)
  52. (when (seq block-props-tx) (ldb/transact! conn block-props-tx))
  53. (when (seq misc-tx) (ldb/transact! conn misc-tx))
  54. (println (if graph-exists? "Updated graph" "Created graph") (str db-name "!"))
  55. (when (:validate options)
  56. (validate-db/validate-db @conn db-name {:group-errors true :closed-maps true :humanize true}))))
  57. (when (= nbb/*file* (nbb/invoked-file))
  58. (-main *command-line-args*))