How do I pass a variable into a prepared statement in Ruby? - ruby

I have a method in Ruby to query a database and print out some data, and I'm trying to use a prepared statement instead.
Here's the functioning method without the prepared statement:
def print_state_speakers(*states)
puts "STATE SPEAKERS"
state_string = "'#{states.*"', '"}'"
state_speakers = $db.execute("
SELECT name, location
FROM congress_members
WHERE location IN (#{state_string})
ORDER BY location")
state_speakers.each { |rep, location| puts "#{rep} - #{location}" }
end
Here's my attempt at the same method using a prepared statement:
def print_state_speakers(*states)
puts "STATE SPEAKERS"
state_string = "'#{states.*"', '"}'"
begin
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (?)
ORDER BY location"
state_speakers = pst.execute state_string
end
state_speakers.each { |rep, location| puts "#{rep} - #{location}" }
end
Here's where I call the method:
print_state_speakers('NJ', 'NY' , 'ME', 'FL', 'AK')
When I run the file with the 1st method it shows the data, when I use the 2nd, it shows nothing. It doesn't throw an error. I feel like the syntax needs to be different to account for the string being passed in, but I've been searching online and messing around with it for a while and can't get it to work. Any insight as to how to fix the prepared statement would be appreciated.

When you say this:
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (?)
ORDER BY location"
state_speakers = pst.execute state_string
The pst.execute call will escape and quote state_string like any other string. But your state_string isn't really a single string, it is an SQL list represented as a (Ruby) string so you'll end up double quoting everything.
An easy solution is to use string interpolation to add the appropriate number of placeholders and then let SQLite3::Statement deal with all the quoting itself:
placeholders = ([ '?' ] * states.length).join(',')
pst = $db.prepare "SELECT name, location
FROM congress_members
WHERE location IN (#{placeholders})
ORDER BY location"
state_speakers = pst.execute states
This use of string interpolation is perfectly safe because you know exactly what is in placeholders.

Related

PostgreSQL "ERROR: could not determine data type of parameter" Ruby exec_params

I am trying to execute a query that selects recipes that match a search term from user input stored in the query variable. This is the portion of relevant code:
class DatabasePersistence
def initialize(logger)
#db = if Sinatra::Base.production?
PG.connect(ENV['DATABASE_URL'])
else
PG.connect(dbname: "recipes")
end
#logger = logger
end
def search_recipes(query)
p "Query parameter is:"
p query
p query.class
sql = <<~SQL
SELECT * FROM recipes
WHERE labels ILIKE '%$1::text%'
SQL
results = query(sql, query)
# ... more code
end
def query(statement, *params)
#logger.info "#{statement}: #{params}"
#db.exec_params(statement, params)
end
end
The following error is raised on when this line results = query(sql, query) is executed.
PG::IndeterminateDatatype at /search
ERROR: could not determine data type of parameter $1
Another post suggested adding an explicit type cast which is why I added the type cast. I could be doing it incorrectly. I also tried it like the following:
WHERE labels ILIKE '%text($1)%'
WHERE labels ILIKE '%cast($1 as text)%'
WHERE labels ~ '$1::text'
WHERE labels ~ 'cast($1 as text'
In all of the above cases it returned the same error "could not determine the datatype of parameter. I added some #p method calls to make sure the query variable is referencing a real value for debuggin. I have confirmed that this error occurs when the query references a string object with value oats.
What is causing this error to still occur if I am casting the datatype and it is not nil? Am I passing the parameters incorrectly? Am I casting the parameters incorrectly? Is it possible there is a way to pass datatypes as arguments to the #exec_params method? Is there another way to safely pass parameters to be executed by the instance of the PG.connect class?
Simply:
WHERE labels ILIKE $1::text
I assume labels is a plain character type like text, too.

Parse a string with multiple XML-like tags using Ruby

I have a string which looks like the following:
string = " <SET-TOPIC>INITIATE</SET-TOPIC>
<SETPROFILE>
<PROFILE-KEY>predicates_live</PROFILE-KEY>
<PROFILE-VALUE>yes</PROFILE-VALUE>
</SETPROFILE>
<think>
<set><name>first_time_initiate</name>yes</set>
</think>
<SETPROFILE>
<PROFILE-KEY>first_time_initiate</PROFILE-KEY>
<PROFILE-VALUE>YES</PROFILE-VALUE>
</SETPROFILE>"
My objective is to be able to read out each top level that is in caps with the parse. I use a case statement to evaluate what is the top level key, such as <SETPROFILE> but there can be lots of different values, and then run a method that does different things with the contnts of the tag.
What this means is I need to be able to know very easily:
top_level_keys = ['SET-TOPIC', 'SET-PROFILE', 'SET-PROFILE']
when I pass in the key know the full value
parsed[0].value = {:PROFILE-KEY => predicates_live, :PROFILE-VALUE => yes}
parsed[0].key = ['SET-TOPIC']
I currently parse the whole string as follows:
doc = Nokogiri::XML::DocumentFragment.parse(string)
parsed = doc.search('*').each_with_object({}){ |n, h|
h[n.name] = n.text
}
As a result, I only parse and know of the second tag. The values from the first tag do not show up in the parsed variable.
I have control over what the tags are, if that helps.
But I need to be able to parse and know the contents of both tag as a result of the parse because I need to apply a method for each instance of the node.
Note: the string also contains just regular text, both before, in between, and after the XML-like tags.
It depends on what you are going to achieve. The problem is that you are overriding hash keys by new values. The easiest way to collect values is to store them in array:
parsed = doc.search('*').each_with_object({}) do |n, h|
# h[n.name] = n.text :: removed because it overrides values
(h[n.name] ||= []) << n.text
end

Ruby String to access an object attribute

I have a text file (objects.txt) which contains Objects and its attributes.
The content of the file is something like:
Object.attribute = "data"
On a different file, I am Loading the objects.txt file and if I type:
puts object.attribute it prints out data
The issue comes when I am trying to access the object and/or the attribute with a string. What I am doing is:
var = "object" + "." + "access"
puts var
It prints out object.access and not the content of it "data".
I have already tried with instance_variable_get and it works, but I have to modify the object.txt and append an # at the beginning to make it an instance variable, but I cannot do this, because I am not the owner of the object.txt file.
As a workaround I can parse the object.txt file and get the data that I need but I don't want to do this, as I want take advantage of what is already there.
Any suggestions?
Yes, puts is correctly spitting out "object.access" because you are creating that string exactly.
In order to evaluate a string as if it were ruby code, you need to use eval()
eg:
var = "object" + "." + "access"
puts eval(var)
=> "data"
Be aware that doing this is quite dangerous if you are evaluating anything that potentially comes from another user.

ruby 2.2. : passing parameter to SQL request string in config yaml file

given a config file config.yml
# config.yml
folders:
tree:
top: "SELECT * FROM mytable WHERE name = 'alpha'"
bottom: "SELECT * FROM mytable WHERE name = '#{name}'"
when I execute in a ruby script :
# myscript1.rb
#config = YAML::load_file File.join( #rundir, 'config.yml')
....
#db.execute(#config['folders']['tree']['top'])
the db select is correctly executed ..
how should I write my ruby command to run the second request passing 'name' as a parameter ?
# myscript2.rb
#config = YAML::load_file File.join( #rundir, 'config.yml')
....
name = "beta"
#db.execute(#config['folders']['tree']['bottom']) # need parameter ?
thanks for help
For the Ruby DB interfaces I'm familiar with, you can pass arguments to execute that will be SQL escaped and interpolated into the query at points marked by ?. So, first you want to rewrite the query to: SELECT * FROM mytable WHERE name = ?;. Then, you can call #db.execute(#config['folders']['tree']['bottom'], name). Compared to Ruby string interpolation, this also has the advantage of ensuring that any untrusted parameters are properly escaped.

Rails String Interpolation in a string from a database

So here is my problem.
I want to retrieve a string stored in a model and at runtime change a part of it using a variable from the rails application. Here is an example:
I have a Message model, which I use to store several unique messages. So different users have the same message, but I want to be able to show their name in the middle of the message, e.g.,
"Hi #{user.name}, ...."
I tried to store exactly that in the database but it gets escaped before showing in the view or gets interpolated when storing in the database, via the rails console.
Thanks in advance.
I don't see a reason to define custom string helper functions. Ruby offers very nice formatting approaches, e.g.:
"Hello %s" % ['world']
or
"Hello %{subject}" % { subject: 'world' }
Both examples return "Hello world".
If you want
"Hi #{user.name}, ...."
in your database, use single quotes or escape the # with a backslash to keep Ruby from interpolating the #{} stuff right away:
s = 'Hi #{user.name}, ....'
s = "Hi \#{user.name}, ...."
Then, later when you want to do the interpolation you could, if you were daring or trusted yourself, use eval:
s = pull_the_string_from_the_database
msg = eval '"' + s + '"'
Note that you'll have to turn s into a double quoted string in order for the eval to work. This will work but it isn't the nicest approach and leaves you open to all sorts of strange and confusing errors; it should be okay as long as you (or other trusted people) are writing the strings.
I think you'd be better off with a simple micro-templating system, even something as simple as this:
def fill_in(template, data)
template.gsub(/\{\{(\w+)\}\}/) { data[$1.to_sym] }
end
#...
fill_in('Hi {{user_name}}, ....', :user_name => 'Pancakes')
You could use whatever delimiters you wanted of course, I went with {{...}} because I've been using Mustache.js and Handlebars.js lately. This naive implementation has issues (no in-template formatting options, no delimiter escaping, ...) but it might be enough. If your templates get more complicated then maybe String#% or ERB might work better.
one way I can think of doing this is to have templates stored for example:
"hi name"
then have a function in models that just replaces the template tags (name) with the passed arguments.
It can also be User who logged in.
Because this new function will be a part of model, you can use it like just another field of model from anywhere in rails, including the html.erb file.
Hope that helps, let me know if you need more description.
Adding another possible solution using Procs:
#String can be stored in the database
string = "->(user){ 'Hello ' + user.name}"
proc = eval(string)
proc.call(User.find(1)) #=> "Hello Bob"
gsub is very powerful in Ruby.
It takes a hash as a second argument so you can supply it with a whitelist of keys to replace like that:
template = <<~STR
Hello %{user_email}!
You have %{user_voices_count} votes!
Greetings from the system
STR
template.gsub(/%{.*?}/, {
"%{user_email}" => 'schmijos#example.com',
"%{user_voices_count}" => 5,
"%{release_distributable_total}" => 131,
"%{entitlement_value}" => 2,
})
Compared to ERB it's secure. And it doesn't complain about single % and unused or inexistent keys like string interpolation with %(sprintf) does.

Resources