Class: Mdb::Database

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, options = {}) ⇒ Database

Returns a new instance of Database.



11
12
13
14
15
16
17
# File 'lib/mdb/database.rb', line 11

def initialize(file, options={})
  file = file.to_path if file.respond_to?(:to_path)
  raise FileDoesNotExistError, "\"#{file}\" does not exist" unless File.exist?(file)

  @file = file
  @delimiter = options.fetch :delimiter, "|"
end

Instance Attribute Details

#delimiterObject (readonly)

Returns the value of attribute delimiter.



21
22
23
# File 'lib/mdb/database.rb', line 21

def delimiter
  @delimiter
end

#fileObject (readonly)

Returns the value of attribute file.



21
22
23
# File 'lib/mdb/database.rb', line 21

def file
  @file
end

Instance Method Details

#columns(table) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/mdb/database.rb', line 31

def columns(table)
  open_csv(table) do |csv|
    line = csv.readline
    unless line || tables.member?(table.to_s)
      raise TableDoesNotExistError, "#{table.inspect} does not exist in #{file_name.inspect}"
    end

    (line || []).map(&:to_sym)
  end
end

#each_record(table, &block) ⇒ Object Also known as: each

Yields a hash for each record



53
54
55
56
57
58
59
60
61
62
# File 'lib/mdb/database.rb', line 53

def each_record(table, &block)
  columns = nil
  read_each(table) do |line|
    if columns
      yield Hash[columns.zip(line)]
    else
      columns = line.map(&:to_sym)
    end
  end
end

#read_csv(table) ⇒ Object



44
45
46
47
48
# File 'lib/mdb/database.rb', line 44

def read_csv(table)
  csv = execute "mdb-export -D '%F %T' -d \\| #{file_name} #{Shellwords.escape(table)}"
  empty_table!(table) if csv.empty?
  csv
end

#read_records(table) ⇒ Object Also known as: read, []

Returns an array of hashes. Each hash represents a record



68
69
70
71
72
# File 'lib/mdb/database.rb', line 68

def read_records(table)
  hashes = []
  each(table) {|hash| hashes << hash}
  hashes
end

#tablesObject



25
26
27
# File 'lib/mdb/database.rb', line 25

def tables
  @tables ||= execute("mdb-tables -1 #{file_name}").scan(/[^\n]+/)
end