-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
core.cljc
1721 lines (1320 loc) · 66.8 KB
/
core.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 datalevin.core
"User facing API for Datalevin library features"
(:require
[clojure.java.io :as io]
[clojure.pprint :as p]
[#?(:cljs cljs.reader :clj clojure.edn) :as edn]
[datalevin.util :as u]
[datalevin.remote :as r]
[datalevin.search :as sc]
[datalevin.db :as db]
[datalevin.datom :as dd]
[datalevin.storage :as s]
[datalevin.constants :as c]
[datalevin.lmdb :as l]
[datalevin.pull-parser]
[datalevin.pull-api :as dp]
[datalevin.query :as dq]
[datalevin.built-ins :as dbq]
[datalevin.entity :as de]
[datalevin.bits :as b])
(:import
[datalevin.entity Entity]
[datalevin.storage Store IStore]
[datalevin.db DB]
[datalevin.lmdb ILMDB]
[datalevin.datom Datom]
[datalevin.remote DatalogStore KVStore]
[java.io PushbackReader IOException]
[java.util UUID]))
(if (u/graal?)
(require 'datalevin.binding.graal)
(require 'datalevin.binding.java))
;; Entities
(defn entity
"Retrieves an entity by its id from a Datalog database. Entities
are lazy map-like structures to navigate Datalevin database content.
`db` is a Datalog database.
For `eid` pass entity id or lookup attr:
(entity db 1)
(entity db [:unique-attr :value])
If entity does not exist, `nil` is returned:
(entity db 100500) ; => nil
Creating an entity by id is very cheap, almost no-op, as attr access
is on-demand:
(entity db 1) ; => {:db/id 1}
Entity attributes can be lazily accessed through key lookups:
(:attr (entity db 1)) ; => :value
(get (entity db 1) :attr) ; => :value
Cardinality many attributes are returned sequences:
(:attrs (entity db 1)) ; => [:v1 :v2 :v3]
Reference attributes are returned as another entities:
(:ref (entity db 1)) ; => {:db/id 2}
(:ns/ref (entity db 1)) ; => {:db/id 2}
References can be walked backwards by prepending `_` to name part
of an attribute:
(:_ref (entity db 2)) ; => [{:db/id 1}]
(:ns/_ref (entity db 2)) ; => [{:db/id 1}]
Reverse reference lookup returns sequence of entities unless
attribute is marked as `:db/isComponent`:
(:_component-ref (entity db 2)) ; => {:db/id 1}
Entity gotchas:
- Entities print as map, but are not exactly maps (they have
compatible get interface though).
- Entities retain reference to the database.
- Creating an entity by id is very cheap, almost no-op
(attributes are looked up on demand).
- Comparing entities just compares their ids. Be careful when
comparing entities taken from different dbs or from different versions of the
same db.
- Accessed entity attributes are cached on entity itself (except
backward references).
- When printing, only cached attributes (the ones you have accessed
before) are printed. See [[touch]]."
[db eid]
{:pre [(db/db? db)]}
(de/entity db eid))
(def ^{:arglists '([ent attr value])
:doc "Add an attribute value to an entity of a Datalog database"}
add de/add)
(def ^{:arglists '([ent attr][ent attr value])
:doc "Remove an attribute from an entity of a Datalog database"}
retract de/retract)
(defn entid
"Given lookup ref `[unique-attr value]`, returns numberic entity id.
`db` is a Datalog database.
If entity does not exist, returns `nil`.
For numeric `eid` returns `eid` itself (does not check for entity
existence in that case)."
[db eid]
{:pre [(db/db? db)]}
(db/entid db eid))
(defn entity-db
"Returns a Datalog db that entity was created from."
[^Entity entity]
{:pre [(de/entity? entity)]}
(.-db entity))
(def ^{:arglists '([e])
:doc "Forces all entity attributes to be eagerly fetched and cached.
Only usable for debug output.
Usage:
(entity db 1) ; => {:db/id 1}
(touch (entity db 1)) ; => {:db/id 1, :dislikes [:pie], :likes [:pizza]}
"}
touch de/touch)
;; Pull API
(def ^{:arglists '([db pattern id] [db pattern id opts])
:doc "Fetches data from a Datalog database using recursive declarative
description. See [docs.datomic.com/on-prem/pull.html](https://docs.datomic.com/on-prem/pull.html).
Unlike [[entity]], returns plain Clojure map (not lazy).
Supported opts:
`:visitor` a fn of 4 arguments, will be called for every entity/attribute pull touches
(:db.pull/attr e a nil) - when pulling a normal attribute, no matter if it has value or not
(:db.pull/wildcard e nil nil) - when pulling every attribute on an entity
(:db.pull/reverse nil a v ) - when pulling reverse attribute
Usage:
(pull db [:db/id, :name, :likes, {:friends [:db/id :name]}] 1)
; => {:db/id 1,
; :name \"Ivan\"
; :likes [:pizza]
; :friends [{:db/id 2, :name \"Oleg\"}]}"}
pull dp/pull)
(def ^{:arglists '([db pattern ids] [db pattern ids opts])
:doc
"Same as [[pull]], but accepts sequence of ids and returns
sequence of maps.
Usage:
(pull-many db [:db/id :name] [1 2])
; => [{:db/id 1, :name \"Ivan\"}
; {:db/id 2, :name \"Oleg\"}]"}
pull-many dp/pull-many)
;; Query
(defn- only-remote-db
"Return [remote-db [updated-inputs]] if the inputs contain only one db
and its backing store is a remote one, where the remote-db in the inputs is
replaced by `:remote-db-placeholder, otherwise return nil"
[inputs]
(let [dbs (filter db/db? inputs)]
(when-let [rdb (first dbs)]
(let [rstore (.-store ^DB rdb)]
(when (and (= 1 (count dbs)) (instance? DatalogStore rstore))
[rstore (vec (replace {rdb :remote-db-placeholder} inputs))])))))
(defn q
"Executes a Datalog query. See [docs.datomic.com/on-prem/query.html](https://docs.datomic.com/on-prem/query.html).
Usage:
```
(q '[:find ?value
:where [_ :likes ?value]
:timeout 5000]
db)
; => #{[\"fries\"] [\"candy\"] [\"pie\"] [\"pizza\"]}
```"
[query & inputs]
(if-let [[store inputs'] (only-remote-db inputs)]
(r/q store query inputs')
(apply dq/q query inputs)))
;; Creating DB
(def ^{:arglists '([] [dir] [dir schema] [dir schema opts])
:doc "Open a Datalog database at the given location.
`dir` could be a local directory path or a dtlv connection URI string.
Creates an empty database there if it does not exist yet.
Update the schema if one is given. Return reference to the database.
`opts` map has keys:
* `:validate-data?`, a boolean, instructing the system to validate data type during transaction. Default is `false`.
* `:auto-entity-time?`, a boolean indicating whether to maintain `:db/created-at` and `:db/updated-at` values for each entity. Default is `false`.
* `:search-opts`, an option map that will be passed to the built-in full-text search engine
* `:kv-opts`, an option map that will be passed to the underlying kV store
* `:client-opts` is the option map passed to the client if `dir` is a remote URI string.
Usage:
(empty-db)
(empty-db \"/tmp/test-empty-db\")
(empty-db \"/tmp/test-empty-db\" {:likes {:db/cardinality :db.cardinality/many}})
(empty-db \"dtlv://datalevin:secret@example.host/mydb\" {} {:auto-entity-time? true :search-engine {:analyzer blank-space-analyzer}})"}
empty-db db/empty-db)
(def ^{:arglists '([x])
:doc "Returns `true` if the given value is a Datalog database. Has the side effect of updating the cache of the db to the most recent. Return `false` otherwise. "}
db? db/db?)
(def ^{:arglists '([e a v] [e a v tx] [e a v tx added])
:doc "Low-level fn to create raw datoms in a Datalog db.
Optionally with transaction id (number) and `added` flag (`true` for addition, `false` for retraction).
See also [[init-db]]."}
datom dd/datom)
(def ^{:arglists '([x])
:doc "Returns `true` if the given value is a datom, `false` otherwise."}
datom? dd/datom?)
(def ^{:arglists '([d])
:doc "Return the entity id of a datom"}
datom-e dd/datom-e)
(def ^{:arglists '([d])
:doc "Return the attribute of a datom"}
datom-a dd/datom-a)
(def ^{:arglists '([d])
:doc "Return the value of a datom"}
datom-v dd/datom-v)
(def ^{:arglists '([datoms] [datoms dir] [datoms dir schema] [datoms dir schema opts])
:doc "Low-level function for creating a Datalog database quickly from a trusted sequence of datoms, useful for bulk data loading. `dir` could be a local directory path or a dtlv connection URI string. Does no validation on inputs, so `datoms` must be well-formed and match schema.
`opts` map has keys:
* `:validate-data?`, a boolean, instructing the system to validate data type during transaction. Default is `false`.
* `:auto-entity-time?`, a boolean indicating whether to maintain `:db/created-at` and `:db/updated-at` values for each entity. Default is `false`.
* `:search-opts`, an option map that will be passed to the built-in full-text search engine
* `:kv-opts`, an option map that will be passed to the underlying kV store
See also [[datom]], [[new-search-engine]]."}
init-db db/init-db)
(def ^{:arglists '([db])
:doc "Close the Datalog database"}
close-db db/close-db)
;; Changing DB
(def ^{:arglists '([db])
:doc "Rollback writes of the transaction from inside [[with-transaction-kv]]."}
abort-transact-kv l/abort-transact-kv)
(u/import-macro l/with-transaction-kv)
(defn datalog-index-cache-limit
"Get or set the cache limit of a Datalog DB. Default is 100. Set to 0 to
disable the cache, useful when transacting bulk data as it saves memory."
([^DB db]
(let [^Store store (.-store db)]
(:cache-limit (s/opts store))))
([^DB db ^long n]
(let [^Store store (.-store db)]
(s/assoc-opt store :cache-limit n)
(db/refresh-cache store (System/currentTimeMillis)))))
(defmacro with-transaction
"Evaluate body within the context of a single new read/write transaction,
ensuring atomicity of Datalog database operations.
`conn` is a new identifier of the Datalog database connection with a new read/write transaction attached, and `orig-conn` is the original database connection.
`body` should refer to `conn`.
Example:
(with-transaction [cn conn]
(let [query '[:find ?c .
:in $ ?e
:where [?e :counter ?c]]
^long now (q query @cn 1)]
(transact! cn [{:db/id 1 :counter (inc now)}])
(q query @cn 1))) "
[[conn orig-conn] & body]
`(let [db# ^DB (deref ~orig-conn)
s# (.-store db#)
old# (datalog-index-cache-limit db#)]
(locking (l/write-txn s#)
(datalog-index-cache-limit db# 0)
(if (instance? DatalogStore s#)
(let [res# (if (l/writing? s#)
(let [~conn ~orig-conn]
~@body)
(let [s1# (r/open-transact s#)
w# #(let [~conn (atom (db/new-db s1#)
:meta (meta ~orig-conn))]
~@body) ]
(try
(u/repeat-try-catch
~c/+in-tx-overflow-times+
l/resized? (w#))
(finally (r/close-transact s#)))))
new-db# (db/new-db s#)]
(reset! ~orig-conn new-db#)
(datalog-index-cache-limit new-db# old#)
res#)
(let [kv# (.-lmdb ^Store s#)
s1# (volatile! nil)
res1# (l/with-transaction-kv [kv1# kv#]
(let [conn1# (atom (db/new-db (s/transfer s# kv1#))
:meta (meta ~orig-conn))
res# (let [~conn conn1#]
~@body)]
(vreset! s1# (.-store ^DB (deref conn1#)))
res#))
new-db# (db/new-db (s/transfer (deref s1#) kv#))]
(reset! ~orig-conn new-db#)
(datalog-index-cache-limit new-db# old#)
res1#)))))
(def ^{:arglists '([conn])
:doc "Rollback writes of the transaction from inside [[with-transaction]]."}
abort-transact db/abort-transact)
(defn ^:no-doc with
"Same as [[transact!]]. Returns transaction report (see [[transact!]])."
([db tx-data] (with db tx-data {} false))
([db tx-data tx-meta] (with db tx-data tx-meta false))
([db tx-data tx-meta simulated?]
{:pre [(db/db? db)]}
(db/transact-tx-data (db/->TxReport db db [] {} tx-meta)
tx-data simulated?)))
(def ^{:arglists '([db tx-data])
:doc "Returns a transaction report without side-effects. Useful for obtaining
the would-be db state and the would-be set of datoms."}
tx-data->simulated-report db/tx-data->simulated-report)
(defn ^:no-doc db-with
"Applies transaction. Return the Datalog db."
[db tx-data]
{:pre [(db/db? db)]}
(:db-after (with db tx-data)))
;; Index lookups
(defn datoms
"Index lookup in Datalog db. Returns a sequence of datoms (lazy iterator over actual DB index) which components (e, a, v) match passed arguments.
Datoms are sorted in index sort order. Possible `index` values are: `:eav`, `:ave`, or `:vea` (only available for :db.type/ref datoms).
Usage:
; find all datoms for entity id == 1 (any attrs and values)
; sort by attribute, then value
(datoms db :eav 1)
; => (#datalevin/Datom [1 :friends 2]
; #datalevin/Datom [1 :likes \"fries\"]
; #datalevin/Datom [1 :likes \"pizza\"]
; #datalevin/Datom [1 :name \"Ivan\"])
; find all datoms for entity id == 1 and attribute == :likes (any values)
; sorted by value
(datoms db :eav 1 :likes)
; => (#datalevin/Datom [1 :likes \"fries\"]
; #datalevin/Datom [1 :likes \"pizza\"])
; find all datoms for entity id == 1, attribute == :likes and value == \"pizza\"
(datoms db :eav 1 :likes \"pizza\")
; => (#datalevin/Datom [1 :likes \"pizza\"])
; find all datoms that have attribute == `:likes` and value == `\"pizza\"` (any entity id)
(datoms db :ave :likes \"pizza\")
; => (#datalevin/Datom [1 :likes \"pizza\"]
; #datalevin/Datom [2 :likes \"pizza\"])
; find all datoms sorted by entity id, then attribute, then value
(datoms db :eav) ; => (...)
Useful patterns:
; get all values of :db.cardinality/many attribute
(->> (datoms db :eav eid attr) (map :v))
; lookup entity ids by attribute value
(->> (datoms db :ave attr value) (map :e))
; find N entities with lowest attr value (e.g. 10 earliest posts)
(->> (datoms db :ave attr) (take N))
; find N entities with highest attr value (e.g. 10 latest posts)
(->> (datoms db :ave attr) (reverse) (take N))
Gotchas:
- Index lookup is usually more efficient than doing a query with a single clause.
- Resulting iterator is calculated in constant time and small constant memory overhead.
"
([db index] {:pre [(db/db? db)]} (db/-datoms db index []))
([db index c1] {:pre [(db/db? db)]} (db/-datoms db index [c1]))
([db index c1 c2] {:pre [(db/db? db)]} (db/-datoms db index [c1 c2]))
([db index c1 c2 c3] {:pre [(db/db? db)]} (db/-datoms db index [c1 c2 c3]))
([db index c1 c2 c3 c4] {:pre [(db/db? db)]} (db/-datoms db index [c1 c2 c3 c4])))
(defn seek-datoms
"Similar to [[datoms]], but will return datoms starting from specified components and including rest of the database until the end of the index.
If no datom matches passed arguments exactly, iterator will start from first datom that could be considered “greater” in index order.
Usage:
(seek-datoms db :eavt 1)
; => (#datalevin/Datom [1 :friends 2]
; #datalevin/Datom [1 :likes \"fries\"]
; #datalevin/Datom [1 :likes \"pizza\"]
; #datalevin/Datom [1 :name \"Ivan\"]
; #datalevin/Datom [2 :likes \"candy\"]
; #datalevin/Datom [2 :likes \"pie\"]
; #datalevin/Datom [2 :likes \"pizza\"])
(seek-datoms db :eavt 1 :name)
; => (#datalevin/Datom [1 :name \"Ivan\"]
; #datalevin/Datom [2 :likes \"candy\"]
; #datalevin/Datom [2 :likes \"pie\"]
; #datalevin/Datom [2 :likes \"pizza\"])
(seek-datoms db :eavt 2)
; => (#datalevin/Datom [2 :likes \"candy\"]
; #datalevin/Datom [2 :likes \"pie\"]
; #datalevin/Datom [2 :likes \"pizza\"])
; no datom [2 :likes \"fish\"], so starts with one immediately following such in index
(seek-datoms db :eavt 2 :likes \"fish\")
; => (#datalevin/Datom [2 :likes \"pie\"]
; #datalevin/Datom [2 :likes \"pizza\"])"
([db index] {:pre [(db/db? db)]} (db/-seek-datoms db index []))
([db index c1] {:pre [(db/db? db)]} (db/-seek-datoms db index [c1]))
([db index c1 c2] {:pre [(db/db? db)]} (db/-seek-datoms db index [c1 c2]))
([db index c1 c2 c3] {:pre [(db/db? db)]} (db/-seek-datoms db index [c1 c2 c3]))
([db index c1 c2 c3 c4] {:pre [(db/db? db)]} (db/-seek-datoms db index [c1 c2 c3 c4])))
(defn rseek-datoms
"Same as [[seek-datoms]], but goes backwards until the beginning of the index."
([db index] {:pre [(db/db? db)]} (db/-rseek-datoms db index []))
([db index c1] {:pre [(db/db? db)]} (db/-rseek-datoms db index [c1]))
([db index c1 c2] {:pre [(db/db? db)]} (db/-rseek-datoms db index [c1 c2]))
([db index c1 c2 c3] {:pre [(db/db? db)]} (db/-rseek-datoms db index [c1 c2 c3]))
([db index c1 c2 c3 c4] {:pre [(db/db? db)]} (db/-rseek-datoms db index [c1 c2 c3 c4])))
(defn fulltext-datoms
"Return datoms that found by the given fulltext search query"
([db query]
(fulltext-datoms db query nil))
([^DB db query opts]
(let [store (.-store db)]
(if (instance? DatalogStore store)
(r/fulltext-datoms store query opts)
(dbq/fulltext db query opts)))))
(defn index-range
"Returns part of `:avet` index between `[_ attr start]` and `[_ attr end]` in AVET sort order.
Same properties as [[datoms]].
Usage:
(index-range db :likes \"a\" \"zzzzzzzzz\")
; => (#datalevin/Datom [2 :likes \"candy\"]
; #datalevin/Datom [1 :likes \"fries\"]
; #datalevin/Datom [2 :likes \"pie\"]
; #datalevin/Datom [1 :likes \"pizza\"]
; #datalevin/Datom [2 :likes \"pizza\"])
(index-range db :likes \"egg\" \"pineapple\")
; => (#datalevin/Datom [1 :likes \"fries\"]
; #datalevin/Datom [2 :likes \"pie\"])
Useful patterns:
; find all entities with age in a specific range (inclusive)
(->> (index-range db :age 18 60) (map :e))"
[db attr start end]
{:pre [(db/db? db)]}
(db/-index-range db attr start end))
;; Conn
(defn conn?
"Returns `true` if this is an open connection to a local Datalog db, `false`
otherwise."
[conn]
(and #?(:clj (instance? clojure.lang.IDeref conn)
:cljs (satisfies? cljs.core/IDeref conn))
(db/db? @conn)))
(defn conn-from-db
"Creates a mutable reference to a given Datalog database. See [[create-conn]]."
[db]
{:pre [(db/db? db)]}
(atom db :meta { :listeners (atom {}) }))
(defn conn-from-datoms
"Create a mutable reference to a Datalog database with the given datoms added to it.
`dir` could be a local directory path or a dtlv connection URI string.
`opts` map has keys:
* `:validate-data?`, a boolean, instructing the system to validate data type during transaction. Default is `false`.
* `:auto-entity-time?`, a boolean indicating whether to maintain `:db/created-at` and `:db/updated-at` values for each entity. Default is `false`.
* `:search-opts`, an option map that will be passed to the built-in full-text search engine. See [[search]]
* `:kv-opts`, an option map that will be passed to the underlying kV store
"
([datoms] (conn-from-db (init-db datoms)))
([datoms dir] (conn-from-db (init-db datoms dir)))
([datoms dir schema] (conn-from-db (init-db datoms dir schema)))
([datoms dir schema opts] (conn-from-db (init-db datoms dir schema opts))))
(defn create-conn
"Creates a mutable reference (a “connection”) to a Datalog database at the given
location and opens the database. Creates the database if it doesn't
exist yet. Update the schema if one is given. Return the connection.
`dir` could be a local directory path or a dtlv connection URI string.
`opts` map may have keys:
* `:validate-data?`, a boolean, instructing the system to validate data type during transaction. Default is `false`.
* `:auto-entity-time?`, a boolean indicating whether to maintain `:db/created-at` and `:db/updated-at` values for each entity. Default is `false`.
* `:search-opts`, an option map that will be passed to the built-in full-text search engine. See [[search]]
* `:kv-opts`, an option map that will be passed to the underlying kV store
* `:client-opts` is the option map passed to the client if `dir` is a remote URI string.
Please note that the connection should be managed like a stateful resource.
Application should hold on to the same connection rather than opening
multiple connections to the same database in the same process.
Connections are lightweight in-memory structures (atoms). To access underlying DB, call [[db]] on it.
See also [[transact!]], [[db]], [[close]], [[get-conn]], and [[open-kv]].
Usage:
(create-conn)
(create-conn \"/tmp/test-create-conn\")
(create-conn \"/tmp/test-create-conn\" {:likes {:db/cardinality :db.cardinality/many}})
(create-conn \"dtlv://datalevin:secret@example.host/mydb\" {} {:auto-entity-time? true})"
([] (conn-from-db (empty-db)))
([dir] (conn-from-db (empty-db dir)))
([dir schema] (conn-from-db (empty-db dir schema)))
([dir schema opts] (conn-from-db (empty-db dir schema opts))))
(defn close
"Close the connection to a Datalog db"
[conn]
(when-let [store (.-store ^DB @conn)]
(s/close ^Store store))
nil)
(defn closed?
"Return true when the underlying Datalog DB is closed or when `conn` is nil or contains nil"
[conn]
(or (nil? conn)
(nil? @conn)
(s/closed? ^Store (.-store ^DB @conn))))
(defn ^:no-doc -transact! [conn tx-data tx-meta]
(let [report (with-transaction [c conn]
(assert (conn? c))
(with @c tx-data tx-meta))]
(assoc report :db-after @conn)))
(defn transact!
"Applies transaction to the underlying Datalog database of a connection.
Returns transaction report, a map:
{ :db-before ...
:db-after ...
:tx-data [...] ; plain datoms that were added/retracted from db-before
:tempids {...} ; map of tempid from tx-data => assigned entid in db-after
:tx-meta tx-meta } ; the exact value you passed as `tx-meta`
Note! `conn` will be updated in-place and is not returned from [[transact!]].
Usage:
; add a single datom to an existing entity (1)
(transact! conn [[:db/add 1 :name \"Ivan\"]])
; retract a single datom
(transact! conn [[:db/retract 1 :name \"Ivan\"]])
; retract single entity attribute
(transact! conn [[:db.fn/retractAttribute 1 :name]])
; ... or equivalently (since Datomic changed its API to support this):
(transact! conn [[:db/retract 1 :name]])
; retract all entity attributes (effectively deletes entity)
(transact! conn [[:db.fn/retractEntity 1]])
; create a new entity (`-1`, as any other negative value, is a tempid
; that will be replaced with Datalevin to a next unused eid)
(transact! conn [[:db/add -1 :name \"Ivan\"]])
; check assigned id (here `*1` is a result returned from previous `transact!` call)
(def report *1)
(:tempids report) ; => {-1 296}
; check actual datoms inserted
(:tx-data report) ; => [#datalevin/Datom [296 :name \"Ivan\"]]
; tempid can also be a string
(transact! conn [[:db/add \"ivan\" :name \"Ivan\"]])
(:tempids *1) ; => {\"ivan\" 297}
; reference another entity (must exist)
(transact! conn [[:db/add -1 :friend 296]])
; create an entity and set multiple attributes (in a single transaction
; equal tempids will be replaced with the same yet unused yet entid)
(transact! conn [[:db/add -1 :name \"Ivan\"]
[:db/add -1 :likes \"fries\"]
[:db/add -1 :likes \"pizza\"]
[:db/add -1 :friend 296]])
; create an entity and set multiple attributes (alternative map form)
(transact! conn [{:db/id -1
:name \"Ivan\"
:likes [\"fries\" \"pizza\"]
:friend 296}])
; update an entity (alternative map form). Can’t retract attributes in
; map form. For cardinality many attrs, value (fish in this example)
; will be added to the list of existing values
(transact! conn [{:db/id 296
:name \"Oleg\"
:likes [\"fish\"]}])
; ref attributes can be specified as nested map, that will create nested entity as well
(transact! conn [{:db/id -1
:name \"Oleg\"
:friend {:db/id -2
:name \"Sergey\"}}])
; reverse attribute name can be used if you want created entity to become
; a value in another entity reference
(transact! conn [{:db/id -1
:name \"Oleg\"
:_friend 296}])
; equivalent to
(transact! conn [{:db/id -1, :name \"Oleg\"}
{:db/id 296, :friend -1}])
; equivalent to
(transact! conn [[:db/add -1 :name \"Oleg\"]
[:db/add 296 :friend -1]])"
([conn tx-data] (transact! conn tx-data nil))
([conn tx-data tx-meta]
(let [report (-transact! conn tx-data tx-meta)]
(doseq [[_ callback] (some-> (:listeners (meta conn)) (deref))]
(callback report))
report)))
(defn reset-conn!
"Forces underlying `conn` value to become a Datalog `db`. Will generate a tx-report that
will remove everything from old value and insert everything from the new one."
([conn db] (reset-conn! conn db nil))
([conn db tx-meta]
(let [report (db/map->TxReport
{ :db-before @conn
:db-after db
:tx-data (concat
(map #(assoc % :added false) (datoms @conn :eavt))
(datoms db :eavt))
:tx-meta tx-meta})]
(reset! conn db)
(doseq [[_ callback] (some-> (:listeners (meta conn)) (deref))]
(callback report))
db)))
(defn- atom? [a]
#?(:cljs (instance? Atom a)
:clj (instance? clojure.lang.IAtom a)))
(defn listen!
"Listen for changes on the given connection to a Datalog db. Whenever a transaction is applied
to the database via [[transact!]], the callback is called with the transaction
report. `key` is any opaque unique value.
Idempotent. Calling [[listen!]] with the same key twice will override old
callback with the new value.
Returns the key under which this listener is registered. See also [[unlisten!]]."
([conn callback] (listen! conn (rand) callback))
([conn key callback]
{:pre [(conn? conn) (atom? (:listeners (meta conn)))]}
(swap! (:listeners (meta conn)) assoc key callback)
key))
(defn unlisten!
"Removes registered listener from connection. See also [[listen!]]."
[conn key]
{:pre [(conn? conn) (atom? (:listeners (meta conn)))]}
(swap! (:listeners (meta conn)) dissoc key))
;; Datomic compatibility layer
(def ^:private last-tempid (atom -1000000))
(defn tempid
"Allocates and returns an unique temporary id (a negative integer). Ignores `part`. Returns `x` if it is specified.
Exists for Datomic API compatibility. Prefer using negative integers directly if possible."
([part]
(if (= part :db.part/tx)
:db/current-tx
(swap! last-tempid dec)))
([part x]
(if (= part :db.part/tx)
:db/current-tx
x)))
(defn resolve-tempid
"Does a lookup in tempids map, returning an entity id that tempid was resolved to.
Exists for Datomic API compatibility. Prefer using map lookup directly if possible."
[_db tempids tempid]
(get tempids tempid))
(defn db
"Returns the underlying Datalog database object from a connection. Note that Datalevin does not have \"db as a value\" feature, the returned object is NOT a database value, but a reference to the database object.
Exists for Datomic API compatibility. "
[conn]
{:pre [(conn? conn)]}
@conn)
(defn opts
"Return the option map of the Datalog DB"
[conn]
{:pre [(conn? conn)]}
(s/opts ^Store (.-store ^DB @conn)))
(defn schema
"Return the schema of Datalog DB"
[conn]
{:pre [(conn? conn)]}
(s/schema ^Store (.-store ^DB @conn)))
(defn update-schema
"Update the schema of an open connection to a Datalog db.
* `schema-update` is a map from attribute keywords to maps of corresponding
properties.
* `del-attrs` is a set of attributes to be removed from the schema, if there is
no datoms associated with them, otherwise an exception will be thrown.
* `rename-map` is a map of old attributes to new attributes, for renaming
attributes
Return the updated schema.
Example:
(update-schema conn {:new/attr {:db/valueType :db.type/string}})
(update-schema conn {:new/attr {:db/valueType :db.type/string}}
#{:old/attr1 :old/attr2})
(update-schema conn nil nil {:old/attr :new/attr}) "
([conn schema-update]
(update-schema conn schema-update nil nil))
([conn schema-update del-attrs]
(update-schema conn schema-update del-attrs nil))
([conn schema-update del-attrs rename-map]
{:pre [(conn? conn)]}
(let [^DB db (db conn)
^Store store (.-store db)]
(s/set-schema store schema-update)
(doseq [attr del-attrs] (s/del-attr store attr))
(doseq [[old new] rename-map] (s/rename-attr store old new))
(schema conn))))
(defonce ^:private connections (atom {}))
(defn- add-conn [dir conn] (swap! connections assoc dir conn))
(defn- new-conn
[dir schema opts]
(let [conn (create-conn dir schema opts)]
(add-conn dir conn)
conn))
(defn get-conn
"Obtain an open connection to a Datalog database. `dir` could be a local directory path or a dtlv connection URI string. Create the database if it does not exist. Reuse the same connection if a connection to the same database already exists. Open the database if it is closed. Return the connection.
See also [[create-conn]] and [[with-conn]]"
([dir]
(get-conn dir nil nil))
([dir schema]
(get-conn dir schema nil))
([dir schema opts]
(if-let [c (get @connections dir)]
(if (closed? c) (new-conn dir schema opts) c)
(new-conn dir schema opts))))
(defmacro with-conn
"Evaluate body in the context of an connection to the Datalog database.
If the database does not exist, this will create it. If it is closed,
this will open it. However, the connection will be closed in the end of
this call. If a database needs to be kept open, use `create-conn` and
hold onto the returned connection. See also [[create-conn]] and [[get-conn]]
`spec` is a vector of an identifier of the database connection, a path or
dtlv URI string, and optionally a schema map.
Example:
(with-conn [conn \"my-data-path\"]
;; body)
(with-conn [conn \"my-data-path\" {:likes {:db/cardinality :db.cardinality/many}}]
;; body)
"
[spec & body]
`(let [dir# ~(second spec)
schema# ~(second (rest spec))
opts# ~(second (rest (rest spec)))
conn# (get-conn dir# schema# opts#)]
(try
(let [~(first spec) conn#] ~@body)
(finally
(close conn#)))))
(defn transact
"Same as [[transact!]], but returns an immediately realized future.
Exists for Datomic API compatibility. Prefer using [[transact!]] if possible."
([conn tx-data] (transact conn tx-data nil))
([conn tx-data tx-meta]
{:pre [(conn? conn)]}
(let [res (transact! conn tx-data tx-meta)]
#?(:cljs
(reify
IDeref
(-deref [_] res)
IDerefWithTimeout
(-deref-with-timeout [_ _ _] res)
IPending
(-realized? [_] true))
:clj
(reify
clojure.lang.IDeref
(deref [_] res)
clojure.lang.IBlockingDeref
(deref [_ _ _] res)
clojure.lang.IPending
(isRealized [_] true))))))
;; ersatz future without proper blocking
#?(:cljs
(defn- future-call [f]
(let [res (atom nil)
realized (atom false)]
(js/setTimeout #(do (reset! res (f)) (reset! realized true)) 0)
(reify
IDeref
(-deref [_] @res)
IDerefWithTimeout
(-deref-with-timeout [_ _ timeout-val] (if @realized @res timeout-val))
IPending
(-realized? [_] @realized)))))
(defn transact-async
"Calls [[transact!]] on a future thread pool, returning immediately."
([conn tx-data] (transact-async conn tx-data nil))
([conn tx-data tx-meta]
{:pre [(conn? conn)]}
(future-call #(transact! conn tx-data tx-meta))))
(defn- rand-bits [^long pow]
(rand-int (bit-shift-left 1 pow)))
#?(:cljs
(defn- to-hex-string [n l]
(let [s (.toString n 16)
c (count s)]
(cond
(> c l) (subs s 0 l)
(< c l) (str (apply str (repeat (- l c) "0")) s)
:else s))))
(defn ^:no-doc squuid
"Generates a UUID that grow with time. Such UUIDs will always go to the end of the index and that will minimize insertions in the middle.
Consist of 64 bits of current UNIX timestamp (in seconds) and 64 random bits (2^64 different unique values per second)."
([]
(squuid #?(:clj (System/currentTimeMillis)
:cljs (.getTime (js/Date.)))))
([^long msec]
#?(:clj
(let [uuid (UUID/randomUUID)
time (int (/ msec 1000))
high (.getMostSignificantBits uuid)
low (.getLeastSignificantBits uuid)
new-high (bit-or (bit-and high 0x00000000FFFFFFFF)
(bit-shift-left time 32)) ]
(UUID. new-high low))
:cljs
(uuid
(str
(-> (int (/ msec 1000))
(to-hex-string 8))
"-" (-> (rand-bits 16) (to-hex-string 4))
"-" (-> (rand-bits 16) (bit-and 0x0FFF) (bit-or 0x4000) (to-hex-string 4))
"-" (-> (rand-bits 16) (bit-and 0x3FFF) (bit-or 0x8000) (to-hex-string 4))
"-" (-> (rand-bits 16) (to-hex-string 4))
(-> (rand-bits 16) (to-hex-string 4))
(-> (rand-bits 16) (to-hex-string 4)))))))
(defn ^:no-doc squuid-time-millis
"Returns time that was used in [[squuid]] call, in milliseconds, rounded to the closest second."
[uuid]
#?(:clj (-> (.getMostSignificantBits ^UUID uuid)
(bit-shift-right 32)
(* 1000))
:cljs (-> (subs (str uuid) 0 8)
(js/parseInt 16)
(* 1000))))
;; -------------------------------------
;; key value store API