Class: DBConnection
- Inherits:
-
Object
- Object
- DBConnection
- Defined in:
- lib/db_connection.rb
Class Method Summary collapse
- .add_to_version(file) ⇒ Object
- .columns(table_name) ⇒ Object
- .ensure_version_table ⇒ Object
- .execute(*args) ⇒ Object
- .has_migrated?(file) ⇒ Boolean
- .instance ⇒ Object
- .migrate ⇒ Object
- .open ⇒ Object
- .parse_migration_file(file) ⇒ Object
- .reset ⇒ Object
Class Method Details
.add_to_version(file) ⇒ Object
48 49 50 51 52 53 54 55 56 |
# File 'lib/db_connection.rb', line 48 def self.add_to_version(file) name = parse_migration_file(file) execute(<<-SQL, [name]) INSERT INTO version (name) VALUES ($1); SQL end |
.columns(table_name) ⇒ Object
83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/db_connection.rb', line 83 def self.columns(table_name) columns = instance.exec(<<-SQL) SELECT attname FROM pg_attribute WHERE attrelid = '#{table_name}'::regclass AND attnum > 0 AND NOT attisdropped SQL columns.map { |col| col['attname'].to_sym } end |
.ensure_version_table ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/db_connection.rb', line 69 def self.ensure_version_table #find a reliable way to query db to see if version table exists. table = nil if table.nil? self.execute(<<-SQL) CREATE TABLE IF NOT EXISTS version ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL ); SQL end end |
.execute(*args) ⇒ Object
64 65 66 67 |
# File 'lib/db_connection.rb', line 64 def self.execute(*args) print_query(*args) instance.exec(*args) end |
.has_migrated?(file) ⇒ Boolean
35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/db_connection.rb', line 35 def self.has_migrated?(file) name = parse_migration_file(file) result = execute(<<-SQL, [name]) SELECT * FROM version WHERE name = $1; SQL !!result.first end |
.instance ⇒ Object
58 59 60 61 62 |
# File 'lib/db_connection.rb', line 58 def self.instance self.open if @db.nil? @db end |
.migrate ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/db_connection.rb', line 21 def self.migrate ensure_version_table to_migrate = MIGRATIONS.reject { |file| has_migrated?(file) } to_migrate.each { |file| add_to_version(file) } to_migrate.map {|file| "psql -d #{APP_NAME} -a -f #{file}"} .each {|command| `#{command}`} end |
.open ⇒ Object
8 9 10 |
# File 'lib/db_connection.rb', line 8 def self.open @db = PG::Connection.new( :dbname => APP_NAME, :port => 5432 ) end |
.parse_migration_file(file) ⇒ Object
29 30 31 32 33 |
# File 'lib/db_connection.rb', line 29 def self.parse_migration_file(file) filename = File.basename(file).split(".").first u_idx = filename.index("_") filename[0..u_idx - 1] end |