Sha256: 23f7a70f1967031729ab9791b10b764ed2d3cf1e52fc94f10b659669f381eb0b

Contents?: true

Size: 1.41 KB

Versions: 6

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

module TableSaw
  module DependencyGraph
    class BelongsToDirectives
      attr_reader :directive

      def initialize(directive)
        @directive = directive
      end

      def call
        associations.map do |from_column, to_table|
          TableSaw::DependencyGraph::AddDirective.new(to_table, ids: ids[from_column], partial: directive.partial?)
        end
      end

      private

      def associations
        TableSaw.information_schema.belongs_to.fetch(directive.table_name, {})
      end

      def ids
        @ids ||= associations.each_key.each_with_object({}) do |column, memo|
          memo[column] = query_result(column).map { |row| row[column] }
        end
      end

      # rubocop:disable Metrics/AbcSize
      def query_result(column)
        return [] unless directive.selectable?

        TableSaw::Connection.exec(
          format(
            'select distinct %{column} from %{table_name} where %{clause} and %{column} is not null',
            primary_key: directive.primary_key, column: column, table_name: directive.table_name,
            clause: TableSaw::Queries::SerializeSqlInClause.new(directive.table_name,
                                                                directive.primary_key,
                                                                directive.ids).call
          )
        )
      end
      # rubocop:enable Metrics/AbcSize
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
table_saw-2.6.0 lib/table_saw/dependency_graph/belongs_to_directives.rb
table_saw-2.5.0 lib/table_saw/dependency_graph/belongs_to_directives.rb
table_saw-2.4.3 lib/table_saw/dependency_graph/belongs_to_directives.rb
table_saw-2.4.2 lib/table_saw/dependency_graph/belongs_to_directives.rb
table_saw-2.4.1 lib/table_saw/dependency_graph/belongs_to_directives.rb
table_saw-2.4.0 lib/table_saw/dependency_graph/belongs_to_directives.rb