Skip to content

Instantly share code, notes, and snippets.

@ekyfauzi
Forked from rietta/sql_views.rake
Created May 7, 2018 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekyfauzi/20e63f283e7db1abf6582c707fabb527 to your computer and use it in GitHub Desktop.
Save ekyfauzi/20e63f283e7db1abf6582c707fabb527 to your computer and use it in GitHub Desktop.
SQL Views rake task implementing `rake db:views`
namespace :db do
desc "Update and create SQL views"
task :views => :environment do
Dir["#{Rails.root}/db/sql_views/*.sql"].each do |file_name|
STDERR.puts "Applying the SQL view at #{file_name}"
source_file = File.new(file_name, 'r')
if source_file and (sql_content = source_file.read)
ActiveRecord::Base.transaction do
# Each statement ends with a semicolon followed by a newline.
sql_lines = sql_content.split(/;[ \t]*$/)
if sql_lines.respond_to?(:each)
sql_lines.each do |line|
ActiveRecord::Base.connection.execute "#{line};"
end
end
end # transaction
end
end # Dir.each
end # task
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment