# \[SUMMARY\] Restoring Data From SQL (#199)

**URL:** <https://www.ruby-forum.com/t/summary-restoring-data-from-sql-199/165517>\
**Category:** Ruby\
**Created:** [April 14, 2009, 6:53pm UTC](https://www.ruby-forum.com/t/summary-restoring-data-from-sql-199/165517 "2009-04-14T18:53:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![danmcb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/13edae/32.png) [@danmcb](https://www.ruby-forum.com/u/danmcb)\
**Post date:** [April 14, 2009, 6:53pm UTC](https://www.ruby-forum.com/t/summary-restoring-data-from-sql-199/165517/1 "2009-04-14T18:53:39Z")

</div>

No submissions this week (there may have been a glitch causing this  
not to have even been posted to the mailing list, so that might  
explain it…)

Here’s the solution that I ended up using:

```
file_names = Dir['PROD_*']

compositions_found = false

compositions = Hash.new {{}}

file_names.each do |file_name|
  File.read(file_name).each_line do |line|
    compositions_found = false if line =~ /\/\*/
    if compositions_found
      line =~

```

/(([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)/

```
      if $2 && $2 != 'NULL'
        composition = {:id => $1.to_i}
        composition[:product_id] = $2.to_i if $2 && $2 != 'NULL'
        composition[:component_id] = $3.to_i if $3 && $3 != 'NULL'
        composition[:quantity] = $6[1...-1].to_f if $6 && $6 != 

```

‘NULL’  
composition[:line\_num] = $7.to\_i if $7 && $7 != ‘NULL’  
composition[:fixed] = $8.to\_i if $8 && $8 != ‘NULL’  
#puts composition.inspect  
compositions[$1] = compositions[$1].merge(composition)  
end  
#puts line  
else  
compositions\_found = true if line =~ /INSERT INTO  
`compositions`/  
end

```
    next unless compositions_found
  end
end

compositions.sort.each do |id, composition|
  puts composition.inspect
end

```

It reads the comma separated fields using a wonky regex (please let me  
know of a better way!). The output is inspected hashes that I eval in  
another program to load the data back into the DB. It worked  
surprisingly well.

I apologize for the late summary and any mishaps on the mailing of this  
quiz.

---

<div class="post-metadata">

**Author:** ![danmcb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/13edae/32.png) [@danmcb](https://www.ruby-forum.com/u/danmcb)\
**Post date:** [April 14, 2009, 8:44pm UTC](https://www.ruby-forum.com/t/summary-restoring-data-from-sql-199/165517/2 "2009-04-14T20:44:01Z")

</div>

On Tue, Apr 14, 2009 at 10:21 PM, Daniel M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> It reads the comma separated fields using a wonky regex (please let me  
> know of a better way!). The output is inspected hashes that I eval in

There’s a nice, friendly CSV library! [http://fastercsv.rubyforge.org/](http://fastercsv.rubyforge.org/)

martin
