Class: Radical::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/radical/database.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.connection_stringObject



13
14
15
# File 'lib/radical/database.rb', line 13

def connection_string
  @connection_string || ENV['DATABASE_URL']
end

.migrations_pathObject

Returns the value of attribute migrations_path.



11
12
13
# File 'lib/radical/database.rb', line 11

def migrations_path
  @migrations_path
end

Class Method Details

.applied_migrationsObject



74
75
76
# File 'lib/radical/database.rb', line 74

def applied_migrations
  migrations.select { |f| applied_versions.include?(version(f)) }
end

.applied_versionsObject



67
68
69
70
71
72
# File 'lib/radical/database.rb', line 67

def applied_versions
  sql = 'select * from radical_migrations order by version'
  rows = db.execute sql

  rows.map { |r| r['version'] }
end

.connectionObject



17
18
19
20
21
22
23
# File 'lib/radical/database.rb', line 17

def connection
  conn = SQLite3::Database.new(connection_string)
  conn.results_as_hash = true
  conn.type_translation = true

  @connection ||= conn
end

.dbObject



29
30
31
# File 'lib/radical/database.rb', line 29

def db
  connection
end

.migrate!Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/radical/database.rb', line 43

def migrate!
  db.execute 'create table if not exists radical_migrations ( version integer primary key )'

  pending_migrations.each do |file|
    puts "Executing migration #{file}"

    v = version(file)

    migration(file).migrate!(db: db, version: v)
  end
end

.migration(file) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/radical/database.rb', line 33

def migration(file)
  context = Module.new
  context.class_eval(File.read(file), file)
  const = context.constants.find do |constant|
    context.const_get(constant).ancestors.include?(Radical::Migration)
  end

  context.const_get(const)
end

.migrationsObject



82
83
84
# File 'lib/radical/database.rb', line 82

def migrations
  Dir[File.join(migrations_path || '.', 'migrations', '*.rb')].sort
end

.pending_migrationsObject



78
79
80
# File 'lib/radical/database.rb', line 78

def pending_migrations
  migrations.reject { |f| applied_versions.include?(version(f)) }
end

.prepend_migrations_path(path) ⇒ Object



25
26
27
# File 'lib/radical/database.rb', line 25

def prepend_migrations_path(path)
  self.migrations_path = path
end

.rollback!Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/radical/database.rb', line 55

def rollback!
  db.execute 'create table if not exists radical_migrations ( version integer primary key )'

  file = applied_migrations.last

  puts "Rolling back migration #{file}"

  v = version(file)

  migration(file).rollback!(db: db, version: v)
end

.version(filename) ⇒ Object



86
87
88
# File 'lib/radical/database.rb', line 86

def version(filename)
  filename.split(File::SEPARATOR).last.split('_').first.to_i
end