Class: DBConnection

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

Class Method Summary collapse

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("    INSERT INTO\n      version (name)\n    VALUES\n      ($1);\n  SQL\nend\n", [name])

.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("    SELECT\n      attname\n    FROM\n      pg_attribute\n    WHERE\n      attrelid = '\#{table_name}'::regclass AND\n      attnum > 0 AND\n      NOT attisdropped\n  SQL\n\n  columns.map { |col| col['attname'].to_sym }\nend\n")

.ensure_version_tableObject



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("      CREATE TABLE IF NOT EXISTS version (\n        id SERIAL PRIMARY KEY,\n        name VARCHAR(255) NOT NULL\n      );\n    SQL\n  end\nend\n")

.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("    SELECT\n      *\n    FROM\n      version\n    WHERE\n      name = $1;\n  SQL\n  !!result.first\nend\n", [name])

.instanceObject



58
59
60
61
62
# File 'lib/db_connection.rb', line 58

def self.instance
  self.open if @db.nil?

  @db
end

.migrateObject



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

.openObject



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

.resetObject



12
13
14
15
16
17
18
19
# File 'lib/db_connection.rb', line 12

def self.reset
  commands = [
    "dropdb #{APP_NAME}",
    "createdb #{APP_NAME}",
  ]

  commands.each { |command| `#{command}` }
end