· 8 years ago · Feb 21, 2018, 07:20 PM
1#! /usr/bin/env ruby
2require 'tempfile'
3
4def print_help
5 puts %{
6Runs database migrations
7
8Usage:
9
10 ./script/run_db_migrations
11}
12 exit
13end
14
15def exec_sql(s)
16 tf = Tempfile.open('cohepub_migration')
17 tf.write(s)
18 tf.close
19 out = `mysql -u #{DB_USER} --password="#{DB_PASS}" -h #{DB_HOST} #{DB_NAME} < #{tf.path}`
20 tf.unlink
21 out
22end
23
24SCHEMA_SETUP = %{
25
26 CREATE TABLE IF NOT EXISTS schema_migrations (
27 id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
28 name VARCHAR(255) NOT NULL,
29 direction TINYINT NOT NULL DEFAULT 1,
30 performed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
31 );
32
33}
34
35DB_HOST = "localhost"
36DB_NAME = ARGV.first || "cohepub_dev"
37DB_USER = "root"
38DB_PASS = ""
39
40puts "\nMigrating #{DB_NAME}...\n"
41exec_sql(SCHEMA_SETUP)
42
43out = exec_sql("SELECT name FROM schema_migrations WHERE direction = 1 ORDER BY performed_at DESC LIMIT 1;")
44
45migrations = Dir[File.dirname(__FILE__) + "/../db/migrations/*.sql"].select {|m| !m.include?("migrations/reverse_")}
46
47unless out.empty?
48end
49
50migrations.each do |migration|
51 print ">>>=================== #{File.basename(migration)}"
52 `mysql -u #{DB_USER} --password="#{DB_PASS}" -h #{DB_HOST} #{DB_NAME} < #{migration}`
53 exec_sql("INSERT INTO schema_migrations (name, direction) VALUES (\"#{File.basename(migration)}\",1)")
54end