rorx/redmine_wiki_sql — Issue #2: [SOLVED] Preserving order of the columns
Author: AlekseyFedorchenko
Created: 2011-12-08 17:01:07+00:00
State: open

Hi Rodrigo!

...and thank you for the great Redmine plugin that solved my demand for truly _custom_ reporting.

There was the only issue that frustrated me: columns were selected in a weird order that was totally different to one defined in SQL. While I'm a total novice to Redmine and Ruby -- it is a 3rd day on board -- I tried to debug your code and found a problem: ActiveRecord::Base.connection.select_all returns with a hashed columns instead of plain columns array that might be used in this case. I tweaked your code with ActiveRecord::Base.connection.execute and it looks like follows:

```ruby
Redmine::WikiFormatting::Macros.register do
desc "Run SQL query"
macro :sql do |obj, args|

_sentence = args.join(",")
_sentence = _sentence.gsub("\\(", "(")
_sentence = _sentence.gsub("\\)", ")")

result = ActiveRecord::Base.connection.execute(_sentence)
unless result.nil?
unless result.num_rows() == 0
column_names = []
for columns in result.fetch_fields.each do
column_names += columns.name.to_a
end

_thead = '
'
column_names.each do |column_name|
_thead << '	' + column_name.to_s + ''
end
_thead << '
'

_tbody = ''
result.each_hash do |record|
unless record.nil?
_tbody << '
'
column_names.each do |column_name|
_tbody << '	' + record[column_name].to_s + ''
end
_tbody << '
'
end
end

_table = '

' << _thead << _tbody << '

'

result.free
return _table
else
result.free
return '0 records returned'
end
else
result.free
return 'No result returned'
end
end
end
```

It works for me and hopefully you will accept this patch to your plugin :)