Datomic search query which sorts by date

After much fiddling I managed to create a datomic search query which

(a) identifies TODOs which reference the current page
(b) sort results by date

I thought I’d share it as I was quite pleased with getting the sorting behaviour right.

However, the sorting only works for SCHEDULED tasks as opposed to deadlines. Can anyone get dates to sort irrespective of whether the TODO is SCHEDULED or a DEADLINE?

(NB the ;; shows a line which has been commented out as it didn’t seem to affect the behaviour).

#+BEGIN_QUERY
  {:title "🔎 All todos tagged using current page"
   :query [
         :find (pull ?b [*])
         :in $ ?current-page ?start ?next
         :where
         [?p :page/name ?current-page]
         [?b :block/marker ?marker]
         [?b :block/ref-pages ?p]
        ;;  [(= "TODO" ?marker)]
        [?block :block/scheduled ?d]
        [?block :block/deadline ?d]
      [(> ?d ?start)]
      [(< ?d ?next)]
         ]
   :result-transform (fn [result]
                        (sort-by (fn [d]
                                   (get d :block/scheduled) ) result))

   :inputs [:current-page :today :7d-after]}
#+END_QUERY