Module: ROM::Plugins::Relation::SQL::DefaultViews Private

Defined in:
lib/rom/plugins/relation/sql/default_views.rb

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Class Method Summary collapse

Class Method Details

.apply(target) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



14
15
16
# File 'lib/rom/plugins/relation/sql/default_views.rb', line 14

def self.apply(target, **)
  define_default_views!(target, registry.schemas.canonical(target))
end

.define_default_views!(target, schema) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rom/plugins/relation/sql/default_views.rb', line 19

def self.define_default_views!(target, schema)
  if schema.primary_key.size > 1
    # @!method by_pk(val1, val2)
    #   Return a relation restricted by its composite primary key
    #
    #   @param [Array] args A list with composite pk values
    #
    #   @return [SQL::Relation]
    #
    #   @api public
    target.class_eval <<-RUBY, __FILE__, __LINE__ + 1
      undef :by_pk if method_defined?(:by_pk)

      def by_pk(#{schema.primary_key.map(&:name).join(", ")})
        where(#{schema.primary_key.map { |attr| "schema.canonical[:#{attr.name}] => #{attr.name}" }.join(", ")})
      end
    RUBY
  else
    # @!method by_pk(pk)
    #   Return a relation restricted by its primary key
    #
    #   @param [Object] pk The primary key value
    #
    #   @return [SQL::Relation]
    #
    #   @api public
    target.class_eval <<-RUBY, __FILE__, __LINE__ + 1
      undef :by_pk if method_defined?(:by_pk)

      def by_pk(pk)
        if primary_key.nil?
          raise MissingPrimaryKeyError.new(
            "Missing primary key for :\#{schema.name}"
          )
        end
        where(schema.canonical[schema.canonical.primary_key_name].qualified => pk)
      end
    RUBY
  end
end

.primary_key_columns(db, table) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



61
62
63
64
# File 'lib/rom/plugins/relation/sql/default_views.rb', line 61

def self.primary_key_columns(db, table)
  names = db.respond_to?(:primary_key) ? Array(db.primary_key(table)) : [:id]
  names.map { |col| :"#{table}__#{col}" }
end