Created
December 12, 2008 12:19
-
-
Save yrashk/35097 to your computer and use it in GitHub Desktop.
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
#! /usr/bin/env ruby | |
def print_help | |
puts %{ | |
Generates database migration | |
Usage: | |
./script/generate_db_migration add_some_columns | |
(Please stick to underscore_style) | |
It will generate something like | |
./db/migrations/20081212121212_add_some_columns.sql | |
./db/migrations/reverse_20081212121212_add_some_columns.sql | |
} | |
exit | |
end | |
print_help if ARGV.empty? | |
unless Dir[File.dirname(__FILE__) + "/../db/migrations/*_#{ARGV.first}.sql"].empty? | |
puts "This migration (#{ARGV.first}) already exist" | |
exit | |
end | |
basename = Time.now.strftime("%Y%m%d%H%M%S") + "_" + ARGV.first | |
File.open(File.dirname(__FILE__) + "/../db/migrations/#{basename}.sql","w+") do |f| | |
end | |
File.open(File.dirname(__FILE__) + "/../db/migrations/reverse_#{basename}.sql","w+") do |f| | |
end | |
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
#! /usr/bin/env ruby | |
require 'tempfile' | |
def print_help | |
puts %{ | |
Runs database migrations | |
Usage: | |
./script/run_db_migrations | |
} | |
exit | |
end | |
def exec_sql(s) | |
tf = Tempfile.open('cohepub_migration') | |
tf.write(s) | |
tf.close | |
out = `mysql -u #{DB_USER} --password="#{DB_PASS}" -h #{DB_HOST} #{DB_NAME} < #{tf.path}` | |
tf.unlink | |
out | |
end | |
SCHEMA_SETUP = %{ | |
CREATE TABLE IF NOT EXISTS schema_migrations ( | |
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, | |
name VARCHAR(255) NOT NULL, | |
direction TINYINT NOT NULL DEFAULT 1, | |
performed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP | |
); | |
} | |
DB_HOST = "localhost" | |
DB_NAME = ARGV.first || "cohepub_dev" | |
DB_USER = "root" | |
DB_PASS = "" | |
puts "\nMigrating #{DB_NAME}...\n" | |
exec_sql(SCHEMA_SETUP) | |
out = exec_sql("SELECT name FROM schema_migrations WHERE direction = 1 ORDER BY performed_at DESC LIMIT 1;") | |
migrations = Dir[File.dirname(__FILE__) + "/../db/migrations/*.sql"].select {|m| !m.include?("migrations/reverse_")} | |
unless out.empty? | |
end | |
migrations.each do |migration| | |
print ">>>=================== #{File.basename(migration)}" | |
`mysql -u #{DB_USER} --password="#{DB_PASS}" -h #{DB_HOST} #{DB_NAME} < #{migration}` | |
exec_sql("INSERT INTO schema_migrations (name, direction) VALUES (\"#{File.basename(migration)}\",1)") | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment