Topic: escaping quote in Ruby
Hi,
I can't seem to escape a quote in ruby. I am trying to migrate data from salesforce.com to postgres.
This is how my code looks like:
require 'mailer'
module ConnectionUtil
def upsertRecords(objectName,queryResult,conn,salesforceOrgId)
queryResult.each do |resultCSVRecord|
begin
headerList = resultCSVRecord.headers
headerStr = headerList.map { |i| i.to_s }.join(",")
if(!salesforceOrgId.nil?)
headerStr = headerStr + "," + "salesforce_org_id"
end
fieldList = resultCSVRecord.fields
fieldStr = fieldList.map { |i| "'" + i.to_s + "'" }.join(",")
fieldStr = fieldStr.gsub("''","null")
if(!salesforceOrgId.nil?)
fieldStr = fieldStr + ",'" + salesforceOrgId + "'"
end
#conn.escape_string(fieldStr)
#puts fieldStr
insertScriptStr = "insert into " + objectName + "(" + headerStr + ") values (" + fieldStr + ")"
quote(insertScriptStr)
#puts insertScriptStr
#arr = fieldStr.split(",")
#arr_length = arr.length
#puts arr_length
#prep_values = ''
#for i in 1..arr_length
# if i != arr_length
# prep_values = prep_values + "$" + i.to_s + ","
# else
# prep_values = prep_values + "$" + i.to_s
# end
#end
#puts prep_values
#teststr = "insert into " + objectName + "(" + headerStr + ") values (" + prep_values + ")"
#puts teststr
#conn.prepare("insertscriptstr", "insert into " + objectName + "(" + headerStr + ") values (" + prep_values + ")")
#conn.exec_prepared("insertscriptstr", arr)
# Try inserting: If it doesn't insert then try to update
#puts insertScriptStr
insertResult = conn.exec(insertScriptStr)
rescue Exception => e
puts e.message
#logic to update
updateStr = ""
i = 0
headerList.each do |hdr|
#puts resultCSVRecord.field(i)
if(resultCSVRecord.field(i).nil? or resultCSVRecord.field(i)=='')
updateStr = updateStr + " " + hdr + " = NULL "
else
updateStr = updateStr + " " + hdr + " = '" + resultCSVRecord.field(i) + "'"
end
i = i+1
if(headerList.size != i)
updateStr = updateStr + ","
end
end
updateScriptStr = "update " + objectName + " set " + updateStr + " where Id = '" + resultCSVRecord.field(0) + "'"
updateResult = conn.exec(updateScriptStr)
end
end
rescue Exception => e
puts e.message
puts e.backtrace.inspect
end
def quote (str)
str.gsub("/'/","\\\\'")
return str
end
endThe str.gsub("/'/", "\\\\'") doesnt seem to work. I have tried many other regular expressions but none has worked for me.
So If I have a dynamic query insert into tablename (col1,col2,col3) values ('Gaurav's','Nitin',1234) I always get the error
Syntax Error near s:
How Do I Fix this?
Thanks
Last edited by gauravsingh2012 (2012-12-19 06:11:22)