I'm attempting to create a function to create prepared statements for Salesforce queries. The requirement is to escape single quotes; other characters are escaped by Salesforce. When I call
prepared_query('Select Id from Account where Id = :id and Name = :name limit 1', {:id => '00001234', :name => "John 'Smith"}
the expected output is
"Select Id from Account where Id = '00001234' and Name = 'John \\'Smith' limit 1"
I'm attempting to use gsub
for this. My function is
def prepared_query(soql, *args)
if args[0].is_a? Hash
args[0].each do |key, val|
val.gsub!("'", %q(\\\'))
soql.gsub! ":#{key}", "'#{val}'"
end
end
end
The output is
"Select Id from Account where Id = '00001234' and Name = 'John limit 1Smith' limit 1"
What is causing this issue?
When you use gsub with two arguments, the replacement string is interpreted in a special way. What is relevant to your case is that \\'
is replaced with the affix of your match (the counterpart to $'
in ordinary replacement). In order to avoid that you have to use a block for gsub.
A fix to your code may be like this:
def prepared_query(soql, h = {})
h.each do |key, val|
val.gsub!("'", %q(\\\'))
soql.gsub!(":#{key}"){"'#{val}'"}
end
soql
end
Try:
def prepared_query(soql, *args)
if args[0].is_a? Hash
args[0].each do |key, val|
soql.gsub! ":#{key}", "#{val.inspect}"
end
end
soql
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.