class SqlMigrations::Script

SqlScript class

Constants

DELEGATED

Public Class Methods

find(database, type) click to toggle source
# File lib/sql_migrations/script.rb, line 40
def self.find(database, type)
  files = []

  Find.find(Dir.pwd) do |path|
    file = File.new(path, database, type)

    raise "Duplicate time for #{type}s: #{files.find { |f| f == file }}, #{file}" if
      file.valid? && files.include?(file)

    files << file if file.valid?
  end

  files.sort_by(&:datetime).map { |file| new(file) }
end
new(file) click to toggle source
# File lib/sql_migrations/script.rb, line 13
def initialize(file)
  @file = file

  DELEGATED.each do |method|
    instance_variable_set("@#{method}", file.send(method))
  end
end

Public Instance Methods

execute(db) click to toggle source
# File lib/sql_migrations/script.rb, line 21
def execute(db)
  @database = db
  return false unless new?
  driver = @database.driver
  begin
    driver.transaction do
      @benchmark = Benchmark.measure do
        statements.each { |query| driver.run(query) }
      end
    end
  rescue
    puts "[-] Error while executing #{@type} #{@name} !"
    puts "    Info: #{self}"
    raise
  else
    true & on_success
  end
end
statements() click to toggle source
# File lib/sql_migrations/script.rb, line 55
def statements
  separator = Config.options[:separator]
  if separator
    statements = @content.split(separator)
    statements.collect!(&:strip)
    statements.reject(&:empty?)
  else
    [content]
  end
end
to_s() click to toggle source
# File lib/sql_migrations/script.rb, line 66
def to_s
  "#{@type.capitalize} `#{@path}` for `#{@file.database}` database"
end

Private Instance Methods

new?() click to toggle source
# File lib/sql_migrations/script.rb, line 72
def new?
  history = @database.history
  last = history.order(Sequel.asc(:time)).where(type: @type).last
  is_new = history.where(time: @datetime, type: @type).count == 0

  puts "[!] #{self} datetime BEFORE last one executed !" if
    is_new && last && last[:time] > @datetime

  is_new
end
on_success() click to toggle source
# File lib/sql_migrations/script.rb, line 83
def on_success
  puts "[+] Successfully executed #{@type}, name: #{@name}"
  puts "    Info: #{self}"
  puts "    Benchmark: #{@benchmark}"

  @database.history.insert(time: @datetime, name: @name,
                           type: @type, executed: DateTime.now)
end