Advertisement
Guest User

Untitled

a guest
May 23rd, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. # Online (non-blocking) ActiveRecord migrations using pt-online-schema-change utility from Percona Toolkit.
  2. #
  3. # In your Rails app put it as lib/online_change_table.rb
  4. # Now you can use it in your migration file:
  5. #
  6. # require 'online_change_table'
  7. #
  8. # class AddSomethingToSomethings < ActiveRecord::Migration
  9. # def up
  10. # online_change_table :somethings do |t|
  11. # t.column :a, :string
  12. # t.column :b, :integer, default: 0
  13. # t.change :c, :text, default: '...'
  14. # end
  15. # end
  16. # end
  17. #
  18. # Tested only on ActiveRecord 4.1
  19. # Maybe some time i will release it as a gem :D
  20.  
  21. class ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
  22. def online_change_table(table_name)
  23. recorder = ActiveRecord::Migration::CommandRecorder.new(self)
  24. yield update_table_definition(table_name, recorder)
  25.  
  26. operations = recorder.commands
  27.  
  28. sqls = operations.map do |command, args|
  29. table, arguments = args.shift, args
  30. method = :"#{command}_sql"
  31.  
  32. if respond_to?(method, true)
  33. send(method, table, *arguments)
  34. else
  35. raise "Unknown method called : #{method}(#{arguments.inspect})"
  36. end
  37. end.flatten.join(", ")
  38.  
  39. config = ActiveRecord::Base.configurations[Rails.env]
  40.  
  41. dsn = "D=#{config['database']},t=#{table_name}"
  42. dsn << ",h=#{config['host']}" if config['host']
  43. dsn << ",u=#{config['username']}" if config['username']
  44. dsn << ",p=#{config['password']}" if config['password']
  45. dsn << ",P=#{config['port']}" if config['port']
  46. dsn << ",A=#{config['encoding']}" if config['encoding']
  47.  
  48. ok = system 'pt-online-schema-change', '--alter', sqls, dsn, '--execute'
  49. fail unless ok
  50. end
  51. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement