Class: ROM::Relation

Inherits:
Object
  • Object
show all
Extended by:
Dry::Core::ClassAttributes, ClassInterface
Includes:
Commands, Materializable
Defined in:
core/lib/rom/relation.rb,
core/lib/rom/relation/name.rb,
core/lib/rom/relation/wrap.rb,
core/lib/rom/relation/graph.rb,
core/lib/rom/relation/loaded.rb,
core/lib/rom/relation/curried.rb,
core/lib/rom/relation/combined.rb,
core/lib/rom/relation/commands.rb,
core/lib/rom/relation/view_dsl.rb,
core/lib/rom/relation/composite.rb,
core/lib/rom/relation/materializable.rb,
core/lib/rom/relation/class_interface.rb

Overview

Base relation class

Relation is a proxy for the dataset object provided by the gateway. It can forward methods to the dataset, which is why the "native" interface of the underlying gateway is available in the relation

Individual adapters sets up their relation classes and provide different APIs depending on their persistence backend.

Direct Known Subclasses

Memory::Relation

Defined Under Namespace

Modules: ClassInterface, Commands, Materializable Classes: Combined, Composite, Curried, Graph, Loaded, ViewDSL, Wrap

Constant Summary

NOOP_OUTPUT_SCHEMA =

Default no-op output schema which is called in Relation#each

-> tuple { tuple }.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#datasetObject (readonly)

Returns dataset used by the relation provided by relation's gateway

Returns:

  • (Object)

    dataset used by the relation provided by relation's gateway



135
# File 'core/lib/rom/relation.rb', line 135

param :dataset

#mappersMapperRegistry (readonly)

Returns an optional mapper registry (empty by default)

Returns:



178
# File 'core/lib/rom/relation.rb', line 178

option :mappers, default: -> { self.class.mapper_registry }

#nameObject (readonly)

Returns The relation name

Returns:

  • (Object)

    The relation name



147
# File 'core/lib/rom/relation.rb', line 147

option :name, default: -> { self.class.schema ? self.class.schema.name : self.class.default_name }

#relation_nameObject (readonly) Originally defined in module ClassInterface

Raises:

#schemaSchema (readonly)

Returns relation schema, defaults to class-level canonical schema (if it was defined) and sets an empty one as the fallback

Returns:

  • (Schema)

    relation schema, defaults to class-level canonical schema (if it was defined) and sets an empty one as the fallback



142
# File 'core/lib/rom/relation.rb', line 142

option :schema, default: -> { self.class.schema || self.class.default_schema }

#struct_namespace(ns) ⇒ Relation (readonly)

Return a new relation configured with the provided struct namespace

Parameters:

  • ns (Module)

    Custom namespace module for auto-structs

Returns:



174
# File 'core/lib/rom/relation.rb', line 174

option :struct_namespace, reader: false, default: -> { self.class.struct_namespace }

Class Method Details

.[](adapter) ⇒ Class Originally defined in module ClassInterface

Return adapter-specific relation subclass

Examples:

ROM::Relation[:memory]
# => ROM::Memory::Relation

Returns:

  • (Class)

.auto_mapBoolean .auto_map(value) ⇒ Object

Whether or not a relation and its compositions should be auto-mapped

Overloads:

  • .auto_mapBoolean

    Return auto_map setting value

    Returns:

    • (Boolean)
  • .auto_map(value) ⇒ Object

    Set auto_map value



82
# File 'core/lib/rom/relation.rb', line 82

defines :auto_map

.auto_structBoolean .auto_struct(value) ⇒ Object

Whether or not tuples should be auto-mapped to structs

Overloads:

  • .auto_structBoolean

    Return auto_struct setting value

    Returns:

    • (Boolean)
  • .auto_struct(value) ⇒ Object

    Set auto_struct value



93
# File 'core/lib/rom/relation.rb', line 93

defines :auto_struct

.dataset(&block) ⇒ Object Originally defined in module ClassInterface

Set or get custom dataset block

This block will be evaluated when a relation is instantiated and registered in a relation registry.

Examples:

class Users < ROM::Relation[:memory]
  dataset { sort_by(:id) }
end

.forward(*methods) ⇒ Object Originally defined in module ClassInterface

Dynamically define a method that will forward to the dataset and wrap response in the relation itself

Examples:

class SomeAdapterRelation < ROM::Relation
  forward :super_query
end

.gatewaySymbol .gateway(gateway_key) ⇒ Object

Manage the gateway

