I need to parse a file to get individual SQL statements and run them from rails controller.
I have the following code:
@sql_file = "#{RAILS_ROOT}/lib/evidence_interface_import.sql"
@sql_stmts_array = File.read(@sql_file).split(";")
@sql_stmts_array.each_with_index do |sql_stmt,s_index|
ActiveRecord::Base.connection.execute(sql_stmt)
end
The split removes the ";" from the end of the SQLs. Is there a way not to remove the ";" and still split using ";".
split() is a powerful string manipulation tool that we have at our disposal, but it can also be destructive. Splitting will remove delimiters from the returned array, which may give us output that differs greatly from what the original string was.
Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.
Use a regex with a lookbehind
split(/(?<=;)/)
Yup, scan
it:
'a; b; c;'.scan(/[^;]*;/)
#=> ["a;", " b;", " c;"]
You could get rid of the excess whitespace by tacking on map(&:strip)
after, but it's probably not needed here.
Note that this is very rudimentary, and something like a string literal in the SQL with a semicolon in it will break this. (E.g. select * from stuff where name = ";";
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With