I'm currently writing a query to look in a table some grouped results in order to build an alphabetical pagination index.
The query I have looks something like the following (based on this answer):
criteria = "substr(%s, 1, 1)" % field_name
Posts.select(criteria).group(criteria).order(criteria).count(:id)
Now I would like to improve this query in order to avoid any SQL injection but I couldn't really find a way to sanitise it.
As far as I see there's no way to use LIKE for this particular query - or at least I haven't found it - and use a where
clause.
Now the example is using a Posts
entity, but in production it will be used with many kind of objects and I's like to have a generic system to specify a field name dynamically.
The only idea I had was to get the table column name and validate the field against that list before proceeding, although this may be overkilling in a production scenario.
The environment I have is Ruby 1.9.3, Rails 3.2.17, and a MySQL db.
Update 1
I'll define better the context: in the query above I'm using Post
but what I really have it's an ActiveRecord query where I'm appending the select
and group
criteria.
Something like:
query = Post.where(:condition => something)
# .. do more stuff here
criteria = "substr(%s, 1, 1)" % field_name
query.select(criteria).group(criteria).order(criteria).count(:id)