Overloads:

  • .gatewaySymbol

    Return the gateway key that the relation is associated with

    Returns:

    • (Symbol)
  • .gateway(gateway_key) ⇒ Object

    Link the relation to a gateway. Change this setting if the relation is defined on a non-default gateway

    Examples:

    class Users < ROM::Relation[:sql]
      gateway :custom
    end

    Parameters:

    • gateway_key (Symbol)


71
# File 'core/lib/rom/relation.rb', line 71

defines :gateway

.schema(dataset = nil, as: nil, infer: false, &block) ⇒ Schema Originally defined in module ClassInterface

Specify canonical schema for a relation

With a schema defined commands will set up a type-safe input handler automatically

Examples:

class Users < ROM::Relation[:sql]
  schema do
    attribute :id, Types::Serial
    attribute :name, Types::String
  end
end

# access schema from a finalized relation
users.schema

Parameters:

  • dataset (Symbol) (defaults to: nil)

    An optional dataset name

  • infer (Boolean)

    Whether to do an automatic schema inferring

Returns:

.struct_namespaceModule .struct_namespace(namespace) ⇒ Object

Get or set a namespace for auto-generated struct classes. By default, new struct classes are created within ROM::Struct

@example using custom namespace class Users < ROM::Relation[:sql] struct_namespace Entities end

users.by_pk(1).one! # => #

Overloads:

  • .struct_namespaceModule

    Returns Default struct namespace

    Returns:

    • (Module)

      Default struct namespace

  • .struct_namespace(namespace) ⇒ Object

    Parameters:

    • namespace (Module)


112
# File 'core/lib/rom/relation.rb', line 112

defines :struct_namespace

.use(plugin, options = EMPTY_HASH) ⇒ Object Originally defined in module ClassInterface

Include a registered plugin in this relation class

Parameters:

  • plugin (Symbol)
  • options (Hash) (defaults to: EMPTY_HASH)

Options Hash (options):

  • :adapter (Symbol) — default: :default

    first adapter to check for plugin

#view(name, schema, &block) ⇒ Symbol #view(name, &block) ⇒ Symbol Originally defined in module ClassInterface

Define a relation view with a specific schema

This method should only be used in cases where a given adapter doesn't support automatic schema projection at run-time.

It's not needed in rom-sql

Overloads:

  • #view(name, schema, &block) ⇒ Symbol

    Examples:

    View with the canonical schema

    class Users < ROM::Relation[:sql]
      view(:listing, schema) do
        order(:name)
      end
    end

    View with a projected schema

    class Users < ROM::Relation[:sql]
      view(:listing, schema.project(:id, :name)) do
        order(:name)
      end
    end
  • #view(name, &block) ⇒ Symbol

    Examples:

    View with the canonical schema and arguments

    class Users < ROM::Relation[:sql]
      view(:by_name) do |name|
        where(name: name)
      end
    end

    View with projected schema and arguments

    class Users < ROM::Relation[:sql]
      view(:by_name) do
        schema { project(:id, :name) }
        relation { |name| where(name: name) }
      end
    end

    View with a schema extended with foreign attributes

    class Users < ROM::Relation[:sql]
      view(:index) do
        schema { append(relations[:tasks][:title]) }
        relation { |name| where(name: name) }
      end
    end

Returns:

  • (Symbol)

    view method name

Instance Method Details

#[](name) ⇒ Attribute

Return schema attribute

Examples:

accessing canonical attribute

users[:id]
# => #<ROM::SQL::Attribute[Integer] primary_key=true name=:id source=ROM::Relation::Name(users)>

accessing joined attribute

tasks_with_users = tasks.join(users).select_append(tasks[:title])
tasks_with_users[:title, :tasks]
# => #<ROM::SQL::Attribute[String] primary_key=false name=:title source=ROM::Relation::Name(tasks)>

Returns:



204
205
206
# File 'core/lib/rom/relation.rb', line 204

def [](name)
  schema[name]
end

#as(aliaz) ⇒ Relation

Return a new relation with an aliased name

Examples:

users.as(:people)

Parameters:

  • aliaz (Symbol)

    Aliased name

Returns:



561
562
563
# File 'core/lib/rom/relation.rb', line 561

def as(aliaz)
  with(name: name.as(aliaz))
end

#associationsAssociationSet

Return schema's association set (empty by default)

Returns:



459
460
461
# File 'core/lib/rom/relation.rb', line 459

def associations
  schema.associations
