Created
February 8, 2018 07:56
-
-
Save bootleq/c40467464a1c28852f30358b609af031 to your computer and use it in GitHub Desktop.
Pry `db-exec` command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if defined?(ActiveRecord::Base) | |
Pry::Commands.create_command 'db-exec' do | |
description 'Run SQL statement with ActiveRecord::Base.connection' | |
banner <<-BANNER | |
Usage: db-exec [ > OUTPUT ] STATEMENT | |
db-exec [ > OUTPUT ] < INPUT | |
db-exec < INPUT > OUTPUT | |
Examples: | |
db-exec SELECT NOW() execute any SQL statement | |
db-exec -- SELECT NOW() -h add -- to avoid option parsing | |
db-exec \#{User.all.to_sql} you can use interpolation | |
db-exec < in.sql execute content read from file | |
db-exec < in.sql > out.txt and write result to another file | |
BANNER | |
def options(opt) | |
opt.on '-t', '--to=', 'Assign result object to specific local variable.' | |
end | |
def process | |
var = opts.to? ? opts[:to] : nil | |
pipe = {} | |
while args.length > 0 && args[0].to_s.presence_in(%w[> <]) | |
raise Pry::CommandError, "Missing pipe argument after '#{args[0]}'" if args[1].blank? | |
pipe[args[0]] = args[1] | |
args.shift | |
args.shift | |
end | |
stmt = if pipe.key?('<') | |
IO.read(pipe['<']) | |
else | |
args.join(' ').strip | |
end | |
result = ActiveRecord::Base.connection.execute(stmt) | |
raise Pry::CommandError, "Execute error #{result.error_message}" if result.error_message.present? | |
# NOTE: require customized ai (awesome_inspect) for table output | |
if pipe.key?('>') | |
IO.write(pipe['>'], result.ai(table: true, plain: true, multibyte: true, max_width: 0)) | |
output.puts "result written to #{pipe['>']}" | |
else | |
output.puts result.ai(table: true) | |
end | |
if var.present? | |
target.local_variable_set(var.to_sym, result) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment