| 1 | package DBIx::dbMan::Extension::InputCSV; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use base 'DBIx::dbMan::Extension'; | ||
| 5 | use Text::CSV_XS; | ||
| 6 | use FileHandle; | ||
| 7 | |||
| 8 | our $VERSION = '0.06'; | ||
| 9 | |||
| 10 | 1; | ||
| 11 | |||
| 12 | sub IDENTIFICATION { return "000001-000041-000006"; } | ||
| 13 | |||
| 14 | sub preference { return 0; } | ||
| 15 | |||
| 16 | sub known_actions { return [ qw/CSV_IN/ ]; } | ||
| 17 | |||
| 18 | sub handle_action { | ||
| 19 | my ($obj,%action) = @_; | ||
| 20 | |||
| 21 | if ($action{action} eq 'CSV_IN') { | ||
| 22 | $action{action} = 'NONE'; | ||
| 23 | my $csv = new Text::CSV_XS { quote => $action{opt_quote}, | ||
| 24 | eol => $action{opt_eol}, binary => 1, | ||
| 25 | sep_char => $action{opt_separator}, | ||
| 26 | escape_char => $action{opt_escape}, | ||
| 27 | allow_loose_escapes => $action{opt_allow_loose_escapes}, | ||
| 28 | allow_loose_quotes => $action{opt_allow_loose_quotes} }; | ||
| 29 | |||
| 30 | if ( ! defined $csv ) { | ||
| 31 | $obj->{ -interface }->error( 'Cannot initialize parser for CSV files.' ); | ||
| 32 | return %action; | ||
| 33 | } | ||
| 34 | |||
| 35 | my $file = new FileHandle "<$action{file}"; | ||
| 36 | if ( $obj->{ -interface }->is_utf8 ) { | ||
| 37 | binmode $file, ':utf8'; | ||
| 38 | } | ||
| 39 | unless (defined $file) { | ||
| 40 | $obj->{-interface}->error("Can't load input CSV file $action{file}."); | ||
| 41 | return %action; | ||
| 42 | } | ||
| 43 | local $/ = $action{opt_eol}; | ||
| 44 | my $now_head = 1; | ||
| 45 | while (<$file>) { | ||
| 46 | chomp; | ||
| 47 | if ($csv->parse($_)) { | ||
| 48 | my @f = $csv->fields(); | ||
| 49 | if ($now_head and $action{opt_headings} == 1) { | ||
| 50 | $now_head = 0; next; | ||
| 51 | } | ||
| 52 | $now_head = 0; | ||
| 53 | my $newaction = { action => 'SQL', sql => $action{sql}, type => 'do', placeholders => \@f }; | ||
| 54 | $obj->{-interface}->add_to_actionlist($newaction); | ||
| 55 | } | ||
| 56 | } | ||
| 57 | $file->close(); | ||
| 58 | } | ||
| 59 | |||
| 60 | $action{processed} = 1; | ||
| 61 | return %action; | ||
| 62 | } |