clojurescriptdatascript

Why does this query return no results?


Given these definitions of a datascript db,

(def schema
  {:tag/name { :db/unique :db.unique/identity }
   :item/tag {:db/valueType   :db.type/ref
               :db/cardinality :db.cardinality/many}
   :outfit/item {:db/valueType   :db.type/ref
                 :db/cardinality :db.cardinality/many}}
)
(defonce conn (d/create-conn schema))

(defn new-entity! [conn attrs]
  (let [entity (merge attrs {:db/id -1})
        txn-result (d/transact! conn [entity])
        temp-ids (:tempids txn-result)]
    (temp-ids -1)))

(defonce init
  (let [tag1    (new-entity! conn {:tag/name "tag1"})
        item1   (new-entity! conn {:item/tag tag1})
        outfit1   (new-entity! conn {:outfit/item item1})]
    :ok))

If I run this devcard, I don't get any results:

(defcard find-by-tag-param
  "find items by tag"
  (d/q '[ :find ?item 
         :in ? ?tagname
         :where
         [ ?tag :tag/name ?tagname ]
         [ ?item :item/tag ?tag ]]
       @conn "tag1"))

Why does this query return no results?


Solution

  • For starters, your in clause should be :in $ ?tagname; The binding you have in there leaves you with no default database, meaning that nothing will match your query clauses.

    The $ symbol is a special symbol which gets used as the default database in the :where forms. You can use non-default databases by prefixing your :where clauses with the name-symbol of the alternate db (e.g. :in ?alt-db :where [?alt-db ?tag :tag/name ?tagname] ...).

    I haven't worked with dev cards, so it's possible there is something else needed to get this working, but fixing your query is the first step.