/
db.cljc
2181 lines (1920 loc) · 96 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 datahike.db
(:require
#?(:cljs [goog.array :as garray])
[clojure.walk]
[clojure.core.cache.wrapped :as cw]
[clojure.data]
#?(:clj [clojure.pprint :as pp])
[datahike.array :refer [a=]]
[datahike.index :refer [-slice -seq -count -all -persistent! -transient] :as di]
[datahike.datom :as dd :refer [datom datom-tx datom-added datom?]]
[datahike.constants :as c :refer [ue0 e0 tx0 utx0 emax txmax system-schema]]
[datahike.tools :refer [get-time case-tree raise] :as tools]
[datahike.schema :as ds]
[datahike.lru :refer [lru-datom-cache-factory]]
[me.tonsky.persistent-sorted-set.arrays :as arrays]
[datahike.config :as dc]
[environ.core :refer [env]]
[clojure.spec.alpha :as s]
[taoensso.timbre :refer [warn]])
#?(:cljs (:require-macros [datahike.db :refer [defrecord-updatable cond+]]
[datahike.datom :refer [combine-cmp datom]]
[datahike.tools :refer [case-tree raise]]))
(:refer-clojure :exclude [seqable?])
#?(:clj (:import [clojure.lang AMapEntry]
[java.util Date]
[datahike.datom Datom])))
;; ----------------------------------------------------------------------------
#?(:cljs
(do
(def Exception js/Error)
(def IllegalArgumentException js/Error)
(def UnsupportedOperationException js/Error)))
;; ----------------------------------------------------------------------------
(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)))))
;; ----------------------------------------------------------------------------
;; 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)))
#?(: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-let [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))))
;; ----------------------------------------------------------------------------
;;;;;;;;;; Searching
(defprotocol ISearch
(-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]))
(defprotocol IDB
(-schema [db])
(-rschema [db])
(-system-entities [db])
(-attrs-by [db property])
(-max-tx [db])
(-max-eid [db])
(-temporal-index? [db]) ;;deprecated
(-keep-history? [db])
(-config [db])
(-ref-for [db a-ident])
(-ident-for [db a-ref]))
(defprotocol IHistory
(-time-point [db])
(-origin [db]))
;; ----------------------------------------------------------------------------
(declare hash-datoms equiv-db empty-db resolve-datom validate-attr validate-attr-ident components->pattern indexing? no-history? multival? search-current-indices search-temporal-indices)
#?(:cljs (declare pr-db))
(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!)))
(defn- search-indices
"Assumes correct pattern form, i.e. refs for ref-database"
[eavt aevt avet pattern indexed? temporal-db?]
(let [[e a v tx added?] pattern]
(if (and (not temporal-db?) (false? added?))
'()
(case-tree [e a (some? v) tx]
[(-slice eavt (datom e a v tx) (datom e a v tx) :eavt) ;; e a v tx
(-slice eavt (datom e a v tx0) (datom e a v txmax) :eavt) ;; e a v _
(->> (-slice eavt (datom e a nil tx0) (datom e a nil txmax) :eavt) ;; e a _ tx
(filter (fn [^Datom d] (= tx (datom-tx d)))))
(-slice eavt (datom e a nil tx0) (datom e a nil txmax) :eavt) ;; e a _ _
(->> (-slice eavt (datom e nil nil tx0) (datom e nil nil txmax) :eavt) ;; e _ v tx
(filter (fn [^Datom d] (and (a= v (.-v d))
(= tx (datom-tx d))))))
(->> (-slice eavt (datom e nil nil tx0) (datom e nil nil txmax) :eavt) ;; e _ v _
(filter (fn [^Datom d] (a= v (.-v d)))))
(->> (-slice eavt (datom e nil nil tx0) (datom e nil nil txmax) :eavt) ;; e _ _ tx
(filter (fn [^Datom d] (= tx (datom-tx d)))))
(-slice eavt (datom e nil nil tx0) (datom e nil nil txmax) :eavt) ;; e _ _ _
(if indexed? ;; _ a v tx
(->> (-slice avet (datom e0 a v tx0) (datom emax a v txmax) :avet)
(filter (fn [^Datom d] (= tx (datom-tx d)))))
(->> (-slice aevt (datom e0 a nil tx0) (datom emax a nil txmax) :aevt)
(filter (fn [^Datom d] (and (a= v (.-v d))
(= tx (datom-tx d)))))))
(if indexed? ;; _ a v _
(-slice avet (datom e0 a v tx0) (datom emax a v txmax) :avet)
(->> (-slice aevt (datom e0 a nil tx0) (datom emax a nil txmax) :aevt)
(filter (fn [^Datom d] (a= v (.-v d))))))
(->> (-slice aevt (datom e0 a nil tx0) (datom emax a nil txmax) :aevt) ;; _ a _ tx
(filter (fn [^Datom d] (= tx (datom-tx d)))))
(-slice aevt (datom e0 a nil tx0) (datom emax a nil txmax) :aevt) ;; _ a _ _
(filter (fn [^Datom d] (and (a= v (.-v d)) (= tx (datom-tx d)))) (-all eavt)) ;; _ _ v tx
(filter (fn [^Datom d] (a= v (.-v d))) (-all eavt)) ;; _ _ v _
(filter (fn [^Datom d] (= tx (datom-tx d))) (-all eavt)) ;; _ _ _ tx
(-all eavt)]))))
(defrecord-updatable DB [schema eavt aevt avet temporal-eavt temporal-aevt temporal-avet max-eid max-tx op-count rschema hash config system-entities ident-ref-map ref-ident-map meta]
#?@(:cljs
[IHash (-hash [db] hash)
IEquiv (-equiv [db other] (equiv-db db other))
ISeqable (-seq [db] (-seq (.-eavt db)))
IReversible (-rseq [db] (-rseq (.-eavt db)))
ICounted (-count [db] (count (.-eavt db)))
IEmptyableCollection (-empty [db] (empty-db (ds/get-user-schema 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 "datahike.DB/conj! is not supported" {})))
(-persistent! [db] (db-persistent! db))]
:clj
[Object (hashCode [db] hash)
clojure.lang.IHashEq (hasheq [db] hash)
clojure.lang.Seqable (seq [db] (-seq eavt))
clojure.lang.IPersistentCollection
(count [db] (-count eavt))
(equiv [db other] (equiv-db db other))
(empty [db] (empty-db (ds/get-user-schema db)))
clojure.lang.IEditableCollection
(asTransient [db] (db-transient db))
clojure.lang.ITransientCollection
(conj [db key] (throw (ex-info "datahike.DB/conj! is not supported" {})))
(persistent [db] (db-persistent! db))])
IDB
(-schema [db] (.-schema db))
(-rschema [db] (.-rschema db))
(-system-entities [db] (.-system-entities db))
(-attrs-by [db property] ((.-rschema db) property))
(-temporal-index? [db] (-keep-history? db))
(-keep-history? [db] (-> db -config :keep-history?))
(-max-tx [db] (.-max-tx db))
(-max-eid [db] (.-max-eid db))
(-config [db] (.-config db))
(-ref-for [db a-ident]
(if (:attribute-refs? (.-config db))
(let [ref (get (.-ident-ref-map db) a-ident)]
(when (nil? ref)
(warn (str "Attribute " a-ident " has not been found in database")))
ref)
a-ident))
(-ident-for [db a-ref]
(if (:attribute-refs? (.-config db))
(let [a-ident (get (.-ref-ident-map db) a-ref)]
(when (nil? a-ident)
(warn (str "Attribute with reference number " a-ref " has not been found in database")))
a-ident)
a-ref))
ISearch
(-search [db pattern]
(search-current-indices db pattern))
IIndexAccess
(-datoms [db index-type cs]
(-slice (get db index-type)
(components->pattern db index-type cs e0 tx0)
(components->pattern db index-type cs emax txmax)
index-type))
(-seek-datoms [db index-type cs]
(-slice (get db index-type)
(components->pattern db index-type cs e0 tx0)
(datom emax nil nil txmax)
index-type))
(-rseek-datoms [db index-type cs]
(-> (-slice (get db index-type)
(components->pattern db index-type cs e0 tx0)
(datom emax nil nil txmax)
index-type)
vec
rseq))
(-index-range [db attr start end]
(when-not (indexing? db attr)
(raise "Attribute" attr "should be marked as :db/index true" {}))
(validate-attr attr (list '-index-range 'db attr start end) db)
(-slice avet
(resolve-datom db nil attr start nil e0 tx0)
(resolve-datom db nil attr end nil emax txmax)
:avet))
clojure.data/EqualityPartition
(equality-partition [x] :datahike/db)
clojure.data/Diff
(diff-similar [a b]
(let [datoms-a (-slice (:eavt a) (datom e0 nil nil tx0) (datom emax nil nil txmax) :eavt)
datoms-b (-slice (:eavt b) (datom e0 nil nil tx0) (datom emax nil nil txmax) :eavt)]
(dd/diff-sorted datoms-a datoms-b dd/cmp-datoms-eavt-quick))))
(defn db? [x]
(and (satisfies? ISearch x)
(satisfies? IIndexAccess x)
(satisfies? IDB x)))
;; ----------------------------------------------------------------------------
(defrecord-updatable FilteredDB [unfiltered-db pred]
#?@(:cljs
[IEquiv (-equiv [db other] (equiv-db db other))
ISeqable (-seq [db] (-datoms db :eavt []))
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")))
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
[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.Seqable (seq [db] (-datoms db :eavt []))
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)))
(-rschema [db] (-rschema (.-unfiltered-db db)))
(-system-entities [db] (-system-entities (.-unfiltered-db db)))
(-attrs-by [db property] (-attrs-by (.-unfiltered-db db) property))
(-temporal-index? [db] (-keep-history? db))
(-keep-history? [db] (-keep-history? (.-unfiltered-db db)))
(-max-tx [db] (-max-tx (.-unfiltered-db db)))
(-max-eid [db] (-max-eid (.-unfiltered-db db)))
(-config [db] (-config (.-unfiltered-db db)))
(-ref-for [db a-ident] (-ref-for (.-unfiltered-db db) a-ident))
(-ident-for [db a-ref] (-ident-for (.-unfiltered-db db) a-ref))
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 distinct-datoms [db current-datoms history-datoms]
(if (-keep-history? db)
(concat (filter #(or (no-history? db (:a %))
(multival? db (:a %)))
current-datoms)
history-datoms)
current-datoms))
(defn temporal-search [^DB db pattern]
(distinct-datoms db
(search-current-indices db pattern)
(search-temporal-indices db pattern)))
(defn temporal-datoms [^DB db index-type cs]
(let [index (get db index-type)
temporal-index (get db (keyword (str "temporal-" (name index-type))))
from (components->pattern db index-type cs e0 tx0)
to (components->pattern db index-type cs emax txmax)]
(distinct-datoms db
(-slice index from to index-type)
(-slice temporal-index from to index-type))))
(defn temporal-seek-datoms [^DB db index-type cs]
(let [index (get db index-type)
temporal-index (get db (keyword (str "temporal-" (name index-type))))
from (components->pattern db index-type cs e0 tx0)
to (datom emax nil nil txmax)]
(distinct-datoms db
(-slice index from to index-type)
(-slice temporal-index from to index-type))))
(defn temporal-rseek-datoms [^DB db index-type cs]
(let [index (get db index-type)
temporal-index (get db (keyword (str "temporal-" (name index-type))))
from (components->pattern db index-type cs e0 tx0)
to (datom emax nil nil txmax)]
(concat
(-> (distinct-datoms db
(-slice index from to index-type)
(-slice temporal-index from to index-type))
vec
rseq))))
(defn temporal-index-range [^DB db current-db attr start end]
(when-not (indexing? db attr)
(raise "Attribute" attr "should be marked as :db/index true" {}))
(validate-attr attr (list '-index-range 'db attr start end) db)
(let [from (resolve-datom current-db nil attr start nil e0 tx0)
to (resolve-datom current-db nil attr end nil emax txmax)]
(distinct-datoms db
(-slice (get db :avet) from to :avet)
(-slice (get db :temporal-avet) from to :avet))))
(defrecord-updatable HistoricalDB [origin-db]
#?@(:cljs
[IEquiv (-equiv [db other] (equiv-db db other))
ISeqable (-seq [db] (-datoms db :eavt []))
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 HistoricalDB")))
IEmptyableCollection (-empty [_] (throw (js/Error. "-empty is not supported on HistoricalDB")))
ILookup (-lookup ([_ _] (throw (js/Error. "-lookup is not supported on HistoricalDB")))
([_ _ _] (throw (js/Error. "-lookup is not supported on HistoricalDB"))))
IAssociative (-contains-key? [_ _] (throw (js/Error. "-contains-key? is not supported on HistoricalDB")))
(-assoc [_ _ _] (throw (js/Error. "-assoc is not supported on HistoricalDB")))]
:clj
[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 HistoricalDB")))
(empty [db] (throw (UnsupportedOperationException. "empty is not supported on HistoricalDB")))
clojure.lang.Seqable (seq [db] (-datoms db :eavt []))
clojure.lang.ILookup (valAt [db k] (throw (UnsupportedOperationException. "valAt/2 is not supported on HistoricalDB")))
(valAt [db k nf] (throw (UnsupportedOperationException. "valAt/3 is not supported on HistoricalDB")))
clojure.lang.IKeywordLookup (getLookupThunk [db k]
(throw (UnsupportedOperationException. "getLookupThunk is not supported on HistoricalDB")))
clojure.lang.Associative
(containsKey [e k] (throw (UnsupportedOperationException. "containsKey is not supported on HistoricalDB")))
(entryAt [db k] (throw (UnsupportedOperationException. "entryAt is not supported on HistoricalDB")))
(assoc [db k v] (throw (UnsupportedOperationException. "assoc is not supported on HistoricalDB")))])
IDB
(-schema [db] (-schema (.-origin-db db)))
(-rschema [db] (-rschema (.-origin-db db)))
(-system-entities [db] (-system-entities (.-origin-db db)))
(-attrs-by [db property] (-attrs-by (.-origin-db db) property))
(-temporal-index? [db] (-keep-history? db))
(-keep-history? [db] (-keep-history? (.-origin-db db)))
(-max-tx [db] (-max-tx (.-origin-db db)))
(-max-eid [db] (-max-eid (.-origin-db db)))
(-config [db] (-config (.-origin-db db)))
(-ref-for [db a-ident] (-ref-for (.-origin-db db) a-ident))
(-ident-for [db a-ref] (-ident-for (.-origin-db db) a-ref))
IHistory
(-time-point [db] (.-time-point db))
(-origin [db] (.-origin-db db))
ISearch
(-search [db pattern]
(temporal-search (.-origin-db db) pattern))
IIndexAccess
(-datoms [db index-type cs] (temporal-datoms (.-origin-db db) index-type cs))
(-seek-datoms [db index-type cs] (temporal-seek-datoms (.-origin-db db) index-type cs))
(-rseek-datoms [db index-type cs] (temporal-rseek-datoms (.-origin-db db) index-type cs))
(-index-range [db attr start end] (temporal-index-range (.-origin-db db) db attr start end)))
(defn filter-txInstant [datoms pred db]
(let [txInstant (if (:attribute-refs? (.-config db))
(-ref-for db :db/txInstant)
:db/txInstant)]
(into #{}
(comp
(map datom-tx)
(distinct)
(mapcat (fn [tx] (temporal-datoms db :eavt [tx])))
(keep (fn [^Datom d]
(when (and (= txInstant (.-a d)) (pred d))
(.-e d)))))
datoms)))
(defn get-current-values [rschema datoms]
(->> datoms
(filter datom-added)
(group-by (fn [^Datom datom] [(.-e datom) (.-a datom)]))
(mapcat
(fn [[[_ a] entities]]
(if (contains? (get-in rschema [:db.cardinality/many]) a)
entities
[(reduce (fn [^Datom datom-0 ^Datom datom-1]
(if (> (datom-tx datom-0) (datom-tx datom-1))
datom-0
datom-1)) entities)])))))
(defn- date? [d]
#?(:cljs (instance? js/Date d)
:clj (instance? Date d)))
(defn filter-as-of-datoms [datoms time-point db]
(let [as-of-pred (fn [^Datom d]
(if (date? time-point)
(.before ^Date (.-v d) ^Date time-point)
(<= (dd/datom-tx d) time-point)))
filtered-tx-ids (filter-txInstant datoms as-of-pred db)
filtered-datoms (->> datoms
(filter (fn [^Datom d] (contains? filtered-tx-ids (datom-tx d))))
(get-current-values (-rschema db)))]
filtered-datoms))
(defrecord-updatable AsOfDB [origin-db time-point]
#?@(:cljs
[IEquiv (-equiv [db other] (equiv-db db other))
ISeqable (-seq [db] (-datoms db :eavt []))
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 AsOfDB")))
IEmptyableCollection (-empty [_] (throw (js/Error. "-empty is not supported on AsOfDB")))
ILookup (-lookup ([_ _] (throw (js/Error. "-lookup is not supported on AsOfDB")))
([_ _ _] (throw (js/Error. "-lookup is not supported on AsOfDB"))))
IAssociative (-contains-key? [_ _] (throw (js/Error. "-contains-key? is not supported on AsOfDB")))
(-assoc [_ _ _] (throw (js/Error. "-assoc is not supported on AsOfDB")))]
:clj
[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 AsOfDB")))
(empty [db] (throw (UnsupportedOperationException. "empty is not supported on AsOfDB")))
clojure.lang.Seqable (seq [db] (-datoms db :eavt []))
clojure.lang.ILookup (valAt [db k] (throw (UnsupportedOperationException. "valAt/2 is not supported on AsOfDB")))
(valAt [db k nf] (throw (UnsupportedOperationException. "valAt/3 is not supported on AsOfDB")))
clojure.lang.IKeywordLookup (getLookupThunk [db k]
(throw (UnsupportedOperationException. "getLookupThunk is not supported on AsOfDB")))
clojure.lang.Associative
(containsKey [e k] (throw (UnsupportedOperationException. "containsKey is not supported on AsOfDB")))
(entryAt [db k] (throw (UnsupportedOperationException. "entryAt is not supported on AsOfDB")))
(assoc [db k v] (throw (UnsupportedOperationException. "assoc is not supported on AsOfDB")))])
IDB
(-schema [db] (-schema (.-origin-db db)))
(-rschema [db] (-rschema (.-origin-db db)))
(-system-entities [db] (-system-entities (.-origin-db db)))
(-attrs-by [db property] (-attrs-by (.-origin-db db) property))
(-temporal-index? [db] (-keep-history? db))
(-keep-history? [db] (-keep-history? (.-origin-db db)))
(-max-tx [db] (-max-tx (.-origin-db db)))
(-max-eid [db] (-max-eid (.-origin-db db)))
(-config [db] (-config (.-origin-db db)))
(-ref-for [db a-ident] (-ref-for (.-origin-db db) a-ident))
(-ident-for [db a-ref] (-ident-for (.-origin-db db) a-ref))
IHistory
(-time-point [db] (.-time-point db))
(-origin [db] (.-origin-db db))
ISearch
(-search [db pattern]
(let [origin-db (.-origin-db db)]
(-> (temporal-search origin-db pattern)
(filter-as-of-datoms (.-time-point db) origin-db))))
IIndexAccess
(-datoms [db index-type cs]
(let [origin-db (.-origin-db db)]
(-> (temporal-datoms origin-db index-type cs)
(filter-as-of-datoms (.-time-point db) origin-db))))
(-seek-datoms [db index-type cs]
(let [origin-db (.-origin-db db)]
(-> (temporal-seek-datoms origin-db index-type cs)
(filter-as-of-datoms (.-time-point db) origin-db))))
(-rseek-datoms [db index-type cs]
(let [origin-db (.-origin-db db)]
(-> (temporal-rseek-datoms origin-db index-type cs)
(filter-as-of-datoms (.-time-point db) origin-db))))
(-index-range [db attr start end]
(let [origin-db (.-origin-db db)]
(-> (temporal-index-range origin-db db attr start end)
(filter-as-of-datoms (.-time-point db) origin-db)))))
(defn- filter-since [datoms time-point db]
(let [since-pred (fn [^Datom d]
(if (date? time-point)
(.after ^Date (.-v d) ^Date time-point)
(>= (.-tx d) time-point)))
filtered-tx-ids (filter-txInstant datoms since-pred db)]
(->> datoms
(filter datom-added)
(filter (fn [^Datom d] (contains? filtered-tx-ids (datom-tx d)))))))
(defn- filter-before [datoms ^Date before-date db]
(let [before-pred (fn [^Datom d]
(.before ^Date (.-v d) before-date))
filtered-tx-ids (filter-txInstant datoms before-pred db)]
(filter
(fn [^Datom d]
(contains? filtered-tx-ids (datom-tx d)))
datoms)))
(defrecord-updatable SinceDB [origin-db time-point]
#?@(:cljs
[IEquiv (-equiv [db other] (equiv-db db other))
ISeqable (-seq [db] (-datoms db :eavt []))
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 SinceDB")))
IEmptyableCollection (-empty [_] (throw (js/Error. "-empty is not supported on SinceDB")))
ILookup (-lookup ([_ _] (throw (js/Error. "-lookup is not supported on SinceDB")))
([_ _ _] (throw (js/Error. "-lookup is not supported on SinceDB"))))
IAssociative (-contains-key? [_ _] (throw (js/Error. "-contains-key? is not supported on SinceDB")))
(-assoc [_ _ _] (throw (js/Error. "-assoc is not supported on SinceDB")))]
:clj
[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 SinceDB")))
(empty [db] (throw (UnsupportedOperationException. "empty is not supported on SinceDB")))
clojure.lang.Seqable (seq [db] (-datoms db :eavt []))
clojure.lang.ILookup (valAt [db k] (throw (UnsupportedOperationException. "valAt/2 is not supported on SinceDB")))
(valAt [db k nf] (throw (UnsupportedOperationException. "valAt/3 is not supported on SinceDB")))
clojure.lang.IKeywordLookup (getLookupThunk [db k]
(throw (UnsupportedOperationException. "getLookupThunk is not supported on SinceDB")))
clojure.lang.Associative
(containsKey [e k] (throw (UnsupportedOperationException. "containsKey is not supported on SinceDB")))
(entryAt [db k] (throw (UnsupportedOperationException. "entryAt is not supported on SinceDB")))
(assoc [db k v] (throw (UnsupportedOperationException. "assoc is not supported on SinceDB")))])
IDB
(-schema [db] (-schema (.-origin-db db)))
(-rschema [db] (-rschema (.-origin-db db)))
(-system-entities [db] (-system-entities (.-origin-db db)))
(-attrs-by [db property] (-attrs-by (.-origin-db db) property))
(-temporal-index? [db] (-keep-history? db))
(-keep-history? [db] (-keep-history? (.-origin-db db)))
(-max-tx [db] (-max-tx (.-origin-db db)))
(-max-eid [db] (-max-eid (.-origin-db db)))
(-config [db] (-config (.-origin-db db)))
(-ref-for [db a-ident] (-ref-for (.-origin-db db) a-ident))
(-ident-for [db a-ref] (-ident-for (.-origin-db db) a-ref))
IHistory
(-time-point [db] (.-time-point db))
(-origin [db] (.-origin-db db))
ISearch
(-search [db pattern]
(let [origin-db (.-origin-db db)]
(-> (temporal-search origin-db pattern)
(filter-since (.-time-point db) origin-db))))
IIndexAccess
(-datoms [db index-type cs]
(let [origin-db (.-origin-db db)]
(-> (temporal-datoms origin-db index-type cs)
(filter-since (.-time-point db) origin-db))))
(-seek-datoms [db index-type cs]
(let [origin-db (.-origin-db db)]
(-> (temporal-seek-datoms origin-db index-type cs)
(filter-since (.-time-point db) origin-db))))
(-rseek-datoms [db index-type cs]
(let [origin-db (.-origin-db db)]
(-> (temporal-rseek-datoms origin-db index-type cs)
(filter-since (.-time-point db) origin-db))))
(-index-range [db attr start end]
(let [origin-db (.-origin-db db)]
(-> (temporal-index-range origin-db db attr start end)
(filter-since (.-time-point db) origin-db)))))
;; ----------------------------------------------------------------------------
(def db-caches (cw/lru-cache-factory {} :threshold (:datahike-max-db-caches env 5)))
(defn memoize-for [^DB db key f]
(if (or (zero? (or (:cache-size (.-config db)) 0))
(zero? (.-hash db))) ;; empty db
(f)
(let [db-cache (cw/lookup-or-miss db-caches
(.-hash db)
(fn [_] (lru-datom-cache-factory {} :threshold (:cache-size (.-config db)))))]
(cw/lookup-or-miss db-cache key (fn [_] (f))))))
(defn- search-current-indices [^DB db pattern]
(memoize-for db [:search pattern]
#(let [[_ a _ _] pattern]
(search-indices (.-eavt db)
(.-aevt db)
(.-avet db)
pattern
(indexing? db a)
false))))
(defn- search-temporal-indices [^DB db pattern]
(memoize-for db [:temporal-search pattern]
#(let [[_ a _ _ added] pattern
result (search-indices (.-temporal-eavt db)
(.-temporal-aevt db)
(.-temporal-avet db)
pattern
(indexing? db a)
true)]
(case added
true (filter datom-added result)
false (remove datom-added result)
nil result))))
(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]
:db.type/tuple [:db.type/tuple]
(if (= k :db/ident)
[:db/ident]
(when (true? v)
(case k
:db/isComponent [:db/isComponent]
:db/index [:db/index]
:db/noHistory [:db/noHistory]
[])))))
(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)))
(defn- attrTuples
"For each attribute involved in a composite tuple, returns a map made of the tuple attribute it is involved in, plus its position in the tuple.
E.g. {:a => {:a+b+c 0, :a+d 0}
:b => {:a+b+c 1}
... }"
[schema rschema]
(reduce
(fn [m tuple-attr]
(reduce-indexed
(fn [m attr idx]
(update m attr assoc tuple-attr idx))
m
(-> schema tuple-attr :db/tupleAttrs)))
{}
(:db.type/tuple rschema)))
(defn- rschema [schema]
(let [rschema (reduce-kv
(fn [m attr keys->values]
(if (keyword? keys->values)
m
(reduce-kv
(fn [m key value]
(reduce
(fn [m prop]
(assoc m prop (conj (get m prop #{}) attr)))
m (attr->properties key value)))
(update m :db/ident (fn [coll] (if coll (conj coll attr) #{attr}))) keys->values)))
{} schema)]
(assoc rschema :db/attrTuples (attrTuples 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-tuple-schema [a kv]
(when (= :db.type/tuple (:db/valueType kv))
(case (some #{:db/tupleAttrs :db/tupleTypes :db/tupleType} (keys kv))
:db/tupleAttrs (when (not (vector? (:db/tupleAttrs kv)))
(throw (ex-info (str "Bad attribute specification for " a ": {:db/tupleAttrs ...} should be a vector}")
{:error :schema/validation
:attribute a
:key :db/tupleAttrs})))
:db/tupleTypes (when (not (vector? (:db/tupleTypes kv)))
(throw (ex-info (str "Bad attribute specification for " a ": {:db/tupleTypes ...} should be a vector}")
{:error :schema/validation
:attribute a
:key :db/tupleTypes})))
:db/tupleType (when (not (keyword? (:db/tupleType kv)))
(throw (ex-info (str "Bad attribute specification for " a ": {:db/tupleType ...} should be a keyword}")
{:error :schema/validation
:attribute a
:key :db/tupleType}))))))
(defn- validate-schema [schema]
(doseq [[a-ident kv] schema]
(let [comp? (:db/isComponent kv false)]
(validate-schema-key a-ident :db/isComponent (:db/isComponent kv) #{true false})
(when (and comp? (not= (:db/valueType kv) :db.type/ref))
(throw (ex-info (str "Bad attribute specification for " a-ident ": {:db/isComponent true} should also have {:db/valueType :db.type/ref}")
{:error :schema/validation
:attribute a-ident
:key :db/isComponent}))))
(validate-schema-key a-ident :db/unique (:db/unique kv) #{:db.unique/value :db.unique/identity})
(validate-schema-key a-ident :db/valueType (:db/valueType kv) #{:db.type/ref :db.type/tuple})
(validate-schema-key a-ident :db/cardinality (:db/cardinality kv) #{:db.cardinality/one :db.cardinality/many})
(validate-tuple-schema a-ident kv)))
(defn to-old-schema [new-schema]
(if (or (vector? new-schema) (seq? new-schema))
(reduce
(fn [acc {:keys [:db/ident] :as schema-entity}]
(assoc acc ident schema-entity))
{}
new-schema)
new-schema))
(defn- validate-write-schema [schema]
(when-not (ds/old-schema-valid? schema)
(raise "Incomplete schema attributes, expected at least :db/valueType, :db/cardinality"
(ds/explain-old-schema schema))))
(defn- max-system-eid []
(->> system-schema
rest
(map first)
(apply max)))
(defn init-max-eid [eavt]
;; solved with reserse slice first in datascript
(if-let [datoms (-slice
eavt
(datom e0 nil nil tx0)
(datom (dec tx0) nil nil txmax)
:eavt)]
(-> datoms vec rseq first :e) ;; :e of last datom in slice
e0))
(defn get-max-tx [eavt]
(transduce (map (fn [^Datom d] (datom-tx d))) max tx0 (-all eavt)))
(def ref-datoms ;; maps enums as well
(let [idents (reduce (fn [m {:keys [db/ident db/id]}]
(assoc m ident id))
{}
system-schema)]
(->> system-schema
(mapcat
(fn [{:keys [db/id] :as i}]
(reduce-kv
(fn [coll k v]
(let [k-ref (idents k)]
(if (= k :db/ident)
(conj coll (dd/datom id k-ref v tx0))
(if-let [v-ref (idents v)]
(conj coll (dd/datom id k-ref v-ref tx0))
(conj coll (dd/datom id k-ref v tx0))))))
[]
(dissoc i :db/id))))
vec)))
(defn get-ident-ref-map
"Maps IDs of system entities to their names (keyword) and attribute names to the attribute's specification"
[schema]
(reduce
(fn [m [a {:keys [db/id]}]]
(when a
(assoc m a id)))
{}
schema))
(defn ^DB empty-db
"Prefer create-database in api, schema only in index for attribute reference database."
([] (empty-db nil nil))
([schema] (empty-db schema nil))
([schema user-config]
{:pre [(or (nil? schema) (map? schema) (coll? schema))]}
(let [complete-config (merge (dc/storeless-config) user-config)
_ (dc/validate-config complete-config)
{:keys [keep-history? index schema-flexibility attribute-refs?]} complete-config
on-read? (= :read schema-flexibility)
schema (to-old-schema schema)
_ (if on-read?
(validate-schema schema)
(validate-write-schema schema))
complete-schema (merge schema
(if attribute-refs?
c/ref-implicit-schema
c/non-ref-implicit-schema))
rschema (rschema complete-schema)
ident-ref-map (if attribute-refs? (get-ident-ref-map complete-schema) {})
ref-ident-map (if attribute-refs? (clojure.set/map-invert ident-ref-map) {})
system-entities (if attribute-refs? c/system-entities #{})
indexed (if attribute-refs?
(set (map ident-ref-map (:db/index rschema)))
(:db/index rschema))
index-config (merge (:index-config complete-config)
{:indexed indexed})
eavt (if attribute-refs?
(di/init-index index ref-datoms :eavt 0 index-config)
(di/empty-index index :eavt index-config))
aevt (if attribute-refs?
(di/init-index index ref-datoms :aevt 0 index-config)
(di/empty-index index :aevt index-config))
indexed-datoms (filter (fn [[_ a _ _]] (contains? indexed a)) ref-datoms)
avet (if attribute-refs?
(di/init-index index indexed-datoms :avet 0 index-config)
(di/empty-index index :avet index-config))
max-eid (if attribute-refs? ue0 e0)
max-tx (if attribute-refs? utx0 tx0)]
(map->DB
(merge
{:schema complete-schema
:rschema rschema
:config complete-config
:eavt eavt
:aevt aevt
:avet avet
:max-eid max-eid
:max-tx max-tx
:hash 0
:system-entities system-entities
:ref-ident-map ref-ident-map
:ident-ref-map ident-ref-map
:meta (tools/meta-data)
:op-count (if attribute-refs? (count ref-datoms) 0)}
(when keep-history? ;; no difference for attribute references since no update possible
{:temporal-eavt (di/empty-index index :eavt index-config)
:temporal-aevt (di/empty-index index :aevt index-config)
:temporal-avet (di/empty-index index :avet index-config)}))))))
(defn advance-all-datoms [datoms offset]
(map
(fn [^Datom d]
(datom (+ (.-e d) offset) (.-a d) (.-v d) (.-tx d)))
datoms))
(defn get-max-tx [eavt]
(transduce (map (fn [^Datom d] (datom-tx d))) max tx0 (-all eavt)))
(defn ^DB init-db
([datoms] (init-db datoms nil nil))
([datoms schema] (init-db datoms schema nil))
([datoms schema user-config]
(validate-schema schema)
(let [{:keys [index schema-flexibility keep-history? attribute-refs?] :as complete-config} (merge (dc/storeless-config) user-config)
_ (dc/validate-config complete-config)
complete-schema (merge schema
(if attribute-refs?
c/ref-implicit-schema
c/non-ref-implicit-schema))
rschema (rschema complete-schema)
ident-ref-map (if attribute-refs? (get-ident-ref-map schema) {})
ref-ident-map (if attribute-refs? (clojure.set/map-invert ident-ref-map) {})
system-entities (if attribute-refs? c/system-entities #{})
indexed (if attribute-refs?
(set (map ident-ref-map (:db/index rschema)))
(:db/index rschema))
new-datoms (if attribute-refs? (concat ref-datoms datoms) datoms)
indexed-datoms (filter (fn [[_ a _ _]] (contains? indexed a)) new-datoms)
op-count 0
index-config (assoc (:index-config complete-config)
:indexed indexed)
avet (di/init-index index indexed-datoms :avet op-count index-config)
eavt (di/init-index index new-datoms :eavt op-count index-config)