File: table_metadata.rb

package info (click to toggle)
rails 2%3A7.2.2.1%2Bdfsg-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 43,352 kB
  • sloc: ruby: 349,799; javascript: 30,703; yacc: 46; sql: 43; sh: 29; makefile: 27
file content (85 lines) | stat: -rw-r--r-- 2,268 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# frozen_string_literal: true

module ActiveRecord
  class TableMetadata # :nodoc:
    delegate :join_primary_key, :join_primary_type, :join_foreign_key, :join_foreign_type, to: :reflection

    def initialize(klass, arel_table, reflection = nil)
      @klass = klass
      @arel_table = arel_table
      @reflection = reflection
    end

    def primary_key
      klass&.primary_key
    end

    def type(column_name)
      arel_table.type_for_attribute(column_name)
    end

    def has_column?(column_name)
      klass&.columns_hash&.key?(column_name)
    end

    def associated_with?(table_name)
      klass&._reflect_on_association(table_name)
    end

    def associated_table(table_name)
      reflection = klass._reflect_on_association(table_name) || klass._reflect_on_association(table_name.singularize)

      if !reflection && table_name == arel_table.name
        return self
      end

      if reflection
        association_klass = reflection.klass unless reflection.polymorphic?
      elsif block_given?
        association_klass = yield table_name
      end

      if association_klass
        arel_table = association_klass.arel_table
        arel_table = arel_table.alias(table_name) if arel_table.name != table_name
        TableMetadata.new(association_klass, arel_table, reflection)
      else
        type_caster = TypeCaster::Connection.new(klass, table_name)
        arel_table = Arel::Table.new(table_name, type_caster: type_caster)
        TableMetadata.new(nil, arel_table, reflection)
      end
    end

    def polymorphic_association?
      reflection&.polymorphic?
    end

    def polymorphic_name_association
      reflection&.polymorphic_name
    end

    def through_association?
      reflection&.through_reflection?
    end

    def reflect_on_aggregation(aggregation_name)
      klass&.reflect_on_aggregation(aggregation_name)
    end
    alias :aggregated_with? :reflect_on_aggregation

    def predicate_builder
      if klass
        predicate_builder = klass.predicate_builder.dup
        predicate_builder.instance_variable_set(:@table, self)
        predicate_builder
      else
        PredicateBuilder.new(self)
      end
    end

    attr_reader :arel_table

    private
      attr_reader :klass, :reflection
  end
end