ROM::SQL

Gem Version Build Status Dependency Status Code Climate Test Coverage Inline docs

RDBMS support for Ruby Object Mapper.

Issues

Please report any issues in the main rom-rb/rom issue tracker.

Installation

Add this line to your application's Gemfile:

gem 'rom-sql'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rom-sql

Setup

ROM uses Sequel under the hood and exposes its Dataset API in relation objects. For schema migrations you can use its Migration API which is available via repositories.

require "rom-sql"
require "sqlite3"

setup = ROM.setup(:sql, "sqlite::memory")

setup.default.connection.create_table(:users) do
  primary_key :id
  String :name
  Boolean :admin
end

setup.default.connection.create_table(:tasks) do
  primary_key :id
  Integer :user_id
  String :title
end

Relations


class Users < ROM::Relation[:sql]
  def by_name(name)
    where(name: name)
  end
end

class Tasks < ROM::Relation[:sql]
end

rom = ROM.finalize.env

users = rom.relations.users
tasks = rom.relations.tasks

users.insert(id: 1, name: "Piotr")
tasks.insert(user_id: 1, title: "Be happy")

puts rom.relation(:users).by_name("Piotr").to_a.inspect
# => [{:id=>1, :name=>"Piotr", :user_id=>1}]

Mapping joins to aggregates

ROM doesn't have a relationship concept like in ActiveRecord or Sequel. Instead it provides a convenient interface for building joined relations that can be mapped to aggregate objects.

There's no lazy-loading, eager-loading or any other magic happening behind the scenes. You're in full control of how data are fetched from the database and it's an explicit operation.

Sequel's association DSL is available in relation definitions which enables association_join interface inside relations. To map joined results to aggregate objects wrap and group mapping transformation can be used

ROM.setup(:sql, "sqlite::memory")

class Users < ROM::Relation[:sql]
  one_to_many :tasks, key: :user_id

  def by_name(name)
    where(name: name)
  end

  def with_tasks
    association_join(:tasks, select: [:title])
  end
end

class UserMapper < ROM::Mapper
  relation :users
  register_as :model

  model name: 'User'

  group tasks: [:title]
end

rom = ROM.finalize.env

users = rom.relations.users
tasks = rom.relations.tasks

users.insert(id: 1, name: "Piotr")
tasks.insert(user_id: 1, title: "Be happy")

rom.relation(:users).with_tasks.by_name("Piotr").to_a
# => [{:id=>1, :name=>"Piotr", :admin=>nil, :title=>"Be happy"}]

rom.relation(:users).as(:model).with_tasks.by_name("Piotr").to_a
# => [#<User:0x007fb31542a098 @id=1, @name="Piotr", @tasks=[{:title=>"Be happy"}]>]

ROADMAP

For details please refer to issues.

License

See LICENSE file.