 (defn build-relation-db [db pattern]
   (let [search-pattern (mapv #(if (symbol? %) nil %) pattern)
         datoms         (d/-search db search-pattern)
-        attr+prop      (->> (map vector pattern ["e" "a" "v" "t"])
+        attr->prop     (->> (map vector pattern ["e" "a" "v" "t"])
                             (filter (fn [[s _]] (and (symbol? s)
-                                                     (not= '_ s)))))
-        props          (to-array (map second attr+prop))]
-    (Relation. (mapv first attr+prop)
-               (mapv (fn [el] (.map props #(aget el %))) datoms))))
+                                                     (not= '_ s))))
+                            (into {}))]
+    (Relation. attr->prop (vec datoms))))
 
 #_(build-relation-db (-> (d/empty-db)
                        (d/with [[:db/add 1 :name "Ivan"]

  (let [context (-q {'$ db}
                    '[[$ ?e :name "Ivan"]
                      [$ ?e :age ?a]])
        res (-collect [#js[]] (:rels context) '[?e ?a])]
;;    (.timeEnd js/console "search")  
    res))


                 (assoc! hash-table key (conj (get hash-table key '()) tuple))))
        (persistent! hash-table)))))

(defn join-tuples [t1 idxs1 t2 idxs2]
  (let [l1  (alength idxs1)
        l2  (alength idxs2)
        res (js/Array. (+ l1 l2))]
    (dotimes [i l1]
      (aset res i (aget t1 (aget idxs1 i)))) ;; FIXME aget
    (dotimes [i l2]
      (aset res (+ l1 i) (aget t2 (aget idxs2 i)))) ;; FIXME aget
    res))

(defn hash-join [rel1 rel2]
;;  (.time js/console "hash-join")
  (let [;; [rel1 rel2]   (if (< (count (:tuples rel1)) (count (:tuples rel2))) [rel1 rel2] [rel2 rel1])
        tuples1       (:tuples rel1)
        tuples2       (:tuples rel2)
        attrs1        (:attrs rel1)
        attrs2        (:attrs rel2)
        common-attrs  (vec (intersect-keys (:attrs rel1) (:attrs rel2)))
        common-idxs1  (map attrs1 common-attrs)
        common-idxs2  (map attrs2 common-attrs)
        keep-attrs1   (keys attrs1)
        keep-attrs2   (vec (set/difference (set (keys attrs2)) (set (keys attrs1))))
        keep-idxs1    (to-array (map attrs1 keep-attrs1))
        keep-idxs2    (to-array (map attrs2 keep-attrs2))
        
;;        _             (.time js/console "hash-attrs")
        hash          (hash-attrs common-idxs1 tuples1)
;;        _             (.timeEnd js/console "hash-attrs")
        
;;        _             (.time js/console "new-tuples")
