Class: DB
- Inherits:
-
Object
- Object
- DB
- Defined in:
- lib/db.rb
Overview
Database managment
Class Method Summary collapse
- .create(config) ⇒ Object
- .databases(config) ⇒ Object
- .drop(config) ⇒ Object
- .forward(config) ⇒ Object
- .migrate(config) ⇒ Object
- .migrations(config) ⇒ Object
- .rollback(config) ⇒ Object
- .version(config) ⇒ Object
Class Method Details
.create(config) ⇒ Object
7 8 9 10 11 12 13 |
# File 'lib/db.rb', line 7 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
44 45 46 47 48 49 50 |
# File 'lib/db.rb', line 44 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
15 16 17 18 19 20 |
# File 'lib/db.rb', line 15 def self.drop(config) pg = Postgres.new(config, 'postgres') pg.execute("DROP DATABASE #{config.database};") pg.finish pg.ok? end |
.forward(config) ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/db.rb', line 63 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
52 53 54 55 56 57 58 59 60 61 |
# File 'lib/db.rb', line 52 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
36 37 38 39 40 41 42 |
# File 'lib/db.rb', line 36 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
75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/db.rb', line 75 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
22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/db.rb', line 22 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 |