背景
Railsアプリケーションを開発する時に、rakeタスクを使って、データを弄ることはたまりあります。自分のメモとして残します。
汎用性を考えるとクエリファイルでクエリを書いて、rake taskを実行することにした。
実装
- rake task 作成
# Rails 5ではrakeタスクをrailsコマンドで実行できるようになった
bundle exec ./bin/rails g task execute_query file
複数のクエリを実行できるようなrake taskを作る
#!/usr/bin/env ruby
require 'awesome_print'
namespace :execute_query do
task :file, %w[sql_file] => :environment do |_task, args|
sql = File.open(args['sql_file']) { |f| f.read }
# split multiple queries
queries = sql.split(/;$/)
# remove last blank line if exists
queries.pop if queries[-1] =~ /^\s+$/
ap queries
ActiveRecord::Base.transaction do
queries.each do |q|
result = ActiveRecord::Base.connection.execute(q)
result.each { |r| ap r }
# TODO: deal with the query result
end
end
end
end
- テストSQLを用意する
select *
from places
limit 1;
select *
from locations
limit 1;
- 実行してみる
$ bundle exec ./bin/rails execute_query:file['./lib/tasks/test.sql']
[
[0] "select *\nfrom places\nlimit 1",
[1] "\n\nselect *\nfrom locations\nlimit 1"
]
[
[ 0] 3,
[ 1] "六本木ヒルズ",
[ 2] "xxxx",
[ 3] "106-6108",
[ 4] xxx,
[ 5] 9,
[ 6] 1,
[ 7] "",
[ 8] 2017-04-18 03:14:05 UTC,
[ 9] 2018-04-13 01:12:36 UTC,
[10] 5,
[11] "xxxx",
[12] 0,
[13] 0,
[14] nil,
[15] 1,
[16] nil,
[17] 0,
[18] 0,
[19] 0,
[20] 107932,
[21] 0
]
[
[0] 5,
[1] 1,
[2] "xxxx",
[3] 0,
[4] 0,
[5] 2017-04-22 04:06:42 UTC,
[6] 2017-04-22 04:06:42 UTC,
[7] 6,
[8] 7181,
[9] 0
]