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