low hanging fruit, please read the diff below
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / MySQL.pm
1 package SQL::Translator::Producer::MySQL;
2
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.17 2003-04-25 11:47:25 dlc 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 #
10 # This program is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU General Public License as
12 # published by the Free Software Foundation; version 2.
13 #
14 # This program is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 # General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 # 02111-1307  USA
23 # -------------------------------------------------------------------
24
25 use strict;
26 use vars qw[ $VERSION $DEBUG ];
27 $VERSION = sprintf "%d.%02d", q$Revision: 1.17 $ =~ /(\d+)\.(\d+)/;
28 $DEBUG   = 0 unless defined $DEBUG;
29
30 use Data::Dumper;
31 use SQL::Translator::Utils qw(debug header_comment);
32
33 my %translate  = (
34     #
35     # Oracle types
36     #
37     varchar2   => 'varchar',
38     long       => 'text',
39     CLOB       => 'longtext',
40
41     #
42     # Sybase types
43     #
44     int        => 'integer',
45     money      => 'float',
46     real       => 'double',
47     comment    => 'text',
48     bit        => 'tinyint',
49 );
50
51 sub produce {
52     my ($translator, $data) = @_;
53     local $DEBUG            = $translator->debug;
54     my $no_comments         = $translator->no_comments;
55     my $add_drop_table      = $translator->add_drop_table;
56
57     debug("PKG: Beginning production\n");
58
59     my $create; 
60     $create .= header_comment unless ($no_comments);
61
62     for my $table ( keys %{ $data } ) {
63
64
65         debug("PKG: Looking at table '$table'\n");
66         my $table_data = $data->{$table};
67 #warn Dumper($table_data);
68         my @fields = sort { 
69             $table_data->{'fields'}->{$a}->{'order'} 
70             <=>
71             $table_data->{'fields'}->{$b}->{'order'}
72         } keys %{$table_data->{'fields'}};
73
74         #
75         # Header.  Should this look like what mysqldump produces?
76         #
77         $create .= "--\n-- Table: $table\n--\n" unless $no_comments;
78         $create .= qq[DROP TABLE IF EXISTS $table;\n] if $add_drop_table;
79         $create .= "CREATE TABLE $table (";
80
81         #
82         # Fields
83         #
84         for (my $i = 0; $i <= $#fields; $i++) {
85             my $field = $fields[$i];
86             debug("PKG: Looking at field '$field'\n");
87             my $field_data = $table_data->{'fields'}->{$field};
88             my @fdata = ("", $field);
89             $create .= "\n";
90
91             # data type and size
92             my $attr      = uc $field_data->{'data_type'} eq 'SET' 
93                             ? 'list' : 'size';
94             my @values    = @{ $field_data->{ $attr } || [] };
95             my $data_type = $field_data->{'data_type'};
96
97             if ( $data_type eq 'number' ) {
98                 # not an integer
99                 if ( scalar @values > 1 ) {
100                     $data_type = 'double';
101                 }
102                 elsif ( $values[0] >= 12 ) {
103                     $data_type = 'bigint';
104                 }
105                 elsif ( $values[0] <= 1 ) {
106                     $data_type = 'tinyint';
107                 }
108                 else {
109                     $data_type = 'int';
110                 }
111             }
112             elsif ( exists $translate{ $data_type } ) {
113                 $data_type = $translate{ $data_type };
114             }
115
116             push @fdata, sprintf "%s%s",
117                 $data_type,
118                 defined( $values[0] )
119                     ? '(' . join( ', ', @values ) . ')'
120                     : '';
121
122             # MySQL qualifiers
123             for my $qual ( qw[ binary unsigned zerofill ] ) {
124                 push @fdata, $qual 
125                     if $field_data->{ $qual } ||
126                        $field_data->{ uc $qual };
127             }
128
129             # Null?
130             push @fdata, "NOT NULL" unless $field_data->{'null'};
131
132             # Default?  XXX Need better quoting!
133             my $default = $field_data->{'default'};
134             if ( defined $default ) {
135                 if ( uc $default eq 'NULL') {
136                     push @fdata, "DEFAULT NULL";
137                 } else {
138                     push @fdata, "DEFAULT '$default'";
139                 }
140             }
141
142             # auto_increment?
143             push @fdata, "auto_increment" if $field_data->{'is_auto_inc'};
144
145             # primary key?
146             # This is taken care of in the indices, could be duplicated here
147             # push @fdata, "PRIMARY KEY" if $field_data->{'is_primary_key'};
148
149
150             $create .= (join " ", '', @fdata);
151             $create .= "," unless ($i == $#fields);
152                 }
153
154         #
155         # Indices
156         #
157         my @index_creates;
158         my @indices     = @{ $table_data->{'indices'}     || [] };
159         my @constraints = @{ $table_data->{'constraints'} || [] };
160
161         for my $key ( @indices, @constraints ) {
162             my ($name, $type, $fields) = @{ $key }{ qw[ name type fields ] };
163             $name ||= '';
164             my $index_type = 
165                 $type eq 'primary_key' ? 'PRIMARY KEY' :
166                 $type eq 'unique'      ? 'UNIQUE KEY'  :
167                 $type eq 'key'         ? 'KEY'         :
168                                 $type eq 'normal'      ? 'KEY'         : '';
169
170             next unless $index_type;
171             push @index_creates,
172                 "  $index_type $name (" . join( ', ', @$fields ) . ')';
173         }
174
175         if ( @index_creates ) {
176             $create .= join(",\n", '', @index_creates);
177         }
178
179         #
180         # Constraints -- need to handle more than just FK. -ky
181         #
182         my @constraint_defs;
183         for my $constraint ( @constraints ) {
184             my $name       = $constraint->{'name'} || '';
185             my $type       = $constraint->{'type'};
186             my $fields     = $constraint->{'fields'};
187             my $ref_table  = $constraint->{'reference_table'};
188             my $ref_fields = $constraint->{'reference_fields'};
189             my $match_type = $constraint->{'match_type'} || '';
190             my $on_delete  = $constraint->{'on_delete_do'};
191             my $on_update  = $constraint->{'on_update_do'};
192
193             if ( $type eq 'foreign_key' ) {
194                 my $def = join(' ', map { $_ || () } '  FOREIGN KEY', $name );
195                 if ( @$fields ) {
196                     $def .= ' (' . join( ', ', @$fields ) . ')';
197                 }
198                 $def .= " REFERENCES $ref_table";
199
200                 if ( @{ $ref_fields || [] } ) {
201                     $def .= ' (' . join( ', ', @$ref_fields ) . ')';
202                 }
203
204                 if ( $match_type ) {
205                     $def .= ' MATCH ' . 
206                         ( $match_type =~ /full/i ) ? 'FULL' : 'PARTIAL';
207                 }
208
209                 if ( @{ $on_delete || [] } ) {
210                     $def .= ' ON DELETE '.join(' ', @$on_delete);
211                 }
212
213                 if ( @{ $on_update || [] } ) {
214                     $def .= ' ON UPDATE '.join(' ', @$on_update);
215                 }
216
217                 push @constraint_defs, $def;
218             }
219         }
220
221         $create .= join(",\n", '', @constraint_defs) if @constraint_defs;
222
223         #
224         # Footer
225         #
226         $create .= "\n)";
227         while ( 
228             my ( $key, $val ) = each %{ $table_data->{'table_options'} ||= {} }
229         ) {
230             $create .= " $key=$val" 
231         }
232         $create .= ";\n\n";
233     }
234
235     return $create;
236 }
237
238 1;
239 __END__
240
241 =head1 NAME
242
243 SQL::Translator::Producer::MySQL - MySQL-specific producer for SQL::Translator
244
245 =head1 AUTHOR
246
247 darren chamberlain E<lt>darren@cpan.orgE<gt>,
248 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>