Forum: Ruby [SUMMARY] Restoring Data From SQL (#199)

33117162fff8a9cf50544a604f60c045?d=identicon&s=25 Daniel X Moore (yahivin)
on 2009-04-14 18:53
(Received via mailing list)
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.
Ae16cb4f6d78e485b04ce1e821592ae5?d=identicon&s=25 Martin DeMello (Guest)
on 2009-04-14 20:44
(Received via mailing list)
On Tue, Apr 14, 2009 at 10:21 PM, Daniel Moore <yahivin@gmail.com>
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/

martin
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.