0

I am trying to parse a SQL query string into a hash. Example: field = value AND field2 = value2 becomes { field: 'value', field2: 'value2' }

I have tried Rack::Utils.parse, which works great for URL params, but doesn't for SQL query string.

My initial thoughts are to split by AND, OR etc and then use Rack::Utils.parse recursively.

I was thinking there would be a straightforward way of doing this in Rails, but I haven't found anything yet. Has anyone accomplished this before?

Thanks in advance.

0

1 Answer 1

1
sql_query = 'field = value AND field2 = value2 OR field3 = value3'

def hash_for sql_query
  parts = sql_query.split /(and|or)/i
  parts.map do | p | 
    fv = p.split('=').map &:strip
    { fv[0].to_sym => fv[1] }
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.