«

Connect to a Database

This guide uses the Datomic Peer library. Instructions for using this guide with the Client Library are located in the Client library getting started guide. Review differences between the Peer and Client libraries.

Creating a database

Setup your project or run the included REPL. If you wish to persist your changes to disk then run a transactor and use the transactor's database URI below.

Include the Peer API:

(require '[datomic.api :as d])
=>
nil

Create the URI that allows you to create and connect to a database.

An in-memory database URI will have three parts:

  • datomic:, identifying it as a Datomic URI
  • mem://, the mem storage protocol that uses local memory instead of a persistent store
  • hello, the name of the database

If you ran a transactor to use local storage then supply the database uri that was supplied when you passed the -Ddatomic.printConnectionInfo=true flag. Replace <DB_NAME> with the name of the database that you want to create:

Bind a var, db-uri, to the value of the URI:

(def db-uri "datomic:mem://hello")

;; If you're using local dev storage, use the db uri you created earlier.
;; replace <DB-NAME> with your database name. It will look similar to:
;; (def db-uri "datomic:dev://localhost:4334/hello")
=>
#'user/db-uri

Create the "hello" database using the create-database function:

(d/create-database db-uri)
=>
true

Create a connection

Once you have created a database, you can use the Datomic Peer Library to interact with it.

Connect to the transactor in the same REPL that you used to create your database:

(def conn (d/connect db-uri))
=>
#'user/conn

You should see that a var was created called conn which is holding your database connection. You can inspect it:

conn
=> #object[datomic.peer.LocalConnection 0x6ca372ef "datomic.peer.LocalConnection@6ca372ef"]

Any transactions submitted to the connection will be persisted to the storage that you chose when creating your database.

Try adding a new entity with the :db/doc value "Hello world".

@(d/transact conn [{:db/doc "Hello world"}])
=>
{:db-before datomic.db.Db@33e08f8b, :db-after datomic.db.Db@7957bcc8, :tx-data [#datom[13194139534312 50 #inst "2022-03-18T09:33:18.156-00:00" 13194139534312 true] #datom[17592186045417 62 "Hello world" 13194139534312 true]], :tempids {-9223301668109598134 17592186045417}}

Interact with Datomic

The next step will be to define some schema for your new database.