def toSQLQuery (opts={})
sql=""
sqlVariableNamesA = []
sqlVariableNamesB = []
sqlVariableMatchAB = {}
realToSqlVarname_A={}
id_a_clause=1
p_field='predicate'
s_field='subject'
o_field='object'
main_table = 'triples'
lookup_table = 'resources'
where_triples=[]
where_lookup=[]
clauses.each { |clause|
p,s,o = clause[0..2]
p=expns(p)
s=expns(s)
o=expns(o)
p_bound = false
s_bound = false
o_bound = false
p.gsub!(/^\?/,"")
s.gsub!(/^\?/,"")
o.gsub!(/^\?/, "")
all_vars.keys.each { |varname|
if s.eql? varname
realToSqlVarname_A[varname] = "a#{id_a_clause}.#{s_field}"
s_bound = true
end
if p.eql? varname
realToSqlVarname_A[varname]= "a#{id_a_clause}.#{p_field}"
p_bound= true
end
if o.eql? varname
realToSqlVarname_A[varname]= "a#{id_a_clause}.#{o_field}"
o_bound = true
end
}
sh1_sub = hashcodeIntFromString(s)
sh1_pred = hashcodeIntFromString(p)
sh1_obj = hashcodeIntFromString(o)
if !s_bound
where_triples.push "a#{id_a_clause}.#{s_field} = '#{sh1_sub}'"
end
if !p_bound
where_triples.push "a#{id_a_clause}.#{p_field} = '#{sh1_pred}'"
end
if !o_bound
where_triples.push "a#{id_a_clause}.#{o_field} = '#{sh1_obj}'"
end
id_a_clause += 1
}
sqlVarnames=[]
all_vars.keys.each do |variableNameToMatch|
sqlVariableNamesA = []
cl_idx=1
clauses.each do |clause|
p,s,o = clause[0..2]
p_bound = false
s_bound = false
o_bound = false
if s.eql? variableNameToMatch
sqlVariableNamesA.push("a#{cl_idx}.#{s_field}")
end
if p.eql? variableNameToMatch
sqlVariableNamesA.push("a#{cl_idx}.#{p_field}")
end
if o.eql? variableNameToMatch
sqlVariableNamesA.push("a#{cl_idx}.#{o_field}")
end
cl_idx= cl_idx+1
end
if sqlVariableNamesA.size > 1
sqlVarnames.push(sqlVariableNamesA)
end
end
sqlVarnames.each { |bindings|
j = 0
bindings.each { |part|
if (j+1<bindings.size)
where_triples.push " #{part} = #{bindings[j+1]} "
end
j=j+1
}
}
selectvars=[]
clause_lookup_id=1
realToSqlVarname_A.keys.each { |realkey|
val = realToSqlVarname_A[realkey]
realkey.sub!(/\?/,"")
if self.sels.include?("?"+realkey)
if opts['quotevars']
selectvars.push "b#{clause_lookup_id}.value AS '#{realkey}'"
else
selectvars.push "b#{clause_lookup_id}.value AS #{realkey}"
end
sqlVariableNamesB.push("b#{clause_lookup_id}");
where_lookup.push("b#{clause_lookup_id}.keyhash="+val );
end
if (sqlVariableMatchAB[val] == nil)
tmp=[]
tmp.push "b#{clause_lookup_id}.value}"
sqlVariableMatchAB[val]=tmp
else
sqlVariableMatchAB[val].push "b#{clause_lookup_id}.value}"
end
clause_lookup_id += 1
}
sql = "SELECT DISTINCT "+ selectvars.join(", ")+" "
sql += "FROM "
(id_a_clause-1).times do |i|
sql += " #{main_table} a#{i+1}, "
end
lookup_tmp=[]
sqlVariableNamesB.each do |v|
lookup_tmp.push "#{lookup_table} #{v}"
end
sql += lookup_tmp.join(", ")
sql += "\nWHERE\n\t" + where_lookup.join(" AND ") + " AND "+ where_triples.join(" AND ")
return sql
end