Class: DB

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

Overview

Database managment

Class Method Summary collapse

Class Method Details

.create(config) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/db.rb', line 6

def self.create(config)
  pg = Postgres.new(config, 'postgres')
  pg.execute("CREATE DATABASE #{config.database} OWNER #{config.username};")
  pg.finish
  DB.version(config) # create migrations table
  pg.ok?
end

.databases(config) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/db.rb', line 43

def self.databases(config)
  dbs = []
  pg = Postgres.new(config, 'postgres')
  dbs = pg.execute('SELECT * FROM pg_database ORDER BY datname;') if pg.ok?
  pg.finish
  dbs
end

.drop(config) ⇒ Object



14
15
16
17
18
19
# File 'lib/db.rb', line 14

def self.drop(config)
  pg = Postgres.new(config, 'postgres')
  pg.execute("DROP DATABASE #{config.database};")
  pg.finish
  pg.ok?
end

.forward(config) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/db.rb', line 62

def self.forward(config)
  db_version = DB.version(config)
  return nil if db_version.empty?
  db_version.next!
  Dir[config.upgrade].sort.each do |file|
    next unless config.version(file) == db_version
    pg = Postgres.new(config)
    pg.update(file)
    pg.finish
  end
end

.migrate(config) ⇒ Object



51
52
53
54
55
56
57
58
59
60
# File 'lib/db.rb', line 51

def self.migrate(config)
  db_version = DB.version(config)
  return nil if db_version.empty?
  Dir[config.upgrade].sort.each do |file|
    next unless config.version(file) > db_version
    pg = Postgres.new(config)
    pg.update(file)
    pg.finish
  end
end

.migrations(config) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/db.rb', line 35

def self.migrations(config)
  mig = []
  pg = Postgres.new(config)
  mig = pg.execute('SELECT * FROM migrations ORDER BY updated_on;') if pg.ok?
  pg.finish
  mig
end

.rollback(config) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/db.rb', line 74

def self.rollback(config)
  db_version = DB.version(config)
  return nil if db_version.empty?
  Dir[config.downgrade].sort.each do |file|
    next unless config.version(file) == db_version
    pg = Postgres.new(config)
    pg.update(file)
    pg.execute("DELETE FROM migrations WHERE version='#{db_version}';")
    pg.finish
  end
end

.version(config) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/db.rb', line 21

def self.version(config)
  pg = Postgres.new(config)
  ver = pg.value('SELECT version FROM migrations ORDER BY updated_on DESC LIMIT 1;')
  if ver.empty? && pg.connected?
    ver = config.version0
    pg.execute("CREATE TABLE migrations (
                  version character varying NOT NULL,
                  updated_on timestamp without time zone);")
    pg.execute("INSERT INTO migrations VALUES('#{ver}', now());")
  end
  pg.finish
  ver
end