Class: ODBC::Statement

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.modeObject



29
30
31
# File 'lib/rsql/odbc.rb', line 29

def mode
  @mode ||= 'column'
end

.mode=(value) ⇒ Object



33
34
35
36
37
# File 'lib/rsql/odbc.rb', line 33

def mode=(value)
  value = value.to_s
  Kernel.raise ArgumentError, "mode should be either 'column' or 'csv'" unless %w(column csv).include?(value)
  @mode = value
end

Instance Method Details



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/rsql/odbc.rb', line 40

def print(aliases = nil)
  # get the column names, etc.
  displayed_columns = columns(true)

  # set column indices
  displayed_columns.each_with_index do |c,i|
    c.index = i
  end

  # set column aliases (if provided)
  if aliases
    displayed_columns.collect! do |c|
      c if c.alias = aliases[c.name.to_sym]
    end.compact!
  end

  # fetch the data
  # TODO: handle huge result sets better... maybe paginate or base column width on initial n-record set
  resultset = fetch_all

  return 0 if resultset.nil? || resultset.empty?
  
  case self.class.mode
  when 'column'
    # determine the column widths (might be realy slow with large result sets)
    resultset.each do |r|
      displayed_columns.each do |c|
        if value = r[c.index]
          value = value.to_s
          c.width = value.length if value.length > c.width
        end
      end
    end

    # prepare the horizontal rule for header and footer
    rule = "+-" + displayed_columns.collect { |c| '-' * c.width }.join("-+-") + "-+"
    # output header
    puts rule
    puts "| " + displayed_columns.collect { |c| c.alias.ljust(c.width,' ') }.join(" | ") + " |"
    puts rule

    # output each row
    resultset.each do |r|
      puts "| " + displayed_columns.collect { |c| r[c.index].to_s.ljust(c.width, ' ') }.join(" | ") + " |"
    end

    # output footer
    puts rule
  when 'csv'
    # output header
    puts displayed_columns.collect { |c| c.alias }.to_csv(:force_quotes => true)
    # output each row
    resultset.each do |r|
      puts displayed_columns.collect { |c| r[c.index].to_s }.to_csv(:force_quotes => true)
    end
  end
  
  return resultset.size
end