Class: SqlMigrations::Script

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_migrations/script.rb

Overview

SqlScript class

Direct Known Subclasses

Migration, Seed

Constant Summary collapse

DELEGATED =
[:name, :date, :time, :datetime, :type, :content, :path]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Script

Returns a new instance of Script.



13
14
15
16
17
18
19
# 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

Class Method Details

.find(database, type) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/sql_migrations/script.rb', line 39

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

Instance Method Details

#execute(db) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 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} !"
    raise
  else
    true & on_success
  end
end

#statementsObject



54
55
56
57
58
59
60
61
62
63
# File 'lib/sql_migrations/script.rb', line 54

def statements
  separator = Config.options[:separator]
  if separator
    statements = @content.split(separator)
    statements.collect!(&:strip)
    statements.reject(&:empty?)
  else
    [content]
  end
end

#to_sObject



65
66
67
# File 'lib/sql_migrations/script.rb', line 65

def to_s
  "#{@type.capitalize} `#{@path}` for `#{@file.database}` database"
end