# File lib/squish.rb, line 742
def SquishQuery.ask(query,db)
  tables=[]

  query.full_clauses.each do |clause|
    vars={}
    p,s,o=clause[0..2]
    if p.gsub!(/^\?/,"")
      vars['p']=p
      p=nil
    end
    if s.gsub!(/^\?/,"")
      vars['s']=s
      s=nil
    end
    if o.gsub!(/^\?/,"")
      vars['o']=o
      o=nil
    end

    bindings = ResultSet.new  
    a = db.ask(Statement.new(s,p,o)).statements.each do |s| 
      # puts "Vars are: #{vars.values.join ' ' } "
      # todo: store vars
      vb={}
      vb[vars['s']] = s.subject.to_s   if (vars['s'] != nil)  
      vb[vars['p']] = s.predicate.to_s  if (vars['p'] != nil)  
      vb[vars['o']] = s.object.to_s if (vars['o'] != nil)  
      bindings.push(ResultRow.new(vb))
      # puts "vars.values: #{vars.values}\n" #hmm: bindings.vars=vars.values
    end
    tables.push bindings
  end
 
  htmllog = ""
  current = tables.shift # todo: if no matches, this would be returned.
  begin 
    while (!tables.empty?)  
    # puts "Calling chooseTable with current vars: #{current.vars}"
      nx = chooseTable(tables, current.vars) 
      joinvars = current.vars & nx.vars
      htmllog += "<h2>Matching next constraint: vars: #{joinvars.inspect} </h2>"
      htmllog += "<h3>Current matches:</h3>" + current.html_report
      old=current
      new = current.match nx, joinvars
      current = new
      htmllog += "<h3>New matches:</h3>"+current.html_report
    end
  rescue
    if (!tables.empty?) 
      # puts "query failed - unbound tables"
      tables.each do |t| 
        # puts " todo: #{t} tables still to do: #{t.vars.inspect} "
      end
      current = ResultSet.new
    else 
      # puts "Checked all tables."
    end
    # todo: should we check that tables is now empty?
  end
  current.debug_report += htmllog 
  # todo: how to make sure all constraints met? todo...

  answers=ResultSet.new
  answers.debug_report=current.debug_report
  dup={}
  current.each do |row|
    r=''
    row.values.each_key do |col|
      r += col.to_s + row.values[col]
    end
    if (!dup[r.hash])
      dup[r.hash] =1
      answers.push row
     end
  end
  return answers
end