end

#callRelation::Loaded

Loads a relation

Returns:



351
352
353
# File 'core/lib/rom/relation.rb', line 351

def call
  Loaded.new(self)
end

#combine(*associations) ⇒ Relation #combine(*associations, **nested_associations) ⇒ Relation #combine(associations) ⇒ Relation

Combine with other relations using configured associations

Overloads:

  • #combine(*associations) ⇒ Relation

    Examples:

    users.combine(:tasks, :posts)

    Parameters:

    • *associations (Array<Symbol>)

      A list of association names

  • #combine(*associations, **nested_associations) ⇒ Relation

    Examples:

    users.combine(:tasks, posts: :authors)

    Parameters:

    • *associations (Array<Symbol>)

      A list of association names

    • *nested_associations (Hash)

      A hash with nested association names

  • #combine(associations) ⇒ Relation

    Examples:

    users.combine(posts: [:authors, reviews: [:tags, comments: :author])

    Parameters:

    • *associations (Hash)

      A hash with nested association names

Returns:



251
252
253
# File 'core/lib/rom/relation.rb', line 251

def combine(*args)
  combine_with(*nodes(*args))
end

#combine_with(*others) ⇒ Relation::Graph

Composes with other relations

Parameters:

  • others (Array<Relation>)

    The other relation(s) to compose with

Returns:



262
263
264
# File 'core/lib/rom/relation.rb', line 262

def combine_with(*others)
  Combined.new(self, others)
end

#command(type, mapper: nil, use: EMPTY_ARRAY, plugins_options: EMPTY_HASH, **opts) ⇒ ROM::Command Originally defined in module Commands

Return a command for the relation

This method can either return an existing custom command identified by type param, or generate a command dynamically based on relation AST.

Examples:

build a simple :create command

users.command(:create)

build a command which returns multiple results

users.command(:create, result: many)

build a command which uses a specific plugin

users.command(:create, plugin: :timestamps)

build a command which sends results through a custom mapper

users.command(:create, mapper: :my_mapper_identifier)

return an existing custom command

users.command(:my_custom_command_identifier)

Parameters:

  • type (Symbol)

    The command type (:create, :update or :delete)

  • opts (Hash)

    Additional options

Options Hash (**opts):

  • :mapper (Symbol) — default: nil

    An optional mapper applied to the command result

  • :use (Array<Symbol>) — default: []

    A list of command plugins

  • :result (Symbol) — default: :one

    Set how many results the command should return. Can be :one or :many

Returns:

#each {|Hash| ... } ⇒ Enumerator

Yields relation tuples

Every tuple is processed through Relation#output_schema, it's a no-op by default

Yields:

  • (Hash)

Returns:

  • (Enumerator)

    if block is not provided



217
218
219
220
221
222
223
224
225
# File 'core/lib/rom/relation.rb', line 217

def each
  return to_enum unless block_given?

  if auto_struct?
    mapper.(dataset.map { |tuple| output_schema[tuple] }).each { |struct| yield(struct) }
  else
    dataset.each { |tuple| yield(output_schema[tuple]) }
  end
end

#eager_load(assoc) ⇒ Relation

Return a graph node prepared by the given association

Parameters:

  • An (Association)

    association object

Returns:



300
301
302
303
304
305
306
307
308
# File 'core/lib/rom/relation.rb', line 300

def eager_load(assoc)
  relation = assoc.prepare(self)

  if assoc.override?
    relation.(assoc)
  else
    relation.preload_assoc(assoc)
  end
end

#firstObject Originally defined in module Materializable

Return first tuple from a relation coerced to an array

Returns:

  • (Object)

#map_to(klass, **opts) ⇒ Relation::Composite

Return a new relation that will map its tuples to instance of the provided class

Examples:

users.map_to(MyUserModel)

Parameters:

  • klass (Class)

    Your custom model class

Returns:



547
548
549
# File 'core/lib/rom/relation.rb', line 547

def map_to(klass, **opts)
  with(opts.merge(auto_struct: true, meta: { model: klass }))
end

#map_with(model) ⇒ Relation #map_with(*mappers) ⇒ Relation #map_with(*mappers, auto_map: true) ⇒ Relation

Maps the wrapped relation with other mappers available in the registry

Overloads:

  • #map_with(model) ⇒ Relation

    Map tuples to the provided custom model class

    Examples:

    users.map_with(MyUserModel)

    Parameters:

    • ] (Class)

      model Your custom model class

  • #map_with(*mappers) ⇒ Relation

    Map tuples using registered mappers

    Examples:

    users.map_with(:my_mapper, :my_other_mapper)

    Parameters:

    • mappers (Array<Symbol>)

      A list of mapper identifiers

  • #map_with(*mappers, auto_map: true) ⇒ Relation

    Map tuples using auto-mapping and custom registered mappers

    If auto_map is enabled, your mappers will be applied after performing default auto-mapping. This means that you can compose complex relations and have them auto-mapped, and use much simpler custom mappers to adjust resulting data according to your requirements.

    Examples:

    users.map_with(:my_mapper, :my_other_mapper, auto_map: true)

    Parameters:

    • mappers (Array<Symbol>)

      A list of mapper identifiers

