Minor cosmetic changes.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / MySQL.pm
1 package SQL::Translator::Producer::MySQL;
2
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.16 2003-04-24 16:14:54 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 #
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.16 $ =~ /(\d+)\.(\d+)/;
28 $DEBUG   = 0 unless defined $DEBUG;
29
30 use Data::Dumper;
31 use SQL::Translator::Utils qw(debug);
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     unless ( $no_comments ) {
61         $create .= sprintf "--\n-- Created by %s\n-- Created on %s\n--\n\n",
62             __PACKAGE__, scalar localtime;
63     }
64
65     for my $table ( keys %{ $data } ) {
66
67
68         debug("PKG: Looking at table '$table'\n");
69         my $table_data = $data->{$table};
70 #warn Dumper($table_data);
71         my @fields = sort { 
72             $table_data->{'fields'}->{$a}->{'order'} 
73             <=>
74             $table_data->{'fields'}->{$b}->{'order'}
75         } keys %{$table_data->{'fields'}};
76
77         #
78         # Header.  Should this look like what mysqldump produces?
79         #
80         $create .= "--\n-- Table: $table\n--\n" unless $no_comments;
81         $create .= qq[DROP TABLE IF EXISTS $table;\n] if $add_drop_table;
82         $create .= "CREATE TABLE $table (";
83
84         #
85         # Fields
86         #
87         for (my $i = 0; $i <= $#fields; $i++) {
88             my $field = $fields[$i];
89             debug("PKG: Looking at field '$field'\n");
90             my $field_data = $table_data->{'fields'}->{$field};
91             my @fdata = ("", $field);
92             $create .= "\n";
93
94             # data type and size
95             my $attr      = uc $field_data->{'data_type'} eq 'SET' 
96                             ? 'list' : 'size';
97             my @values    = @{ $field_data->{ $attr } || [] };
98             my $data_type = $field_data->{'data_type'};
99
100             if ( $data_type eq 'number' ) {
101                 # not an integer
102                 if ( scalar @values > 1 ) {
103                     $data_type = 'double';
104                 }
105                 elsif ( $values[0] >= 12 ) {
106                     $data_type = 'bigint';
107                 }
108                 elsif ( $values[0] <= 1 ) {
109                     $data_type = 'tinyint';
110                 }
111                 else {
112                     $data_type = 'int';
113                 }
114             }
115             elsif ( exists $translate{ $data_type } ) {
116                 $data_type = $translate{ $data_type };
117             }
118
119             push @fdata, sprintf "%s%s",
120                 $data_type,
121                 defined( $values[0] )
122                     ? '(' . join( ', ', @values ) . ')'
123                     : '';
124
125             # MySQL qualifiers
126             for my $qual ( qw[ binary unsigned zerofill ] ) {
127                 push @fdata, $qual 
128                     if $field_data->{ $qual } ||
129                        $field_data->{ uc $qual };
130             }
131
132             # Null?
133             push @fdata, "NOT NULL" unless $field_data->{'null'};
134
135             # Default?  XXX Need better quoting!
136             my $default = $field_data->{'default'};
137             if ( defined $default ) {
138                 if ( uc $default eq 'NULL') {
139                     push @fdata, "DEFAULT NULL";
140                 } else {
141                     push @fdata, "DEFAULT '$default'";
142                 }
143             }
144
145             # auto_increment?
146             push @fdata, "auto_increment" if $field_data->{'is_auto_inc'};
147
148             # primary key?
149             # This is taken care of in the indices, could be duplicated here
150             # push @fdata, "PRIMARY KEY" if $field_data->{'is_primary_key'};
151
152
153             $create .= (join " ", '', @fdata);
154             $create .= "," unless ($i == $#fields);
155                 }
156
157         #
158         # Indices
159         #
160         my @index_creates;
161         my @indices     = @{ $table_data->{'indices'}     || [] };
162         my @constraints = @{ $table_data->{'constraints'} || [] };
163
164         for my $key ( @indices, @constraints ) {
165             my ($name, $type, $fields) = @{ $key }{ qw[ name type fields ] };
166             $name ||= '';
167             my $index_type = 
168                 $type eq 'primary_key' ? 'PRIMARY KEY' :
169                 $type eq 'unique'      ? 'UNIQUE KEY'  :
170                 $type eq 'key'         ? 'KEY'         :
171                                 $type eq 'normal'      ? 'KEY'         : '';
172
173             next unless $index_type;
174             push @index_creates,
175                 "  $index_type $name (" . join( ', ', @$fields ) . ')';
176         }
177
178         if ( @index_creates ) {
179             $create .= join(",\n", '', @index_creates);
180         }
181
182         #
183         # Constraints -- need to handle more than just FK. -ky
184         #
185         my @constraint_defs;
186         for my $constraint ( @constraints ) {
187             my $name       = $constraint->{'name'} || '';
188             my $type       = $constraint->{'type'};
189             my $fields     = $constraint->{'fields'};
190             my $ref_table  = $constraint->{'reference_table'};
191             my $ref_fields = $constraint->{'reference_fields'};
192             my $match_type = $constraint->{'match_type'} || '';
193             my $on_delete  = $constraint->{'on_delete_do'};
194             my $on_update  = $constraint->{'on_update_do'};
195
196             if ( $type eq 'foreign_key' ) {
197                 my $def = join(' ', map { $_ || () } '  FOREIGN KEY', $name );
198                 if ( @$fields ) {
199                     $def .= ' (' . join( ', ', @$fields ) . ')';
200                 }
201                 $def .= " REFERENCES $ref_table";
202
203                 if ( @{ $ref_fields || [] } ) {
204                     $def .= ' (' . join( ', ', @$ref_fields ) . ')';
205                 }
206
207                 if ( $match_type ) {
208                     $def .= ' MATCH ' . 
209                         ( $match_type =~ /full/i ) ? 'FULL' : 'PARTIAL';
210                 }
211
212                 if ( @{ $on_delete || [] } ) {
213                     $def .= ' ON DELETE '.join(' ', @$on_delete);
214                 }
215
216                 if ( @{ $on_update || [] } ) {
217                     $def .= ' ON UPDATE '.join(' ', @$on_update);
218                 }
219
220                 push @constraint_defs, $def;
221             }
222         }
223
224         $create .= join(",\n", '', @constraint_defs) if @constraint_defs;
225
226         #
227         # Footer
228         #
229         $create .= "\n)";
230         while ( 
231             my ( $key, $val ) = each %{ $table_data->{'table_options'} ||= {} }
232         ) {
233             $create .= " $key=$val" 
234         }
235         $create .= ";\n\n";
236     }
237
238     return $create;
239 }
240
241 1;
242 __END__
243
244 =head1 NAME
245
246 SQL::Translator::Producer::MySQL - MySQL-specific producer for SQL::Translator
247
248 =head1 AUTHOR
249
250 darren chamberlain E<lt>darren@cpan.orgE<gt>,
251 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>