Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sanitize raw SQL in a Ruby script

Tags:

ruby

sequel

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
like image 736
Henry Yang Avatar asked Dec 15 '25 17:12

Henry Yang


1 Answers

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.

like image 80
Pavel Mikhailyuk Avatar answered Dec 17 '25 09:12

Pavel Mikhailyuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!