Returns:

  • (Relation)

    A new relation proxy with pipelined relation



533
534
535
# File 'core/lib/rom/relation.rb', line 533

def map_with(*names, **opts)
  super(*names).with(opts)
end

#new(dataset, new_opts = EMPTY_HASH) ⇒ Object

Return a new relation with provided dataset and additional options

Use this method whenever you need to use dataset API to get a new dataset and you want to return a relation back. Typically relation API should be enough though. If you find yourself using this method, it might be worth to consider reporting an issue that some dataset functionality is not available through relation API.

Examples:

with a new dataset

users.new(users.dataset.some_method)

with a new dataset and options

users.new(users.dataset.some_method, other: 'options')

Parameters:

  • dataset (Object)
  • new_opts (Hash) (defaults to: EMPTY_HASH)

    Additional options



418
419
420
421
422
423
424
425
426
427
428
429
# File 'core/lib/rom/relation.rb', line 418

def new(dataset, new_opts = EMPTY_HASH)
  opts =
    if new_opts.empty?
      options
    elsif new_opts.key?(:schema)
      options.merge(new_opts).reject { |k, _| k == :input_schema || k == :output_schema }
    else
      options.merge(new_opts)
    end

  self.class.new(dataset, opts)
end

#node(name) ⇒ Relation

Create a graph node for a given association identifier

Parameters:

  • (Symbol, Relation::Name)

Returns:



287
288
289
290
291
# File 'core/lib/rom/relation.rb', line 287

def node(name)
  assoc = associations[name]
  other = assoc.node
  other.eager_load(assoc)
end

#oneObject Originally defined in module Materializable

Delegate to loaded relation and return one object

Returns:

  • (Object)

See Also:

#one!Object Originally defined in module Materializable

Delegate to loaded relation and return one object

Returns:

  • (Object)

See Also:

#schemasHash<Symbol=>Schema>

Return all registered relation schemas

This holds all schemas defined via view DSL

Returns:



588
589
590
# File 'core/lib/rom/relation.rb', line 588

def schemas
  self.class.schemas
end

#to_aArray<Hash>

Materializes a relation into an array

Returns:

  • (Array<Hash>)


360
361
362
# File 'core/lib/rom/relation.rb', line 360

def to_a
  to_enum.to_a
end

#to_astArray

Returns AST for the wrapped relation

Returns:

  • (Array)


468
469
470
# File 'core/lib/rom/relation.rb', line 468

def to_ast
  [:relation, [name.relation, attr_ast, meta_ast]]
end

#with(opts) ⇒ Relation

Returns a new instance with the same dataset but new options

Examples:

users.with(output_schema: -> tuple { .. })

Parameters:

  • opts (Hash)

    New options

Returns:



443
444
445
446
447
448
449
450
451
452
# File 'core/lib/rom/relation.rb', line 443

def with(opts)
  new_options =
    if opts.key?(:meta)
      opts.merge(meta: meta.merge(opts[:meta]))
    else
      opts
    end

  new(dataset, options.merge(new_options))
end

#wrap(*names) ⇒ Wrap

Wrap other relations using association names

Examples:

tasks.wrap(:owner)

Parameters:

  • names (Array<Symbol>)

    A list with association identifiers

Returns:



331
332
333
# File 'core/lib/rom/relation.rb', line 331

def wrap(*names)
  wrap_around(*names.map { |n| associations[n].wrap })
end

#wrap_around(*others) ⇒ Relation::Wrap

Wrap around other relations

Parameters:

  • others (Array<Relation>)

    Other relations

Returns:



342
343
344
# File 'core/lib/rom/relation.rb', line 342

def wrap_around(*others)
  wrap_class.new(self, others)
end