Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: e572310076
Fetching contributors…

Cannot retrieve contributors at this time

file 191 lines (169 sloc) 7.256 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
namespace :sq do
  task :SEQUEL_PLUS_APP_ROOT do
    if defined? PADRINO_ROOT
      SEQUEL_PLUS_APP_ROOT = PADRINO_ROOT
    else
      SEQUEL_PLUS_APP_ROOT = File.dirname File.expand_path Rake.application.rakefile
    end
    Rake::Task["environment"].invoke if Rake::Task.task_defined?("environment")
  end
  
  task :load_config => :SEQUEL_PLUS_APP_ROOT do
    raise "no DB has been defined.\n Assign DB in your Rakefile or declare an :environment task and connect to your database." unless defined? DB
    ::Sequel.extension :migration
    ::Sequel.extension :schema_dumper
    ::Sequel.extension :pretty_table
  end

  desc "Displays a list of tables in the database"
  task :tables => :load_config do
    puts "No tables in this database" if DB.tables.empty?
    DB.tables.each_with_index do |table_name, i|
      puts "#{'%3d' % (i+1)}: #{table_name}"
    end
  end
  task :list_tables => :tables
  
  desc "Displays content of table or lists all tables"
  task :show, [:table] => :load_config do |t, args|
    args.table ? DB[args.table.to_sym].print : Rake::Task["sq:tables"].invoke
  end
  
  desc "Displays simple list of fields of table in sorted order"
  task :fields, [:table] => :load_config do |t, args|
    raise "no table name given" unless args[:table]
    
    puts '==[' << args.table << ']' << '=' * (80 - args.table.size - 4)
    DB.schema(args.table.to_sym).sort{|a, b| a[0].to_s <=> b[0].to_s}.each{|col| puts col[0]}
    puts '=' * 80
  end

  desc "Displays schema of table"
  task :desc, [:table] => :load_config do |t, args|
    unless args[:table]
      Rake::Task["sq:tables"].invoke
    else
      puts '==[' << args.table << ']' << '=' * (80 - args.table.size - 4)
      DB.schema(args.table.to_sym).each_with_index do |col, i|
        name, info = col
        values = [
          "%3s:" % (i + 1),
          (" %-12s:" % "#{info[:db_type]}#{('(' + info[:max_chars].to_s + ')') if info[:max_chars]}"),
          ("%15s:" % info[:type]),
          "%-25s: " % name,
          (' not null ' unless info[:allow_null]),
          (' pk ' if info[:primary_key]),
          (" default: %s" % info[:default] if info[:default]),
          ]
        puts values.join
      end
      puts '-' * 80
      indexes = DB.indexes(args.table.to_sym)
      if indexes.size == 0
        puts " No indexes defined"
      else
        indexes.each_with_index do |idx, i|
          name, attrs = idx
          puts ' ' << "%-28s" % name << ": unique? " << "%-6s" % (attrs[:unique] ? 'yes' : 'no') << ': ' << attrs[:columns].join(', ')
        end
      end
      puts '=' * 80
    end
  end

  namespace :schema do
    task :ensure_db_dir do
      FileUtils.mkdir_p File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'migrate')
    end
    
    desc "Dumps the schema to db/schema.db"
    task :dump => [:load_config, :ensure_db_dir] do
      schema = DB.dump_schema_migration
      File.open(File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'schema.rb'), "w"){|f| f.write(schema)}
    end
    
    desc "drops the schema, using schema.rb"
    task :drop => [:load_config, :dump] do
      eval(File.read(File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'schema.rb'))).apply(DB, :down)
    end
    
    desc "loads the schema from db/schema.rb"
    task :load => :load_config do
      eval(File.read(File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'schema.rb'))).apply(DB, :up)
      latest_version = ::Sequel::Migrator.latest_migration_version(File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'migrate'))
      ::Sequel::Migrator.set_current_migration_version(DB, latest_version)
      puts "Database schema loaded version #{latest_version}"
    end
    
    desc "Returns current schema version"
    task :version => :load_config do
      puts "Current Schema Version: #{::Sequel::Migrator.get_current_migration_version(DB)}"
    end
  end
  
  desc "Migrate the database through scripts in db/migrate and update db/schema.rb by invoking db:schema:dump."
  task :migrate => :load_config do
    ::Sequel::Migrator.apply(DB, File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'migrate'))
    Rake::Task["sq:schema:dump"].invoke
    Rake::Task["sq:schema:version"].invoke
  end

  namespace :migrate do
    desc "Perform automigration (reset your db data)"
    task :auto => :load_config do
      ::Sequel::Migrator.run DB, "db/migrate", :target => 0
      ::Sequel::Migrator.run DB, "db/migrate"
    end

    desc 'Rollbacks the database one migration and re-migrates up.'
    task :redo => :load_config do
      Rake::Task["sq:rollback"].invoke
      Rake::Task["sq:migrate"].invoke
      Rake::Task["sq:schema:dump"].invoke
    end

    desc "Perform migration up/down to VERSION"
    task :to, [:version] => :load_config do |t, args|
      version = (args[:version] || ENV['VERSION']).to_s.strip
      raise "No VERSION was provided" if version.empty?
      ::Sequel::Migrator.apply(DB, "db/migrate", version.to_i)
    end

    desc 'Runs the "up" for a given migration VERSION.'
    task :up, [:version] => :load_config do |t, args|
      raise "version is required" unless args[:version]

      puts "migrating up to version #{args.version}"
      ::Sequel::Migrator.apply(DB, File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'migrate'), args.version.to_i)
      Rake::Task["sq:schema:dump"].invoke
    end

    desc 'Reverts to previous schema version. Specify the number of steps with STEP=n'
    task :down, [:step] => :load_config do |t, args|
      step = args[:step] ? args.step.to_i : 1
      current_version = ::Sequel::Migrator.get_current_migration_version(DB)
      down_version = current_version - step
      down_version = 0 if down_version < 0

      puts "migrating down to version #{down_version}"
      ::Sequel::Migrator.apply(DB, File.join(SEQUEL_PLUS_APP_ROOT, 'db', 'migrate'), down_version)
      Rake::Task["sq:schema:dump"].invoke
    end
    
    desc "Creates a new migrate script. The verb is optional."
    task :new, [:table, :verb] => :load_config do |t, args|
      unless args[:table]
        puts "need to provide a table name: rake db:migrate:new[new_table]"
      else
        table = args.table
        verb = args.verb || 'create'
        migrate_path = File.join(SEQUEL_PLUS_APP_ROOT,'db', 'migrate')
        begin
          last_file = File.basename(Dir.glob(File.join(migrate_path, '*.rb')).sort.last)
          next_value = last_file.scan(/\d+/).first.to_i + 1
        rescue
          next_value = 1
        end
        filename = '%03d' % next_value << "_" << args.table << '.rb'
        File.open(File.join(migrate_path, filename), 'w') do |file|
          file.puts "class #{verb.capitalize}#{table.capitalize} < Sequel::Migration\n"
          file.puts "\tdef up"
          file.puts "\t\t#{verb}_table :#{table} do"
          file.puts "\t\t\tprimary_key\t:id"
          file.puts "\t\tend"
          file.puts "\tend\n\n"
          file.puts "\tdef down\n"
          file.puts "\t\tdrop_table :#{table}"
          file.puts "\tend"
          file.puts "end"
        end
      end
    end
  end

  desc 'Rolls the schema back to the previous version.'
  task :rollback => :load_config do
    Rake::Task["sq:migrate:down"].invoke
  end

  desc 'Drops all tables and recreates the schema from db/schema.rb'
  task :reset => ['db:schema:drop', 'db:schema:load']
end
Something went wrong with that request. Please try again.