Sha256: 0f05da3afc3ae0f6fa8d4d34df4527bbb6b29cdbb3b98623cdf4333d0a8b34f5

Contents?: true

Size: 1.64 KB

Versions: 4

Compression:

Stored size: 1.64 KB

Contents

# frozen_string_literal: true

module TableSaw
  module DependencyGraph
    class BuildHasManyQuery
      QUERY = <<~SQL.squish
        select %{primary_key} from %{table} where %{clause} and %{polymorphic}
      SQL

      attr_reader :manifest, :directive, :foreign_key

      def initialize(manifest, directive, foreign_key)
        @manifest = manifest
        @directive = directive
        @foreign_key = foreign_key
      end

      def call
        build_base_query
          .then { |query| append_scope(query) }
          .then { |query| append_limit(query) }
      end

      private

      # rubocop:disable Metrics/AbcSize
      def build_base_query
        format(QUERY, primary_key: TableSaw.schema_cache.primary_keys(foreign_key.from_table),
                      table: foreign_key.from_table,
                      clause: TableSaw::Queries::SerializeSqlInClause.new(foreign_key.from_table,
                                                                          foreign_key.column.primary_key,
                                                                          directive.ids).call,
                      polymorphic: foreign_key.type_condition)
      end
      # rubocop:enable Metrics/AbcSize

      def append_scope(query)
        return query unless has_many&.scope

        [query, has_many.scope].join(' and ')
      end

      def append_limit(query)
        return query unless has_many&.limit

        [query, "limit #{has_many.limit}"].join(' ')
      end

      def has_many
        directive.has_many[foreign_key.from_table] ||
          manifest.has_many.fetch(directive.table_name, {})[foreign_key.from_table]
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
table_saw-3.2.0 lib/table_saw/dependency_graph/build_has_many_query.rb
table_saw-3.1.0 lib/table_saw/dependency_graph/build_has_many_query.rb
table_saw-3.0.0 lib/table_saw/dependency_graph/build_has_many_query.rb
table_saw-2.10.0 lib/table_saw/dependency_graph/build_has_many_query.rb