class SyntaxTree::Database::AttrQuery

Query for the attributes of a node, optionally also filtering by type.

Attributes

attrs[R]
type[R]

Public Class Methods

new(type, attrs) click to toggle source
# File lib/syntax_tree/database.rb, line 102
def initialize(type, attrs)
  @type = type
  @attrs = attrs
end

Public Instance Methods

each(database, &block) click to toggle source
# File lib/syntax_tree/database.rb, line 107
      def each(database, &block)
        joins = []
        binds = []

        attrs.each do |name, query|
          ids = query.each(database).map { |row| row[0] }
          joins << <<~SQL
            JOIN edges AS #{name}
            ON #{name}.from_id = nodes.id
            AND #{name}.name = ?
            AND #{name}.to_id IN (#{(["?"] * ids.size).join(", ")})
          SQL

          binds.push(name).concat(ids)
        end

        sql = +"SELECT nodes.* FROM nodes, edges #{joins.join(" ")}"

        if type
          sql << " WHERE nodes.type = ?"
          binds << type
        end

        sql << " GROUP BY nodes.id"
        database.execute(sql, binds).each(&block)
      end