Skip to content
Yoko Harada edited this page Nov 10, 2013 · 1 revision

The persistence API comes in two flavors: REST- and Peer-based. Although REST-bases API supports CRUD operations like a legacy RDBMS, it is a subset of Peer-based API.

The suitable persistent module will be selected based on URI to connect datomic. You don't need to care which module should be included. However, if you like to inlcude REST or Peer module explicitely, you can write it.

Peer

With Peer connection, you can create objects that know how to store themselves to Datomic through a Datomic Peer.

Peer connection as well as "require diametric/persistence/peer" are only available on JRuby. When you install the diametric gem with JRuby, all .jar files needed to run Datomic will be downloaded.

require 'diametric'
require 'diametric/persistence'

# database URI
# will create database if it does not already exist
Diametric::Persistence.establish_base_connection({:uri=>'datomic:mem://sample'})

REST

With REST connection, you can create objects that know how to store themselves to Datomic through the Datomic REST API. REST connection is available both on CRuby and JRuby. You need to download Datomic by yourself and start the server before you run the code.

require 'diametric'
require 'diametric/persistence'

# database url, database alias, database name
# will create database if it does not already exist
Diametric::Persistence.establish_base_connection({:uri => 'http://localhost:9000', :storage => 'free', :database => 'sample'})

Using persisted models

class Goat
  include Diametric::Entity
  include Diametric::Persistence
  
  attribute :name, String, :index => true
  attribute :age, Integer
end

goat = Goat.new(:name => 'Beans', :age => 2)
goat.dbid # => nil
goat.name # => "Beans"
goat.persisted? # => false
goat.new? # => true

goat.save
goat.dbid # => new id autogenerated
goat.name # => "Beans"
goat.persisted? # => true
goat.new? # => false

goats = Goat.where(:name => "Beans")
#=> [Goat(id: 1, age: 2, name: "Beans")]

goat = Goat.first(:name => "Beans")
#=> Goat(id: 1, age: 2, name: "Beans")

goats = Goat.filter(:<, :age, 3)
#=> [Goat(id: 1, age: 2, name: "Beans")]

goats = Goat.filter(:>, :age, 3)
#=> []