Search code examples
rubysequel

How to sanitize raw SQL in a Ruby script


I'm trying to write a script that connects with a database using Sequel.

If I have a SQL query like this:

record_values = csv_row.to_h.values.join(', ')

sql_query = "INSERT INTO table (#{ COLUMN_NAMES.join(', ') }) VALUES (#{ record_values })"

and the array record_values is dangerous.

How can I sanitize it?

I tried to sanitize using

ActiveRecord.sanitize_sql_array(sql_query)

but I kept getting the error

NoMethodError: undefined method 'sanitize_sql_array' for ActiveRecord:Module

Solution

  • I don't know Sequel, but did you try standard insert method?

    connection = Sequel.connect('...')
    table_name = connection.from(:table_name)
    # OR
    # table_name = DB.from(:table_name)
    # table_name = DB[:table_name]
    table_name.insert(csv_row.to_h)
    

    It's more reliable I believe, because you avoid difference between COLUMN_NAMES and record_values.