/
db.cljc
1667 lines (1433 loc) · 61.1 KB
/
db.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns ^:no-doc ^:lean-ns datascript.db
(:require
#?(:cljs [goog.array :as garray])
[clojure.walk]
[clojure.data]
#?(:clj [datascript.inline :refer [update]])
[datascript.lru :as lru]
[me.tonsky.persistent-sorted-set :as set]
[me.tonsky.persistent-sorted-set.arrays :as arrays])
#?(:clj (:import clojure.lang.IFn$OOL))
#?(:cljs (:require-macros [datascript.db :refer [case-tree combine-cmp cond+ defcomp defrecord-updatable int-compare raise]]))
(:refer-clojure :exclude [seqable? #?(:clj update)]))
#?(:clj (set! *warn-on-reflection* true))
;; ----------------------------------------------------------------------------
#?(:cljs
(do
(def Exception js/Error)
(def IllegalArgumentException js/Error)
(def UnsupportedOperationException js/Error)))
(def ^:const e0 0)
(def ^:const tx0 0x20000000)
(def ^:const emax 0x7FFFFFFF)
(def ^:const txmax 0x7FFFFFFF)
(def ^:const implicit-schema {:db/ident {:db/unique :db.unique/identity}})
;; ----------------------------------------------------------------------------
#?(:clj
(defmacro raise [& fragments]
(let [msgs (butlast fragments)
data (last fragments)]
`(throw (ex-info (str ~@(map (fn [m#] (if (string? m#) m# (list 'pr-str m#))) msgs)) ~data)))))
(defn #?@(:clj [^Boolean seqable?]
:cljs [^boolean seqable?])
[x]
(and (not (string? x))
#?(:cljs (or (cljs.core/seqable? x)
(arrays/array? x))
:clj (or (seq? x)
(instance? clojure.lang.Seqable x)
(nil? x)
(instance? Iterable x)
(arrays/array? x)
(instance? java.util.Map x)))))
#?(:clj
(defmacro cond+ [& clauses]
(when-some [[test expr & rest] clauses]
(case test
:do `(do ~expr (cond+ ~@rest))
:let `(let ~expr (cond+ ~@rest))
:some `(or ~expr (cond+ ~@rest))
`(if ~test ~expr (cond+ ~@rest))))))
#?(:clj
(defmacro some-of
([] nil)
([x] x)
([x & more]
`(let [x# ~x] (if (nil? x#) (some-of ~@more) x#)))))
(def conjv (fnil conj []))
(def conjs (fnil conj #{}))
(defn reduce-indexed
"Same as reduce, but `f` takes [acc el idx]"
[f init xs]
(first
(reduce
(fn [[acc idx] x]
(let [res (f acc x idx)]
(if (reduced? res)
(reduced [res idx])
[res (inc idx)])))
[init 0]
xs)))
;; ----------------------------------------------------------------------------
;; macros and funcs to support writing defrecords and updating
;; (replacing) builtins, i.e., Object/hashCode, IHashEq hasheq, etc.
;; code taken from prismatic:
;; https://github.com/Prismatic/schema/commit/e31c419c56555c83ef9ee834801e13ef3c112597
;;
(defn- cljs-env?
"Take the &env from a macro, and tell whether we are expanding into cljs."
[env]
(boolean (:ns env)))
#?(:clj
(defmacro if-cljs
"Return then if we are generating cljs code and else for Clojure code.
https://groups.google.com/d/msg/clojurescript/iBY5HaQda4A/w1lAQi9_AwsJ"
[then else]
(if (cljs-env? &env) then else)))
(defn combine-hashes [x y]
#?(:clj (clojure.lang.Util/hashCombine x y)
:cljs (hash-combine x y)))
#?(:clj
(defn- get-sig [method]
;; expects something like '(method-symbol [arg arg arg] ...)
;; if the thing matches, returns [fully-qualified-symbol arity], otherwise nil
(and (sequential? method)
(symbol? (first method))
(vector? (second method))
(let [sym (first method)
ns (or (some->> sym resolve meta :ns str) "clojure.core")]
[(symbol ns (name sym)) (-> method second count)]))))
#?(:clj
(defn- dedupe-interfaces [deftype-form]
;; get the interfaces list, remove any duplicates, similar to remove-nil-implements in potemkin
;; verified w/ deftype impl in compiler:
;; (deftype* tagname classname [fields] :implements [interfaces] :tag tagname methods*)
(let [[deftype* tagname classname fields implements interfaces & rest] deftype-form]
(when (or (not= deftype* 'deftype*) (not= implements :implements))
(throw (IllegalArgumentException. "deftype-form mismatch")))
(list* deftype* tagname classname fields implements (vec (distinct interfaces)) rest))))
#?(:clj
(defn- make-record-updatable-clj [name fields & impls]
(let [impl-map (->> impls (map (juxt get-sig identity)) (filter first) (into {}))
body (macroexpand-1 (list* 'defrecord name fields impls))]
(clojure.walk/postwalk
(fn [form]
(if (and (sequential? form) (= 'deftype* (first form)))
(->> form
dedupe-interfaces
(remove (fn [method]
(when-some [impl (-> method get-sig impl-map)]
(not= method impl)))))
form))
body))))
#?(:clj
(defn- make-record-updatable-cljs [name fields & impls]
`(do
(defrecord ~name ~fields)
(extend-type ~name ~@impls))))
#?(:clj
(defmacro defrecord-updatable [name fields & impls]
`(if-cljs
~(apply make-record-updatable-cljs name fields impls)
~(apply make-record-updatable-clj name fields impls))))
;; ----------------------------------------------------------------------------
(declare hash-datom equiv-datom seq-datom nth-datom assoc-datom val-at-datom)
(defprotocol IDatom
(datom-tx [this])
(datom-added [this])
(datom-get-idx [this])
(datom-set-idx [this value]))
(deftype Datom #?(:clj [^int e a v ^int tx ^:unsynchronized-mutable ^int idx ^:unsynchronized-mutable ^int _hash]
:cljs [^number e a v ^number tx ^:mutable ^number idx ^:mutable ^number _hash])
IDatom
(datom-tx [d] (if (pos? tx) tx (- tx)))
(datom-added [d] (pos? tx))
(datom-get-idx [_] idx)
(datom-set-idx [_ value] (set! idx (int value)))
#?@(:cljs
[IHash
(-hash [d] (if (zero? _hash)
(set! _hash (hash-datom d))
_hash))
IEquiv
(-equiv [d o] (and (instance? Datom o) (equiv-datom d o)))
ISeqable
(-seq [d] (seq-datom d))
ILookup
(-lookup [d k] (val-at-datom d k nil))
(-lookup [d k nf] (val-at-datom d k nf))
IIndexed
(-nth [this i] (nth-datom this i))
(-nth [this i not-found] (nth-datom this i not-found))
IAssociative
(-assoc [d k v] (assoc-datom d k v))
IPrintWithWriter
(-pr-writer [d writer opts]
(pr-sequential-writer writer pr-writer
"#datascript/Datom [" " " "]"
opts [(.-e d) (.-a d) (.-v d) (datom-tx d) (datom-added d)]))]
:clj
[Object
(hashCode [d]
(if (zero? _hash)
(let [h (int (hash-datom d))]
(set! _hash h)
h)
_hash))
(toString [d] (pr-str d))
clojure.lang.IHashEq
(hasheq [d] (.hashCode d))
clojure.lang.Seqable
(seq [d] (seq-datom d))
clojure.lang.IPersistentCollection
(equiv [d o] (and (instance? Datom o) (equiv-datom d o)))
(empty [d] (throw (UnsupportedOperationException. "empty is not supported on Datom")))
(count [d] 5)
(cons [d [k v]] (assoc-datom d k v))
clojure.lang.Indexed
(nth [this i] (nth-datom this i))
(nth [this i not-found] (nth-datom this i not-found))
clojure.lang.ILookup
(valAt [d k] (val-at-datom d k nil))
(valAt [d k nf] (val-at-datom d k nf))
clojure.lang.Associative
(entryAt [d k] (some->> (val-at-datom d k nil) (clojure.lang.MapEntry k)))
(containsKey [e k] (#{:e :a :v :tx :added} k))
(assoc [d k v] (assoc-datom d k v))]
))
#?(:cljs (goog/exportSymbol "datascript.db.Datom" Datom))
(defn ^Datom datom
([e a v] (Datom. e a v tx0 0 0))
([e a v tx] (Datom. e a v tx 0 0))
([e a v tx added] (Datom. e a v (if added tx (- tx)) 0 0)))
(defn datom? [x] (instance? Datom x))
(defn- hash-datom [^Datom d]
(-> (hash (.-e d))
(combine-hashes (hash (.-a d)))
(combine-hashes (hash (.-v d)))))
(defn- equiv-datom [^Datom d ^Datom o]
(and (== (.-e d) (.-e o))
(= (.-a d) (.-a o))
(= (.-v d) (.-v o))))
(defn- seq-datom [^Datom d]
(list (.-e d) (.-a d) (.-v d) (datom-tx d) (datom-added d)))
;; keep it fast by duplicating for both keyword and string cases
;; instead of using sets or some other matching func
(defn- val-at-datom [^Datom d k not-found]
(case k
:e (.-e d) "e" (.-e d)
:a (.-a d) "a" (.-a d)
:v (.-v d) "v" (.-v d)
:tx (datom-tx d)
"tx" (datom-tx d)
:added (datom-added d)
"added" (datom-added d)
not-found))
(defn- nth-datom
([^Datom d ^long i]
(case i
0 (.-e d)
1 (.-a d)
2 (.-v d)
3 (datom-tx d)
4 (datom-added d)
#?(:clj (throw (IndexOutOfBoundsException.))
:cljs (throw (js/Error. (str "Datom/-nth: Index out of bounds: " i))))))
([^Datom d ^long i not-found]
(case i
0 (.-e d)
1 (.-a d)
2 (.-v d)
3 (datom-tx d)
4 (datom-added d)
not-found)))
(defn- ^Datom assoc-datom [^Datom d k v]
(case k
:e (datom v (.-a d) (.-v d) (datom-tx d) (datom-added d))
:a (datom (.-e d) v (.-v d) (datom-tx d) (datom-added d))
:v (datom (.-e d) (.-a d) v (datom-tx d) (datom-added d))
:tx (datom (.-e d) (.-a d) (.-v d) v (datom-added d))
:added (datom (.-e d) (.-a d) (.-v d) (datom-tx d) v)
(throw (IllegalArgumentException. (str "invalid key for #datascript/Datom: " k)))))
;; printing and reading
;; #datomic/DB {:schema <map>, :datoms <vector of [e a v tx]>}
(defn ^Datom datom-from-reader [vec]
(apply datom vec))
#?(:clj
(defmethod print-method Datom [^Datom d, ^java.io.Writer w]
(.write w (str "#datascript/Datom "))
(binding [*out* w]
(pr [(.-e d) (.-a d) (.-v d) (datom-tx d) (datom-added d)]))))
;; ----------------------------------------------------------------------------
;; datom cmp macros/funcs
;;
#?(:clj
(defmacro combine-cmp [& comps]
(loop [comps (reverse comps)
res (num 0)]
(if (not-empty comps)
(recur
(next comps)
`(let [c# ~(first comps)]
(if (== 0 c#)
~res
c#)))
res))))
#?(:clj
(defn- -case-tree [queries variants]
(if queries
(let [v1 (take (/ (count variants) 2) variants)
v2 (drop (/ (count variants) 2) variants)]
(list 'if (first queries)
(-case-tree (next queries) v1)
(-case-tree (next queries) v2)))
(first variants))))
#?(:clj
(defmacro case-tree [qs vs]
(-case-tree qs vs)))
(defn cmp
#?(:clj
{:inline
(fn [x y]
`(let [x# ~x y# ~y]
(if (nil? x#) 0 (if (nil? y#) 0 (long (compare x# y#))))))})
^long [x y]
(if (nil? x) 0 (if (nil? y) 0 (long (compare x y)))))
(defn class-identical?
#?(:clj {:inline (fn [x y] `(identical? (class ~x) (class ~y)))})
[x y]
#?(:clj (identical? (class x) (class y))
:cljs (identical? (type x) (type y))))
#?(:clj
(defn class-name
{:inline
(fn [x]
`(let [^Object x# ~x]
(if (nil? x#) x# (.getName (. x# (getClass))))))}
^String [^Object x] (if (nil? x) x (.getName (. x (getClass))))))
(defn class-compare
^long [x y]
#?(:clj (long (compare (class-name x) (class-name y)))
:cljs (garray/defaultCompare (type->str (type x)) (type->str (type y)))))
#?(:clj
(defmacro int-compare [x y]
`(if-cljs
(- ~x ~y)
(long (Integer/compare ~x ~y)))))
(defn ihash
{:inline (fn [x] `(. clojure.lang.Util (hasheq ~x)))}
^long [x]
#?(:clj (. clojure.lang.Util (hasheq x))
:cljs (hash x)))
(defn value-compare
^long [x y]
(try
(cond
(= x y) 0
#?@(:clj [(instance? Number x) (clojure.lang.Numbers/compare x y)])
#?@(:clj [(instance? Comparable x) (.compareTo ^Comparable x y)]
:cljs [(satisfies? IComparable x) (-compare x y)])
(not (class-identical? x y)) (class-compare x y)
#?@(:cljs [(or (number? x) (string? x) (array? x) (true? x) (false? x)) (garray/defaultCompare x y)])
:else (int-compare (ihash x) (ihash y)))
(catch #?(:clj ClassCastException :cljs js/Error) e
(if (not (class-identical? x y))
(class-compare x y)
(throw e)))))
(defn value-cmp
#?(:clj
{:inline
(fn [x y]
`(let [x# ~x y# ~y]
(if (nil? x#) 0 (if (nil? y#) 0 (value-compare x# y#)))))})
^long [x y]
(if (nil? x)
0
(if (nil? y)
0
(value-compare x y))))
;; Slower cmp-* fns allows for datom fields to be nil.
;; Such datoms come from slice method where they are used as boundary markers.
#?(:clj
(defmacro defcomp [sym [arg1 arg2] & body]
(let [a1 (with-meta arg1 {})
a2 (with-meta arg2 {})]
`(if-cljs
(defn ~sym [~arg1 ~arg2]
~@body)
(def ~sym
(reify
java.util.Comparator
(compare [_# ~a1 ~a2]
(let [~arg1 ~arg1 ~arg2 ~arg2]
~@body))
clojure.lang.IFn
(invoke [this# ~a1 ~a2]
(.compare this# ~a1 ~a2))
IFn$OOL
(invokePrim [this# ~a1 ~a2]
(.compare this# ~a1 ~a2))))))))
(defcomp cmp-datoms-eavt ^long [^Datom d1, ^Datom d2]
(combine-cmp
(int-compare (.-e d1) (.-e d2))
(cmp (.-a d1) (.-a d2))
(value-cmp (.-v d1) (.-v d2))
(int-compare (datom-tx d1) (datom-tx d2))))
(defcomp cmp-datoms-aevt ^long [^Datom d1, ^Datom d2]
(combine-cmp
(cmp (.-a d1) (.-a d2))
(int-compare (.-e d1) (.-e d2))
(value-cmp (.-v d1) (.-v d2))
(int-compare (datom-tx d1) (datom-tx d2))))
(defcomp cmp-datoms-avet ^long [^Datom d1, ^Datom d2]
(combine-cmp
(cmp (.-a d1) (.-a d2))
(value-cmp (.-v d1) (.-v d2))
(int-compare (.-e d1) (.-e d2))
(int-compare (datom-tx d1) (datom-tx d2))))
;; fast versions without nil checks
(defn- cmp-attr-quick
#?(:clj
{:inline
(fn [a1 a2]
`(long (.compareTo ~(with-meta a1 {:tag "Comparable"}) ~a2)))})
^long [a1 a2]
;; either both are keywords or both are strings
#?(:cljs
(if (keyword? a1)
(-compare a1 a2)
(garray/defaultCompare a1 a2))
:clj
(.compareTo ^Comparable a1 a2)))
(defcomp cmp-datoms-eav-quick ^long [^Datom d1, ^Datom d2]
(combine-cmp
(int-compare (.-e d1) (.-e d2))
(cmp-attr-quick (.-a d1) (.-a d2))
(value-compare (.-v d1) (.-v d2))))
(defcomp cmp-datoms-eavt-quick ^long [^Datom d1, ^Datom d2]
(combine-cmp
(int-compare (.-e d1) (.-e d2))
(cmp-attr-quick (.-a d1) (.-a d2))
(value-compare (.-v d1) (.-v d2))
(int-compare (datom-tx d1) (datom-tx d2))))
(defcomp cmp-datoms-aevt-quick ^long [^Datom d1, ^Datom d2]
(combine-cmp
(cmp-attr-quick (.-a d1) (.-a d2))
(int-compare (.-e d1) (.-e d2))
(value-compare (.-v d1) (.-v d2))
(int-compare (datom-tx d1) (datom-tx d2))))
(defcomp cmp-datoms-avet-quick ^long [^Datom d1, ^Datom d2]
(combine-cmp
(cmp-attr-quick (.-a d1) (.-a d2))
(value-compare (.-v d1) (.-v d2))
(int-compare (.-e d1) (.-e d2))
(int-compare (datom-tx d1) (datom-tx d2))))
(defn- diff-sorted [a b cmp]
(loop [only-a []
only-b []
both []
a a
b b]
(cond
(empty? a) [(not-empty only-a) (not-empty (into only-b b)) (not-empty both)]
(empty? b) [(not-empty (into only-a a)) (not-empty only-b) (not-empty both)]
:else
(let [first-a (first a)
first-b (first b)
diff (try
(cmp first-a first-b)
(catch #?(:clj ClassCastException :cljs js/Error) _
:incomparable))]
(cond
(= diff :incomparable) (recur (conj only-a first-a) (conj only-b first-b) both (next a) (next b))
(== diff 0) (recur only-a only-b (conj both first-a) (next a) (next b))
(< diff 0) (recur (conj only-a first-a) only-b both (next a) b)
(> diff 0) (recur only-a (conj only-b first-b) both a (next b)))))))
;; ----------------------------------------------------------------------------
(declare hash-db hash-fdb equiv-db empty-db resolve-datom validate-attr components->pattern indexing?)
#?(:cljs (declare pr-db))
;;;;;;;;;; Searching
(defprotocol ISearch
(-search [data pattern]))
(defn- ^Datom fsearch [data pattern]
(first (-search data pattern)))
(defprotocol IIndexAccess
(-datoms [db index components])
(-seek-datoms [db index components])
(-rseek-datoms [db index components])
(-index-range [db attr start end]))
(defn validate-indexed [db index components]
(when (= index :avet)
(when-some [attr (first components)]
(when-not (indexing? db attr)
(raise "Attribute " attr " should be marked as :db/index true"
{:error :index-access :index :avet :components components})))))
(defprotocol IDB
(-schema [db])
(-attrs-by [db property]))
;; ----------------------------------------------------------------------------
(defn db-transient [db]
(-> db
(update :eavt transient)
(update :aevt transient)
(update :avet transient)))
(defn db-persistent! [db]
(-> db
(update :eavt persistent!)
(update :aevt persistent!)
(update :avet persistent!)))
#?(:clj
(defn vpred [v]
(cond
(string? v) (fn [x] (if (string? x) (.equals ^String v x) false))
(int? v) (fn [x] (if (int? x) (= (long v) (long x)) false))
(keyword? v) (fn [x] (.equals ^Object v x))
(nil? v) (fn [x] (nil? x))
:else (fn [x] (= v x)))))
(defrecord-updatable DB [schema eavt aevt avet max-eid max-tx rschema pull-patterns pull-attrs hash]
#?@(:cljs
[IHash (-hash [db] (hash-db db))
IEquiv (-equiv [db other] (equiv-db db other))
IReversible (-rseq [db] (-rseq (.-eavt db)))
ICounted (-count [db] (count (.-eavt db)))
IEmptyableCollection (-empty [db] (with-meta (empty-db (.-schema db)) (meta db)))
IPrintWithWriter (-pr-writer [db w opts] (pr-db db w opts))
IEditableCollection (-as-transient [db] (db-transient db))
ITransientCollection (-conj! [db key] (throw (ex-info "datascript.DB/conj! is not supported" {})))
(-persistent! [db] (db-persistent! db))]
:clj
[Object (hashCode [db] (hash-db db))
clojure.lang.IHashEq (hasheq [db] (hash-db db))
clojure.lang.IPersistentCollection
(count [db] (count eavt))
(equiv [db other] (equiv-db db other))
clojure.lang.IEditableCollection
(empty [db] (with-meta (empty-db schema) (meta db)))
(asTransient [db] (db-transient db))
clojure.lang.ITransientCollection
(conj [db key] (throw (ex-info "datascript.DB/conj! is not supported" {})))
(persistent [db] (db-persistent! db))])
IDB
(-schema [db] (.-schema db))
(-attrs-by [db property] ((.-rschema db) property))
ISearch
(-search [db pattern]
(let [[e a v tx] pattern
eavt (.-eavt db)
aevt (.-aevt db)
avet (.-avet db)
pred #?(:clj (vpred v)
:cljs #(= v %))
multival? (contains? (-attrs-by db :db.cardinality/many) a)]
(case-tree [e a (some? v) tx]
[(set/slice eavt (datom e a v tx) (datom e a v tx)) ;; e a v tx
(set/slice eavt (datom e a v tx0) (datom e a v txmax)) ;; e a v _
(->> (set/slice eavt (datom e a nil tx0) (datom e a nil txmax)) ;; e a _ tx
(->Eduction (filter (fn [^Datom d] (= tx (datom-tx d))))))
(set/slice eavt (datom e a nil tx0) (datom e a nil txmax)) ;; e a _ _
(->> (set/slice eavt (datom e nil nil tx0) (datom e nil nil txmax)) ;; e _ v tx
(->Eduction (filter (fn [^Datom d] (and (pred (.-v d))
(= tx (datom-tx d)))))))
(->> (set/slice eavt (datom e nil nil tx0) (datom e nil nil txmax)) ;; e _ v _
(->Eduction (filter (fn [^Datom d] (pred (.-v d))))))
(->> (set/slice eavt (datom e nil nil tx0) (datom e nil nil txmax)) ;; e _ _ tx
(->Eduction (filter (fn [^Datom d] (= tx (datom-tx d))))))
(set/slice eavt (datom e nil nil tx0) (datom e nil nil txmax)) ;; e _ _ _
(if (indexing? db a) ;; _ a v tx
(->> (set/slice avet (datom e0 a v tx0) (datom emax a v txmax))
(->Eduction (filter (fn [^Datom d] (= tx (datom-tx d))))))
(->> (set/slice aevt (datom e0 a nil tx0) (datom emax a nil txmax))
(->Eduction (filter (fn [^Datom d] (and (pred (.-v d))
(= tx (datom-tx d))))))))
(if (indexing? db a) ;; _ a v _
(set/slice avet (datom e0 a v tx0) (datom emax a v txmax))
(->> (set/slice aevt (datom e0 a nil tx0) (datom emax a nil txmax))
(->Eduction (filter (fn [^Datom d] (pred (.-v d)))))))
(->> (set/slice aevt (datom e0 a nil tx0) (datom emax a nil txmax)) ;; _ a _ tx
(->Eduction (filter (fn [^Datom d] (= tx (datom-tx d))))))
(set/slice aevt (datom e0 a nil tx0) (datom emax a nil txmax)) ;; _ a _ _
(filter (fn [^Datom d] (and (pred (.-v d))
(= tx (datom-tx d)))) eavt) ;; _ _ v tx
(filter (fn [^Datom d] (pred (.-v d))) eavt) ;; _ _ v
(filter (fn [^Datom d] (= tx (datom-tx d))) eavt) ;; _ _ _ tx
eavt]))) ;; _ _ _ _
IIndexAccess
(-datoms [db index cs]
(validate-indexed db index cs)
(set/slice (get db index) (components->pattern db index cs e0 tx0) (components->pattern db index cs emax txmax)))
(-seek-datoms [db index cs]
(validate-indexed db index cs)
(set/slice (get db index) (components->pattern db index cs e0 tx0) (datom emax nil nil txmax)))
(-rseek-datoms [db index cs]
(validate-indexed db index cs)
(set/rslice (get db index) (components->pattern db index cs emax txmax) (datom e0 nil nil tx0)))
(-index-range [db attr start end]
(validate-indexed db :avet [attr])
(validate-attr attr (list '-index-range 'db attr start end))
(set/slice (.-avet db)
(resolve-datom db nil attr start nil e0 tx0)
(resolve-datom db nil attr end nil emax txmax)))
clojure.data/EqualityPartition
(equality-partition [x] :datascript/db)
clojure.data/Diff
(diff-similar [a b]
(diff-sorted (:eavt a) (:eavt b) cmp-datoms-eav-quick)))
(defn db? [x]
#?(:clj
(or
(and x
(instance? datascript.db.ISearch x)
(instance? datascript.db.IIndexAccess x)
(instance? datascript.db.IDB x))
(and (satisfies? ISearch x)
(satisfies? IIndexAccess x)
(satisfies? IDB x)))
:cljs
(and (satisfies? ISearch x)
(satisfies? IIndexAccess x)
(satisfies? IDB x))))
;; ----------------------------------------------------------------------------
(defrecord-updatable FilteredDB [unfiltered-db pred hash]
#?@(:cljs
[IHash (-hash [db] (hash-fdb db))
IEquiv (-equiv [db other] (equiv-db db other))
ICounted (-count [db] (count (-datoms db :eavt [])))
IPrintWithWriter (-pr-writer [db w opts] (pr-db db w opts))
IEmptyableCollection (-empty [_] (throw (js/Error. "-empty is not supported on FilteredDB")))
ILookup (-lookup ([_ _] (throw (js/Error. "-lookup is not supported on FilteredDB")))
([_ _ _] (throw (js/Error. "-lookup is not supported on FilteredDB"))))
IAssociative (-contains-key? [_ _] (throw (js/Error. "-contains-key? is not supported on FilteredDB")))
(-assoc [_ _ _] (throw (js/Error. "-assoc is not supported on FilteredDB")))]
:clj
[Object (hashCode [db] (hash-fdb db))
clojure.lang.IHashEq (hasheq [db] (hash-fdb db))
clojure.lang.IPersistentCollection
(count [db] (count (-datoms db :eavt [])))
(equiv [db o] (equiv-db db o))
(cons [db [k v]] (throw (UnsupportedOperationException. "cons is not supported on FilteredDB")))
(empty [db] (throw (UnsupportedOperationException. "empty is not supported on FilteredDB")))
clojure.lang.ILookup (valAt [db k] (throw (UnsupportedOperationException. "valAt/2 is not supported on FilteredDB")))
(valAt [db k nf] (throw (UnsupportedOperationException. "valAt/3 is not supported on FilteredDB")))
clojure.lang.IKeywordLookup (getLookupThunk [db k]
(throw (UnsupportedOperationException. "getLookupThunk is not supported on FilteredDB")))
clojure.lang.Associative
(containsKey [e k] (throw (UnsupportedOperationException. "containsKey is not supported on FilteredDB")))
(entryAt [db k] (throw (UnsupportedOperationException. "entryAt is not supported on FilteredDB")))
(assoc [db k v] (throw (UnsupportedOperationException. "assoc is not supported on FilteredDB")))])
IDB
(-schema [db]
(-schema (.-unfiltered-db db)))
(-attrs-by [db property]
(-attrs-by (.-unfiltered-db db) property))
ISearch
(-search [db pattern]
(filter (.-pred db) (-search (.-unfiltered-db db) pattern)))
IIndexAccess
(-datoms [db index cs]
(filter (.-pred db) (-datoms (.-unfiltered-db db) index cs)))
(-seek-datoms [db index cs]
(filter (.-pred db) (-seek-datoms (.-unfiltered-db db) index cs)))
(-rseek-datoms [db index cs]
(filter (.-pred db) (-rseek-datoms (.-unfiltered-db db) index cs)))
(-index-range [db attr start end]
(filter (.-pred db) (-index-range (.-unfiltered-db db) attr start end))))
(defn unfiltered-db ^DB [db]
(if (instance? FilteredDB db)
(.-unfiltered-db ^FilteredDB db)
db))
;; ----------------------------------------------------------------------------
(defn attr->properties [k v]
(case v
:db.unique/identity [:db/unique :db.unique/identity :db/index]
:db.unique/value [:db/unique :db.unique/value :db/index]
:db.cardinality/many [:db.cardinality/many]
:db.type/ref [:db.type/ref :db/index]
(cond
(and (= :db/isComponent k) (true? v)) [:db/isComponent]
(and (= :db/index k) (true? v)) [:db/index]
(= :db/tupleAttrs k) [:db.type/tuple :db/index]
:else [])))
(defn attr-tuples
"e.g. :reg/semester => #{:reg/semester+course+student ...}"
[schema rschema]
(reduce
(fn [m tuple-attr] ;; e.g. :reg/semester+course+student
(reduce-indexed
(fn [m src-attr idx] ;; e.g. :reg/semester
(update m src-attr assoc tuple-attr idx))
m
(-> schema (get tuple-attr) :db/tupleAttrs)))
{}
(:db.type/tuple rschema)))
(defn- rschema
":db/unique => #{attr ...}
:db.unique/identity => #{attr ...}
:db.unique/value => #{attr ...}
:db/index => #{attr ...}
:db.cardinality/many => #{attr ...}
:db.type/ref => #{attr ...}
:db/isComponent => #{attr ...}
:db.type/tuple => #{attr ...}
:db/attrTuples => {attr => {tuple-attr => idx}}"
[schema]
(let [rschema (reduce-kv
(fn [rschema attr attr-schema]
(reduce-kv
(fn [rschema key value]
(reduce
(fn [rschema prop]
(update rschema prop conjs attr))
rschema (attr->properties key value)))
rschema attr-schema))
{} schema)]
(assoc rschema :db/attrTuples (attr-tuples schema rschema))))
(defn- validate-schema-key [a k v expected]
(when-not (or (nil? v)
(contains? expected v))
(throw (ex-info (str "Bad attribute specification for " (pr-str {a {k v}}) ", expected one of " expected)
{:error :schema/validation
:attribute a
:key k
:value v}))))
(defn- validate-schema [schema]
(doseq [[a kv] schema]
;; isComponent
(let [comp? (:db/isComponent kv false)]
(validate-schema-key a :db/isComponent (:db/isComponent kv) #{true false})
(when (and comp? (not= (:db/valueType kv) :db.type/ref))
(raise "Bad attribute specification for " a ": {:db/isComponent true} should also have {:db/valueType :db.type/ref}"
{:error :schema/validation
:attribute a
:key :db/isComponent})))
(validate-schema-key a :db/unique (:db/unique kv) #{:db.unique/value :db.unique/identity})
(validate-schema-key a :db/valueType (:db/valueType kv) #{:db.type/ref :db.type/tuple})
(validate-schema-key a :db/cardinality (:db/cardinality kv) #{:db.cardinality/one :db.cardinality/many})
;; tuple should have tupleAttrs
(when (and (= :db.type/tuple (:db/valueType kv))
(not (contains? kv :db/tupleAttrs)))
(raise "Bad attribute specification for " a ": {:db/valueType :db.type/tuple} should also have :db/tupleAttrs"
{:error :schema/validation
:attribute a
:key :db/valueType}))
;; :db/tupleAttrs is a non-empty sequential coll
(when (contains? kv :db/tupleAttrs)
(let [ex-data {:error :schema/validation
:attribute a
:key :db/tupleAttrs}]
(when (= :db.cardinality/many (:db/cardinality kv))
(raise a " has :db/tupleAttrs, must be :db.cardinality/one" ex-data))
(let [attrs (:db/tupleAttrs kv)]
(when-not (sequential? attrs)
(raise a " :db/tupleAttrs must be a sequential collection, got: " attrs ex-data))
(when (empty? attrs)
(raise a " :db/tupleAttrs can’t be empty" ex-data))
(doseq [attr attrs
:let [ex-data (assoc ex-data :value attr)]]
(when (contains? (get schema attr) :db/tupleAttrs)
(raise a " :db/tupleAttrs can’t depend on another tuple attribute: " attr ex-data))
(when (= :db.cardinality/many (:db/cardinality (get schema attr)))
(raise a " :db/tupleAttrs can’t depend on :db.cardinality/many attribute: " attr ex-data))))))))
(defn ^DB empty-db
([] (empty-db nil))
([schema]
{:pre [(or (nil? schema) (map? schema))]}
(validate-schema schema)
(map->DB
{:schema schema
:rschema (rschema (merge implicit-schema schema))
:eavt (set/sorted-set-by cmp-datoms-eavt)
:aevt (set/sorted-set-by cmp-datoms-aevt)
:avet (set/sorted-set-by cmp-datoms-avet)
:max-eid e0
:max-tx tx0
:pull-patterns (lru/cache 100)
:pull-attrs (lru/cache 100)
:hash (atom 0)})))
(defn- init-max-eid [eavt]
(or (-> (set/rslice eavt (datom (dec tx0) nil nil txmax) (datom e0 nil nil tx0))
(first)
(:e))
e0))
(defn ^DB init-db
([datoms] (init-db datoms nil))
([datoms schema]
(when-some [not-datom (first (drop-while datom? datoms))]
(raise "init-db expects list of Datoms, got " (type not-datom)
{:error :init-db}))
(validate-schema schema)
(let [rschema (rschema (merge implicit-schema schema))
indexed (:db/index rschema)
arr (cond-> datoms
(not (arrays/array? datoms)) (arrays/into-array))
_ (arrays/asort arr cmp-datoms-eavt-quick)
eavt (set/from-sorted-array cmp-datoms-eavt arr)
_ (arrays/asort arr cmp-datoms-aevt-quick)
aevt (set/from-sorted-array cmp-datoms-aevt arr)
avet-datoms (filter (fn [^Datom d] (contains? indexed (.-a d))) datoms)
avet-arr (to-array avet-datoms)
_ (arrays/asort avet-arr cmp-datoms-avet-quick)
avet (set/from-sorted-array cmp-datoms-avet avet-arr)
max-eid (init-max-eid eavt)
max-tx (transduce (map (fn [^Datom d] (datom-tx d))) max tx0 eavt)]
(map->DB {
:schema schema
:rschema rschema
:eavt eavt
:aevt aevt
:avet avet
:max-eid max-eid
:max-tx max-tx
:pull-patterns (lru/cache 100)
:pull-attrs (lru/cache 100)
:hash (atom 0)}))))
(defn restore-db [{:keys [schema eavt aevt avet max-eid max-tx]}]
(map->DB
{:schema schema
:rschema (rschema (merge implicit-schema schema))
:eavt eavt
:aevt aevt
:avet avet
:max-eid max-eid
:max-tx max-tx
:pull-patterns (lru/cache 100)
:pull-attrs (lru/cache 100)
:hash (atom 0)}))
(defn- equiv-db-index [x y]
(loop [xs (seq x)
ys (seq y)]
(cond
(nil? xs) (nil? ys)
(= (first xs) (first ys)) (recur (next xs) (next ys))
:else false)))
(defn- hash-db [^DB db]
(let [h @(.-hash db)]
(if (zero? h)
(reset! (.-hash db) (combine-hashes (hash (.-schema db))
(hash (.-eavt db))))
h)))
(defn- hash-fdb [^FilteredDB db]
(let [h @(.-hash db)
datoms (or (-datoms db :eavt []) #{})]
(if (zero? h)
(let [datoms (or (-datoms db :eavt []) #{})]
(reset! (.-hash db) (combine-hashes (hash (-schema db))
(hash-unordered-coll datoms))))
h)))
(defn- equiv-db [db other]
(and (or (instance? DB other) (instance? FilteredDB other))
(= (-schema db) (-schema other))
(equiv-db-index (-datoms db :eavt []) (-datoms other :eavt []))))
#?(:cljs
(defn pr-db [db w opts]
(-write w "#datascript/DB {")
(-write w ":schema ")
(pr-writer (-schema db) w opts)
(-write w ", :datoms ")
(pr-sequential-writer w
(fn [d w opts]
(pr-sequential-writer w pr-writer "[" " " "]" opts [(.-e d) (.-a d) (.-v d) (datom-tx d)]))
"[" " " "]" opts (-datoms db :eavt []))
(-write w "}")))
#?(:clj
(do
(defn pr-db [db, ^java.io.Writer w]
(.write w (str "#datascript/DB {"))
(.write w ":schema ")
(binding [*out* w]
(pr (-schema db))
(.write w ", :datoms [")
(apply pr (map (fn [^Datom d] [(.-e d) (.-a d) (.-v d) (datom-tx d)]) (-datoms db :eavt []))))
(.write w "]}"))
(defmethod print-method DB [db w] (pr-db db w))
(defmethod print-method FilteredDB [db w] (pr-db db w))
))
(defn db-from-reader [{:keys [schema datoms]}]
(init-db (map (fn [[e a v tx]] (datom e a v tx)) datoms) schema))
;; ----------------------------------------------------------------------------
(declare entid-strict entid-some ref?)
(defn- resolve-datom [db e a v t default-e default-tx]
(when a (validate-attr a (list 'resolve-datom 'db e a v t)))
(datom
(or (entid-some db e) default-e) ;; e
a ;; a
(if (and (some? v) (ref? db a)) ;; v
(entid-strict db v)
v)
(or (entid-some db t) default-tx))) ;; t
(defn- components->pattern [db index [c0 c1 c2 c3] default-e default-tx]