Class: Bio::Ngs::Db

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

Constant Summary collapse

DB_TYPES =
[:ontology, :homology]

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Db

Open a connection to a database using ActiveRecord



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/bio/ngs/db.rb', line 17

def initialize(*args)
  @db_type = args[0]
  if DB_TYPES.include? @db_type
    yaml_file=(args[1]) ? args[1] : Dir.pwd+"/conf/#{@db_type}_db.yml"
    @db = ActiveRecord::Base
    @db.establish_connection YAML.load_file(yaml_file)
    # ONLY FOR DEBUG
    #require 'logger'
    #ActiveRecord::Base.logger = Logger.new 'log/db.log'
    require File.expand_path(File.dirname(__FILE__)+"/db/models/#{@db_type}.rb")
  else
    raise ArgumentError, "Invalid database type: #{@db_type}"
  end
end

Instance Method Details

#create_tables(verbose = false) ⇒ Object

Runs AR migrations and create database tables



33
34
35
36
# File 'lib/bio/ngs/db.rb', line 33

def create_tables(verbose=false)
  ActiveRecord::Migration.verbose = verbose
  ActiveRecord::Migrator.migrate(File.expand_path(File.dirname(__FILE__)+"/db/migrate/#{@db_type}"),nil)
end

#export(table, fileout) ⇒ Object

Export a database table into a tab-separated file



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/bio/ngs/db.rb', line 39

def export(table,fileout)
  klass = @db.const_get(table.singularize.camelize)
  columns = klass.column_names
  out = File.open(fileout,"w") 
  out.write columns.join("\t")+"\n"
  klass.find(:all).each do |output|
    records = output.attributes
    values = []
    columns.each {|c| values << records[c]}
    out.write values.join("\t")+"\n"
  end
end

#insert_many(table, query, values = []) ⇒ Object

Wrapper for DB transaction to execute many INSERT queries into a single transaction This can speed up things particularly for SQLite databases.



54
55
56
57
58
59
60
61
62
# File 'lib/bio/ngs/db.rb', line 54

def insert_many(table,query,values=[])
  klass = @db.const_get(table.to_s.singularize.camelize)
  klass.transaction do 
    values.each do |v|
      sql = @db.send(:sanitize_sql_array,[query]+v)
      @db.connection.execute(sql)
    end
  end
end