Guest User

Untitled

a guest
Feb 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #! /usr/bin/env ruby
  2. require 'tempfile'
  3.  
  4. def print_help
  5. puts %{
  6. Runs database migrations
  7.  
  8. Usage:
  9.  
  10. ./script/run_db_migrations
  11. }
  12. exit
  13. end
  14.  
  15. def 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
  22. end
  23.  
  24. SCHEMA_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.  
  35. DB_HOST = "localhost"
  36. DB_NAME = ARGV.first || "cohepub_dev"
  37. DB_USER = "root"
  38. DB_PASS = ""
  39.  
  40. puts "\nMigrating #{DB_NAME}...\n"
  41. exec_sql(SCHEMA_SETUP)
  42.  
  43. out = exec_sql("SELECT name FROM schema_migrations WHERE direction = 1 ORDER BY performed_at DESC LIMIT 1;")
  44.  
  45. migrations = Dir[File.dirname(__FILE__) + "/../db/migrations/*.sql"].select {|m| !m.include?("migrations/reverse_")}
  46.  
  47. unless out.empty?
  48. end
  49.  
  50. migrations.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)")
  54. end
Add Comment
Please, Sign In to add comment