Last active
February 8, 2017 13:46
-
-
Save p9436/26d9c00a05cbe413441c to your computer and use it in GitHub Desktop.
Generate SQL files from rails migrations
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
| namespace :db do | |
| task migrations2sql: :environment do |task| | |
| SQL_FILES_DIR = Rails.root.join('tmp', 'sql') | |
| FileUtils.rm_rf(SQL_FILES_DIR, secure: true) | |
| Dir.mkdir(SQL_FILES_DIR) unless File.exists?(SQL_FILES_DIR) | |
| TMP_FILE = Tempfile.new('migrations2sql') | |
| module ActiveRecord | |
| module AttributeAssignment | |
| def assign_attributes(new_attributes) | |
| return | |
| end | |
| end | |
| end | |
| ActiveRecord::Base.connection.class.class_eval do | |
| # it should think that indexes are not existed | |
| def index_name_exists?(table_name, index_name, default) | |
| false | |
| end | |
| alias :old_execute :execute | |
| # define our own execute | |
| def execute(sql, name = nil) | |
| # check for some DDL and DML statements | |
| if /^(alter|create|drop|delete|insert|update)/i.match sql | |
| p sql | |
| TMP_FILE.write "#{sql};\n" | |
| else | |
| # pass everything else to the aliased execute | |
| old_execute sql, name | |
| end | |
| end | |
| end | |
| migrations = ActiveRecord::Migrator.migrations(File.join(Rails.root, 'db')) | |
| migrations.each_with_index do |migration, i| | |
| migration.migrate(:up) | |
| begin | |
| version = migration.filename[/([0-9]+_[_a-z0-9]*\.?[_a-z0-9]*)?\.rb\z/, 1] | |
| filename = File.join(SQL_FILES_DIR, "V1_#{i}__#{version}.sql") | |
| TMP_FILE.rewind | |
| content = TMP_FILE.read | |
| file = File.open(filename, "w") | |
| file.write "-- #{migration.filename}\n\n" | |
| file.write content | |
| TMP_FILE.truncate(0) | |
| TMP_FILE.rewind | |
| rescue IOError => e | |
| p e | |
| ensure | |
| file.close unless file.nil? | |
| end | |
| end | |
| TMP_FILE.close | |
| TMP_FILE.unlink | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment