Sha256: 140cdd6c342548346a6a5e33ba9a6126d3eb602fea4a898ac65fbd864cdccd57

Contents?: true

Size: 1007 Bytes

Versions: 8

Compression:

Stored size: 1007 Bytes

Contents

# frozen_string_literal: true

module TableSaw
  class Associations
    attr_reader :manifest

    def initialize(manifest)
      @manifest = manifest
    end

    def belongs_to
      @belongs_to ||= foreign_keys.each_with_object(Hash.new { |h, k| h[k] = Set.new }) do |fk, memo|
        memo[fk.from_table].add(fk)
      end
    end

    def has_many
      @has_many ||= foreign_keys.each_with_object(Hash.new { |h, k| h[k] = Set.new }) do |fk, memo|
        memo[fk.to_table].add(fk)
      end
    end

    private

    def foreign_keys
      @foreign_keys ||= manifest_foreign_keys + schema_foreign_keys
    end

    def manifest_foreign_keys
      manifest.foreign_keys.map do |fk|
        TableSaw::ForeignKey.new(from_table: fk['from_table'], from_column: fk['from_column'],
                                 to_table: fk['to_table'], to_column: fk['to_column'])
      end
    end

    def schema_foreign_keys
      TableSaw.information_schema.foreign_key_relationships.foreign_keys
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
table_saw-3.2.0 lib/table_saw/associations.rb
table_saw-3.1.0 lib/table_saw/associations.rb
table_saw-3.0.0 lib/table_saw/associations.rb
table_saw-2.10.0 lib/table_saw/associations.rb
table_saw-2.9.0 lib/table_saw/associations.rb
table_saw-2.8.1 lib/table_saw/associations.rb
table_saw-2.8.0 lib/table_saw/associations.rb
table_saw-2.7.0 lib/table_saw/associations.rb