### Installing WebSocket Dependency
Source: https://github.com/tonsky/datascript/blob/master/README.md
Installs the WebSocket (ws) dependency using npm. This is required for running tests.
```shell
npm install ws
```
--------------------------------
### Running Datomic Compatibility Checks
Source: https://github.com/tonsky/datascript/blob/master/README.md
Executes compatibility checks with Datomic. This requires datomic-free to be installed locally.
```clojure
clj -M:datomic
```
--------------------------------
### Including DataScript via CDN - HTML
Source: https://github.com/tonsky/datascript/blob/master/README.md
This HTML snippet shows how to include the DataScript library in a web page using a CDN. This allows you to use DataScript in your JavaScript code without needing to install it locally.
```HTML
```
--------------------------------
### Accessing Transaction ID in Transaction
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Introduced in version 0.4.2, this allows referencing the transaction ID inside a transaction using `:db/current-tx` instead of the entity ID. It also provides a way to get the transaction ID from the `TxReport`.
```Clojure
(get-in tx-report [:tempids :db/current-tx])
```
--------------------------------
### Initializing DataScript Database
Source: https://github.com/tonsky/datascript/blob/master/release-js/README.md
This snippet demonstrates how to initialize a DataScript database. DataScript databases are immutable and based on persistent data structures, making them efficient for client-side applications.
```JavaScript
No code examples were provided in the text.
```
--------------------------------
### Querying DataScript with Datalog
Source: https://github.com/tonsky/datascript/blob/master/release-js/README.md
This snippet illustrates querying a DataScript database using Datalog. Datalog queries allow answering non-trivial questions about the current application state, providing a structured way to retrieve data.
```JavaScript
No code examples were provided in the text.
```
--------------------------------
### Running Benchmarks
Source: https://github.com/tonsky/datascript/blob/master/README.md
Navigates to the bench directory and executes the bench.clj script to run benchmarks. This measures the performance of DataScript.
```shell
cd bench
./bench.clj
```
--------------------------------
### Create DataScript DB with IStorage during initialization
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Creates an empty DataScript database with a specified storage implementation during initialization. This allows the database to remember its storage for subsequent `d/store` calls without needing to provide the storage argument.
```Clojure
(let [schema nil
db (d/empty-db schema {:storage storage})]
(d/store db))
```
--------------------------------
### Creating a Connection with Storage in DataScript
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
This snippet demonstrates how to create a DataScript connection with storage. When a connection is created with storage, every transaction will be automatically stored.
```clojure
(def conn
(d/create-conn schema {:storage storage}))
(d/transact! conn
[[:db/add 1 :name "Ivan"]]) ;; <- will be stored automatically
(d/transact! conn
[[:db/add 2 :name "Oleg"]]) ;; <- will be stored again
```
--------------------------------
### Implement IStorage protocol for DataScript persistence
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Defines a storage implementation for DataScript using the `datascript.storage/IStorage` protocol. This involves implementing `-store` for writing data and `-restore` for reading data from a persistent storage.
```Clojure
(def storage
(reify datascript.storage/IStorage
(-store [_ addr+data-seq]
(doseq [[addr data] addr+data-seq]
... serialize and store -> somehow ...))
(-restore [_ addr]
... load and de-serialize stored at )))
```
--------------------------------
### Running Tests with Kaocha Runner
Source: https://github.com/tonsky/datascript/blob/master/README.md
Executes the tests using the Kaocha test runner. This command is used to verify the functionality of DataScript.
```clojure
clj -M:test -m kaocha.runner
```
--------------------------------
### Creating and Using File Storage in DataScript
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
This snippet demonstrates how to create a file storage instance in DataScript and store/restore a database. File storage persists the database to a directory on the file system.
```clojure
(def storage
(d/file-storage "/tmp/db"))
(d/store db storage)
(def db'
(d/restore storage))
```
--------------------------------
### Shadow-cljs compiler options
Source: https://github.com/tonsky/datascript/blob/master/README.md
This snippet shows the required compiler options for shadow-cljs when using DataScript. Add this to your build configuration.
```clj
:compiler-options {:externs ["datascript/externs.js"]}
```
--------------------------------
### Store DataScript DB using IStorage implementation
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Stores a DataScript database using a provided `IStorage` implementation. The `d/store` function persists the database to the storage, enabling incremental updates on subsequent calls.
```Clojure
(d/store db storage)
```
```Clojure
(let [db' (d/db-with db
tx-data)]
(d/store db' storage))
```
--------------------------------
### Querying with Return Maps using Keys
Source: https://github.com/tonsky/datascript/blob/master/docs/queries.md
Demonstrates how to use the `:keys` option in a Datascript query to return a set of maps instead of tuples. The keys specified after `:keys` determine the keys in the resulting maps, mapping them to the corresponding find elements.
```datascript
[:find ?name ?age ?email,
...]
=> #{["Ivan" 10 "ivan@"]
["Oleg" 20 "oleg@"]
["Sergey" 30 "sergey@"]}
[:find ?name ?age ?email
:keys name A e-mail
...]
=> #{{:name "Ivan", :A 10, :e-mail "ivan@"}
{:name "Oleg", :A 20, :e-mail "oleg@"}
{:name "Sergey", :A 30, :e-mail "sergey@"}}
```
--------------------------------
### Importing DataScript as RequireJS Module - JavaScript
Source: https://github.com/tonsky/datascript/blob/master/README.md
This JavaScript snippet demonstrates how to import DataScript as a RequireJS module. This is used in environments that use RequireJS for asynchronous module loading.
```JavaScript
require(['datascript'], function(ds) { ... });
```
--------------------------------
### Restoring a Connection from Storage in DataScript
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
This snippet shows how to restore a DataScript connection from storage. This allows you to retrieve a previously stored database state.
```clojure
(def conn
(d/restore-conn storage))
```
--------------------------------
### Using Tuple Function in Query
Source: https://github.com/tonsky/datascript/blob/master/docs/queries.md
Demonstrates how to use the `tuple` function within a Datascript query to create a tuple from input values. The query finds a tuple `?tup` created from the input variables `?a` and `?b`.
```datascript
[;; query
[:find ?tup
:in ?a ?b
:where [(tuple ?a ?b) ?tup]]
;; inputs
1 2
;; result
#{[[1 2]]}]
```
--------------------------------
### Defining Return Map Syntax
Source: https://github.com/tonsky/datascript/blob/master/docs/queries.md
Defines the syntax for return maps in Datascript queries, including options for keys, symbols, and strings. These options determine the format of the keys in the returned maps.
```datascript
return-map = (return-keys | return-syms | return-strs)
return-keys = ':keys' symbol+
return-syms = ':syms' symbol+
return-strs = ':strs' symbol+
```
--------------------------------
### Aggregate Query - Clojure
Source: https://github.com/tonsky/datascript/blob/master/README.md
This Clojure snippet demonstrates the use of aggregates in a DataScript query. It finds the maximum and minimum amounts for each color in a dataset, using the `max` and `min` aggregate functions.
```Clojure
(d/q '[ :find ?color (max ?amount ?x) (min ?amount ?x)
:in [[?color ?x]] ?amount ]
[[:red 10] [:red 20] [:red 30] [:red 40] [:red 50]
[:blue 7] [:blue 8]]
3)
```
--------------------------------
### Serialize DataScript DB to String using print/read
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Serializes a DataScript database into a string representation using `pr-str`. This string can then be stored on disk. Deserialization is achieved using `read` or `clojure.edn/read-string` with data readers.
```Clojure
(def string
(pr-str db))
```
```Clojure
(read string)
```
```Clojure
(clojure.edn/read-string
{:readers d/data-readers}
string)
```
--------------------------------
### Restore DataScript DB from IStorage implementation
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Restores a DataScript database from a given `IStorage` implementation using `d/restore`. The restoration process is lazy, meaning data is only read from the storage when it is accessed.
```Clojure
(def db
(d/restore storage))
```
```Clojure
(first (d/datoms db))
```
--------------------------------
### Serialize DataScript DB to JSON-friendly format
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Converts a DataScript database into a serialization-friendly data structure using `d/serializable`. This structure can then be serialized to JSON using libraries like Cheshire or other serialization methods.
```Clojure
(d/serializable db)
```
```Clojure
(cheshire/generate-string
(d/serializable db))
```
--------------------------------
### Importing DataScript as CommonJS Module - JavaScript
Source: https://github.com/tonsky/datascript/blob/master/README.md
This JavaScript snippet demonstrates how to import DataScript as a CommonJS module. This is typically used in Node.js environments where modules are managed using `require`.
```JavaScript
var ds = require('datascript');
```
--------------------------------
### Deserialize DataScript DB from JSON-friendly format
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
Restores a DataScript database from a serialized format using `d/from-serializable`. This function takes a deserialized data structure (e.g., parsed JSON) and reconstructs the DataScript database.
```Clojure
(def db
(d/from-serializable
(cheshire/parse-string
string)))
```
--------------------------------
### Watching Tests with Watch Script
Source: https://github.com/tonsky/datascript/blob/master/README.md
Executes a shell script to watch for file changes and automatically re-run tests. This is useful for continuous testing during development.
```shell
./script/watch.sh
```
--------------------------------
### Adding DataScript dependency using deps.edn
Source: https://github.com/tonsky/datascript/blob/master/README.md
This snippet shows how to add DataScript as a dependency to your Clojure project using deps.edn. Add the following to your deps.edn file.
```clj
datascript/datascript {:mvn/version "1.7.5"}
```
--------------------------------
### Implicit Join and Multi-valued Attribute Query - Clojure
Source: https://github.com/tonsky/datascript/blob/master/README.md
This Clojure snippet demonstrates an implicit join and queries a multi-valued attribute in DataScript. It creates a connection with a schema, transacts data with a multi-valued attribute `:aka`, and then queries for entities with a specific `:aka` value, returning their name and age.
```Clojure
(require '[datascript.core :as d])
;; Implicit join, multi-valued attribute
(let [schema {:aka {:db/cardinality :db.cardinality/many}}
conn (d/create-conn schema)]
(d/transact! conn [ { :db/id -1
:name "Maksim"
:age 45
:aka ["Max Otto von Stierlitz", "Jack Ryan"] } ])
(d/q '[ :find ?n ?a
:where [?e :aka "Max Otto von Stierlitz"]
[?e :name ?n]
[?e :age ?a] ]
@conn))
```
--------------------------------
### Garbage Collection in DataScript
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
This snippet shows how to call the garbage collection function in DataScript. Garbage collection removes unused data from the storage, preventing it from growing indefinitely.
```clojure
(d/collect-garbage storage)
```
--------------------------------
### Adding DataScript dependency using Leiningen
Source: https://github.com/tonsky/datascript/blob/master/README.md
This snippet shows how to add DataScript as a dependency to your Clojure project using Leiningen. Add the following line to your project's dependencies.
```clj
[datascript "1.7.5"]
```
--------------------------------
### Querying Indexed Composite Tuples
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Shows how to use `d/index-range` to query composite tuple attributes, which are automatically indexed by DataScript. This allows for efficient retrieval of entities based on composite key ranges.
```Clojure
(d/index-range db :a+b+c ["A" "B" "C"] ["a" "b" "c"])
; => [#db/Datom 1 :a+b+c ["a" "b" "c"]]
```
--------------------------------
### Referring to Externs File
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Introduced in version 0.2.1, this allows referring to the externs file using `:externs [datascript/externs.js"]`. This simplifies the process of specifying externs when using datascript as a dependency.
```Clojure
:externs [datascript/externs.js"]
```
--------------------------------
### Setting Reference Type for DataScript Node Values
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
This option determines how node values are stored in DataScript, influencing memory management. `:strong` keeps values in memory, `:soft` uses SoftReferences for potential unloading under memory pressure, and `:weak` employs WeakReferences for more aggressive unloading, intended for use with pluggable caches.
```clojure
:ref-type :strong | :soft | :weak, default :soft
```
--------------------------------
### Creating Datoms in Datascript
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Introduced in version 0.7.0, this function allows the creation of new datoms. It takes entity ID, attribute, value, and optionally transaction and added flag as arguments. This function is part of the datascript namespace.
```Clojure
(datascript/datom e a v & [tx added])
```
--------------------------------
### Automatic Population of Composite Tuple
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Demonstrates how DataScript automatically populates the composite attribute `:a+b+c` when attributes `:a` and `:b` are asserted for an entity. The missing attribute `:c` defaults to `nil`.
```Clojure
[{:db/id 1, :a "a", :b "b"}]
```
```Clojure
(d/pull db '[*] 1)
; => {:db/id 1, :a "a", :b "b", :a+b+c ["a" "b" nil]}
```
--------------------------------
### Untuple Function Definition
Source: https://github.com/tonsky/datascript/blob/master/docs/queries.md
Defines the syntax for the `untuple` function in Datascript queries. This function takes a tuple as input and destructures it, allowing you to name each element of the tuple.
```datascript
[(untuple ?tup) [?a ?b]]
```
--------------------------------
### Configuring B-tree Branching Factor in DataScript
Source: https://github.com/tonsky/datascript/blob/master/docs/storage.md
This option controls the width of B-trees in DataScript. A higher branching factor results in fewer, larger nodes, which can be beneficial when writing to storage has a high overhead. Conversely, a lower branching factor creates more granular nodes, suitable for scenarios where writing small keys is cheaper.
```clojure
:branching-factor , default 512
```
--------------------------------
### Tuple Function Definition
Source: https://github.com/tonsky/datascript/blob/master/docs/queries.md
Defines the syntax for the `tuple` function in Datascript queries. This function takes one or more values as input and returns a tuple containing those values.
```datascript
[(tuple ?a ...) ?tup]
```
--------------------------------
### Requiring Datascript Core Namespace
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
This code snippet demonstrates how to require the `datascript.core` namespace in Clojure, which is the recommended way to use Datascript from version 0.13.0 onwards. This change was made to avoid the discouraged use of top-level namespaces in ClojureScript.
```clojure
(require '[datascript.core :as d])
```
--------------------------------
### Aggregate Function Syntax
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Demonstrates the syntax for calling custom aggregate functions in Datascript queries. Custom aggregate functions must be called using the `aggregate` keyword, while built-in aggregates work as before. This change was introduced in version 0.8.0.
```Clojure
(q '[:find (aggregate ?myfn ?e) :in $ ?myfn ...])
```
```Clojure
(q '[:find (count ?e) ...])
```
--------------------------------
### Destructuring, Function Call, Predicate Query - Clojure
Source: https://github.com/tonsky/datascript/blob/master/README.md
This Clojure snippet demonstrates destructuring, function calls, and predicate calls within a DataScript query. It defines a query that uses a range function and an even? predicate to filter data based on specified conditions.
```Clojure
(d/q '[ :find ?k ?x
:in [[?k [?min ?max]] ...] ?range
:where [(?range ?min ?max) [?x ...]]
[(even? ?x)] ]
{ :a [1 7], :b [2 4] }
range)
```
--------------------------------
### Using Compare-and-Swap Transaction Function
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Added in version 0.4.1, `:db.fn/cas` is a transaction function that allows for compare-and-swap operations. This function enables conditional updates within a transaction.
```Clojure
:db.fn/cas
```
--------------------------------
### Conn Atom Access
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Demonstrates the change in accessing listeners from the Conn metadata. Before 1.6.0, listeners were accessed directly from the Conn meta. After 1.6.0, listeners are accessed from the atom within the Conn.
```clojure
`@(:listeners (meta conn))`
```
```clojure
`(:listeners @(:atom conn))`
```
--------------------------------
### Using Composite Tuple in Lookup Refs
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Shows how to use a composite tuple with a unique identity in a lookup ref to retrieve an entity.
```Clojure
(d/entity (d/db conn) [:a+b ["a" "b"]])
; => {:db/id 4, :a "a", :b "b", :a+b ["a" "b"]}
```
--------------------------------
### Using Untuple Function in Query
Source: https://github.com/tonsky/datascript/blob/master/docs/queries.md
Demonstrates how to use the `untuple` function within a Datascript query to deconstruct a tuple. The query finds the value of `?b` after destructuring the input tuple `?tup` into `?a` and `?b`.
```datascript
[;; query
[:find ?b
:in ?tup
:where [(untuple ?tup) [?a ?b]]]
;; inputs
[1 2]
;; result
#{[2]}]
```
--------------------------------
### Recursive Rule Query - Clojure
Source: https://github.com/tonsky/datascript/blob/master/README.md
This Clojure snippet demonstrates a recursive rule in a DataScript query. It defines a `follows` rule that can recursively determine relationships between entities, and then queries for entities that follow each other based on this rule.
```Clojure
(d/q '[ :find ?u1 ?u2
:in $ %
:where (follows ?u1 ?u2) ]
[ [1 :follows 2]
[2 :follows 3]
[3 :follows 4] ]
'[ [(follows ?e1 ?e2)
[?e1 :follows ?e2]]
[(follows ?e1 ?e2)
[?e1 :follows ?t]
(follows ?t ?e2)] ])
```
--------------------------------
### Defining db/index Schema Attribute
Source: https://github.com/tonsky/datascript/blob/master/CHANGELOG.md
Defines the `:db/index` schema attribute, which controls whether attributes are indexed in AVET. Attributes with `:db/index true`, `:db/unique :db.unique/identity`, `:db/unique :db.unique/value`, or `:db/valueType :db.type/ref` are indexed by default. This configuration impacts query performance and storage of data.
```Clojure
:db/index true
```
```Clojure
:db/unique :db.unique/identity
```
```Clojure
:db/unique :db.unique/value
```
```Clojure
:db/valueType :db.type/ref
```
--------------------------------
### Defining a Composite Tuple
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Defines a composite tuple `:a+b+c` consisting of attributes `:a`, `:b`, and `:c`. This configuration tells DataScript to automatically manage the composite attribute.
```Clojure
{:a+b+c {:db/tupleAttrs [:a :b :c]}}
```
--------------------------------
### Automatic Update of Composite Tuple
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Shows how DataScript automatically updates the composite tuple `:a+b+c` when the underlying attributes `:a`, `:b`, and `:c` are modified via a transaction.
```Clojure
(d/transact! conn
[{:db/id 1, :a "A", :b "B", :c "c"}])
; => {:db/id 1, :a "A", :b "B", :c "c", :a+b+c ["A" "B" "c"]}
```
--------------------------------
### Enforcing Uniqueness Constraint on Composite Tuple
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Demonstrates how DataScript enforces the uniqueness constraint on the composite tuple `:a+b`. Attempting to insert an entity with a duplicate composite key results in an exception.
```Clojure
(d/transact! conn
[{:db/id 5, :a "A", :b "B"}])
; => clojure.lang.ExceptionInfo: Cannot add #datascript/Datom [5 :a+b ["A" "B"] 536870916 true] because of unique constraint: (#datascript/Datom [1 :a+b ["A" "b"] 536870915 true])
```
--------------------------------
### Defining Unique Identity Composite Tuples
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Defines a composite tuple `:a+b` with a uniqueness constraint on its identity. This allows the composite tuple to be used in lookup refs.
```Clojure
(def conn (d/create-conn {:a+b {:db/tupleAttrs [:a :b]
:db/unique :db.unique/identity}}))
```
--------------------------------
### Defining Unique Composite Tuples
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Defines a composite tuple `:a+b` with a uniqueness constraint on its value. This ensures that the combination of `:a` and `:b` is unique across all entities.
```Clojure
(def conn (d/create-conn {:a+b {:db/tupleAttrs [:a :b]
:db/unique :db.unique/value}}))
(d/transact! conn
[{:db/id 1, :a "A", :b "B"}
{:db/id 2, :a "A", :b "b"}
{:db/id 3, :a "a", :b "B"}
{:db/id 4, :a "a", :b "b"}])
```
--------------------------------
### Automatic Retraction of Composite Tuple
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Illustrates how DataScript automatically retracts the composite tuple attribute when all of its constituent attributes are retracted from an entity.
```Clojure
(d/transact! conn
[[:db/add 1 :d "d"]
[:db/retract 1 :a]
[:db/retract 1 :b]
[:db/retract 1 :c]])
; => {:db/id 1, :d "d"}
```
--------------------------------
### Preventing Direct Update of Composite Tuple
Source: https://github.com/tonsky/datascript/blob/master/docs/tuples.md
Demonstrates that direct modification of composite tuple attributes is not allowed. DataScript manages these attributes automatically based on the underlying attributes.
```Clojure
(d/transact! conn
[{:db/id 1, :a+b+c ["A" "B" "c"]}])
; => clojure.lang.ExceptionInfo: Can’t modify tuple attrs directly: [:db/add 1 :a+b+c ["A" "B" "c"]]
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.