- Removed use of $Revision$ SVN keyword to generate VERSION variables; now sub-module...
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / Excel.pm
1 package SQL::Translator::Parser::Excel;
2
3 # -------------------------------------------------------------------
4 # $Id$
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-2009 SQLFairy Authors
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; version 2.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 # 02111-1307  USA
21 # -------------------------------------------------------------------
22
23 =head1 NAME
24
25 SQL::Translator::Parser::Excel - parser for Excel
26
27 =head1 SYNOPSIS
28
29   use SQL::Translator;
30
31   my $translator = SQL::Translator->new;
32   $translator->parser('Excel');
33
34 =head1 DESCRIPTION
35
36 Parses an Excel spreadsheet file using Spreadsheet::ParseExcel.
37
38 =head1 OPTIONS
39
40 =over
41
42 =item * scan_fields
43
44 Indicates that the columns should be scanned to determine data types
45 and field sizes.  True by default.
46
47 =back
48
49 =cut
50
51 use strict;
52 use vars qw($DEBUG @EXPORT_OK);
53 $DEBUG = 0 unless defined $DEBUG;
54
55 use Spreadsheet::ParseExcel;
56 use Exporter;
57 use SQL::Translator::Utils qw(debug normalize_name);
58
59 use base qw(Exporter);
60
61 @EXPORT_OK = qw(parse);
62
63 my %ET_to_ST  = (
64     'Text'    => 'VARCHAR',
65     'Date'    => 'DATETIME',
66     'Numeric' => 'DOUBLE',
67 );
68
69 # -------------------------------------------------------------------
70 # parse($tr, $data)
71 #
72 # Note that $data, in the case of this parser, is unuseful.
73 # Spreadsheet::ParseExcel works on files, not data streams.
74 # -------------------------------------------------------------------
75 sub parse {
76     my ($tr, $data) = @_;
77     my $args        = $tr->parser_args;
78     my $filename    = $tr->filename || return;
79     my $wb          = Spreadsheet::ParseExcel::Workbook->Parse( $filename );
80     my $schema      = $tr->schema;
81     my $table_no    = 0;
82
83     my $wb_count = $wb->{'SheetCount'} || 0;
84     for my $num ( 0 .. $wb_count - 1 ) {
85         $table_no++;
86         my $ws         = $wb->Worksheet( $num );
87         my $table_name = normalize_name( $ws->{'Name'} || "Table$table_no" );
88
89         my @cols = $ws->ColRange;
90         next unless $cols[1] > 0;
91
92         my $table = $schema->add_table( name => $table_name );
93
94         my @field_names = ();
95         for my $col ( $cols[0] .. $cols[1] ) {
96             my $cell      = $ws->Cell(0, $col);
97             my $col_name  = normalize_name( $cell->{'Val'} );
98             my $data_type = ET_to_ST( $cell->{'Type'} );
99             push @field_names, $col_name;
100
101             my $field = $table->add_field(
102                 name              => $col_name,
103                 data_type         => $data_type,
104                 default_value     => '',
105                 size              => 255,
106                 is_nullable       => 1,
107                 is_auto_increment => undef,
108             ) or die $table->error;
109
110             if ( $col == 0 ) {
111                 $table->primary_key( $field->name );
112                 $field->is_primary_key(1);
113             }
114         }
115
116         #
117         # If directed, look at every field's values to guess size and type.
118         #
119         unless ( 
120             defined $args->{'scan_fields'} &&
121             $args->{'scan_fields'} == 0
122         ) {
123             my %field_info = map { $_, {} } @field_names;
124
125             for(
126                 my $iR = $ws->{'MinRow'} == 0 ? 1 : $ws->{'MinRow'};
127                 defined $ws->{'MaxRow'} && $iR <= $ws->{'MaxRow'}; 
128                 $iR++
129             ) {
130                for ( 
131                     my $iC = $ws->{'MinCol'};
132                     defined $ws->{'MaxCol'} && $iC <= $ws->{'MaxCol'}; 
133                     $iC++
134                 ) {
135                     my $field = $field_names[ $iC ];
136                     my $data  = $ws->{'Cells'}[ $iR ][ $iC ]->{'_Value'};
137                     next if !defined $data || $data eq '';
138                     my $size  = [ length $data ];
139                     my $type;
140
141                     if ( $data =~ /^-?\d+$/ ) {
142                         $type = 'integer';
143                     }
144                     elsif ( 
145                         $data =~ /^-?[,\d]+\.[\d+]?$/ 
146                         ||
147                         $data =~ /^-?[,\d]+?\.\d+$/  
148                         ||
149                         $data =~ /^-?\.\d+$/  
150                     ) {
151                         $type = 'float';
152                         my ( $w, $d ) = 
153                             map { s/,//g; length $_ || 1 } 
154                             split( /\./, $data )
155                         ;
156                         $size = [ $w + $d, $d ];
157                     }
158                     else {
159                         $type = 'char';
160                     }
161
162                     for my $i ( 0, 1 ) {
163                         next unless defined $size->[ $i ];
164                         my $fsize = $field_info{ $field }{'size'}[ $i ] || 0;
165                         if ( $size->[ $i ] > $fsize ) {
166                             $field_info{ $field }{'size'}[ $i ] = $size->[ $i ];
167                         }
168                     }
169
170                     $field_info{ $field }{ $type }++;
171                 }
172             }
173
174             for my $field ( keys %field_info ) {
175                 my $size      = $field_info{ $field }{'size'} || [ 1 ];
176                 my $data_type = 
177                     $field_info{ $field }{'char'}    ? 'char'    : 
178                     $field_info{ $field }{'float'}   ? 'float'   :
179                     $field_info{ $field }{'integer'} ? 'integer' : 'char';
180
181                 if ( $data_type eq 'char' && scalar @$size == 2 ) {
182                     $size = [ $size->[0] + $size->[1] ];
183                 }
184
185                 my $field = $table->get_field( $field );
186                 $field->size( $size ) if $size;
187                 $field->data_type( $data_type );
188             }
189         }
190     }
191
192     return 1;
193 }
194
195 # -------------------------------------------------------------------
196 sub ET_to_ST {
197     my $et = shift;
198     $ET_to_ST{$et} || $ET_to_ST{'Text'};
199 }
200
201 1;
202
203 # -------------------------------------------------------------------
204 # Education is an admirable thing,
205 # but it is as well to remember that
206 # nothing that is worth knowing can be taught.
207 # Oscar Wilde
208 # -------------------------------------------------------------------
209
210 =pod
211
212 =head1 AUTHORS
213
214 Mike Mellilo <mmelillo@users.sourceforge.net>,
215 darren chamberlain E<lt>dlc@users.sourceforge.netE<gt>,
216 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
217
218 =head1 SEE ALSO
219
220 Spreadsheet::ParseExcel, SQL::Translator.
221
222 =cut