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



50
51
52
53
54
55
56
57
58
# File 'lib/db_connection.rb', line 50

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



85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/db_connection.rb', line 85

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



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/db_connection.rb', line 71

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



66
67
68
69
# File 'lib/db_connection.rb', line 66

def self.execute(*args)
  print_query(*args)
  instance.exec(*args)
end

.has_migrated?(file) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/db_connection.rb', line 37

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



60
61
62
63
64
# File 'lib/db_connection.rb', line 60

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

  @db
end

.migrateObject



23
24
25
26
27
28
29
# File 'lib/db_connection.rb', line 23

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



10
11
12
# File 'lib/db_connection.rb', line 10

def self.open
  @db = PG::Connection.new( :dbname => APP_NAME, :port => 5432 )
end

.parse_migration_file(file) ⇒ Object



31
32
33
34
35
# File 'lib/db_connection.rb', line 31

def self.parse_migration_file(file)
  filename = File.basename(file).split(".").first
  u_idx = filename.index("_")
  filename[0..u_idx - 1]
end

.resetObject



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

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

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