001e8fa4631747be416b407eeffdc02c00bb81ad
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / MySQL.pm
1 package SQL::Translator::Producer::MySQL;
2
3 # -------------------------------------------------------------------
4 # $Id: MySQL.pm,v 1.43 2005-06-08 14:44:07 grommit Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 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::Producer::MySQL - MySQL-specific producer for SQL::Translator
26
27 =head1 SYNOPSIS
28
29 Use via SQL::Translator:
30
31   use SQL::Translator;
32
33   my $t = SQL::Translator->new( parser => '...', producer => 'MySQL', '...' );
34   $t->translate;
35
36 =head1 DESCRIPTION
37
38 This module will produce text output of the schema suitable for MySQL.
39 There are still some issues to be worked out with syntax differences 
40 between MySQL versions 3 and 4 ("SET foreign_key_checks," character sets
41 for fields, etc.).
42
43 =head2 Table Types
44
45 Normally the tables will be created without any explicit table type given and
46 so will use the MySQL default.
47
48 Any tables involved in foreign key constraints automatically get a table type
49 of InnoDB, unless this is overridden by setting the C<mysql_table_type> extra
50 attribute explicitly on the table.
51
52 =head2 Extra attributes.
53
54 The producer recognises the following extra attributes on the Schema objects.
55
56 =over 4
57
58 =item field.list
59
60 Set the list of allowed values for Enum fields.
61
62 =item field.binary field.unsigned field.zerofill
63
64 Set the MySQL field options of the same name.
65
66 =item table.mysql_table_type
67
68 Set the type of the table e.g. 'InnoDB', 'MyISAM'. This will be
69 automatically set for tables involved in foreign key constraints if it is
70 not already set explicitly. See L<"Table Types">.
71
72 =item table.mysql_charset table.mysql_collate
73
74 Set the tables default charater set and collation order.
75
76 =item field.mysql_charset field.mysql_collate
77
78 Set the fields charater set and collation order.
79
80 =back
81
82 =cut
83
84 use strict;
85 use vars qw[ $VERSION $DEBUG ];
86 $VERSION = sprintf "%d.%02d", q$Revision: 1.43 $ =~ /(\d+)\.(\d+)/;
87 $DEBUG   = 0 unless defined $DEBUG;
88
89 use Data::Dumper;
90 use SQL::Translator::Schema::Constants;
91 use SQL::Translator::Utils qw(debug header_comment);
92
93 #
94 # Use only lowercase for the keys (e.g. "long" and not "LONG")
95 #
96 my %translate  = (
97     #
98     # Oracle types
99     #
100     varchar2   => 'varchar',
101     long       => 'text',
102     clob       => 'longtext',
103
104     #
105     # Sybase types
106     #
107     int        => 'integer',
108     money      => 'float',
109     real       => 'double',
110     comment    => 'text',
111     bit        => 'tinyint',
112
113     #
114     # Access types
115     #
116     'long integer' => 'integer',
117     'text'         => 'text',
118     'datetime'     => 'datetime',
119 );
120
121 sub produce {
122     my $translator     = shift;
123     local $DEBUG       = $translator->debug;
124     my $no_comments    = $translator->no_comments;
125     my $add_drop_table = $translator->add_drop_table;
126     my $schema         = $translator->schema;
127     my $show_warnings  = $translator->show_warnings || 0;
128
129     debug("PKG: Beginning production\n");
130
131     my $create; 
132     $create .= header_comment unless ($no_comments);
133     # \todo Don't set if MySQL 3.x is set on command line
134     $create .= "SET foreign_key_checks=0;\n\n";
135
136     #
137     # Work out which tables need to be InnoDB to support foreign key
138     # constraints. We do this first as we need InnoDB at both ends.
139     #
140     foreach ( map { $_->get_constraints } $schema->get_tables ) {
141         foreach my $meth (qw/table reference_table/) {
142             my $table = $schema->get_table($_->$meth) || next;
143             next if $table->extra('mysql_table_type');
144             $table->extra( 'mysql_table_type' => 'InnoDB');
145         }
146     }
147
148     #
149     # Generate sql
150     #
151     for my $table ( $schema->get_tables ) {
152         my $table_name = $table->name;
153         debug("PKG: Looking at table '$table_name'\n");
154
155         #
156         # Header.  Should this look like what mysqldump produces?
157         #
158         $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
159         $create .= qq[DROP TABLE IF EXISTS $table_name;\n] if $add_drop_table;
160         $create .= "CREATE TABLE $table_name (\n";
161
162         #
163         # Fields
164         #
165         my @field_defs;
166         for my $field ( $table->get_fields ) {
167             my $field_name = $field->name;
168             debug("PKG: Looking at field '$field_name'\n");
169             my $field_def = $field_name;
170
171             # data type and size
172             my $data_type = $field->data_type;
173             my @size      = $field->size;
174             my %extra     = $field->extra;
175             my $list      = $extra{'list'} || [];
176             # \todo deal with embedded quotes
177             my $commalist = join( ', ', map { qq['$_'] } @$list );
178             my $charset = $extra{'mysql_charset'};
179             my $collate = $extra{'mysql_collate'};
180
181             #
182             # Oracle "number" type -- figure best MySQL type
183             #
184             if ( lc $data_type eq 'number' ) {
185                 # not an integer
186                 if ( scalar @size > 1 ) {
187                     $data_type = 'double';
188                 }
189                 elsif ( $size[0] && $size[0] >= 12 ) {
190                     $data_type = 'bigint';
191                 }
192                 elsif ( $size[0] && $size[0] <= 1 ) {
193                     $data_type = 'tinyint';
194                 }
195                 else {
196                     $data_type = 'int';
197                 }
198             }
199             #
200             # Convert a large Oracle varchar to "text"
201             #
202             elsif ( $data_type =~ /char/i && $size[0] > 255 ) {
203                 $data_type = 'text';
204                 @size      = ();
205             }
206             elsif ( $data_type =~ /char/i && ! $size[0] ) {
207                 @size = (255);
208             }
209             elsif ( $data_type =~ /boolean/i ) {
210                 $data_type = 'enum';
211                 $commalist = "'0','1'";
212             }
213             elsif ( exists $translate{ lc $data_type } ) {
214                 $data_type = $translate{ lc $data_type };
215             }
216
217             @size = () if $data_type =~ /(text|blob)/i;
218
219             if ( $data_type =~ /(double|float)/ && scalar @size == 1 ) {
220                 push @size, '0';
221             }
222
223             $field_def .= " $data_type";
224
225             if ( lc $data_type eq 'enum' ) {
226                 $field_def .= '(' . $commalist . ')';
227                         } 
228             elsif ( defined $size[0] && $size[0] > 0 ) {
229                 $field_def .= '(' . join( ', ', @size ) . ')';
230             }
231
232             # char sets
233             $field_def .= " CHARACTER SET $charset" if $charset;
234             $field_def .= " COLLATE $collate" if $collate;
235
236             # MySQL qualifiers
237             for my $qual ( qw[ binary unsigned zerofill ] ) {
238                 my $val = $extra{ $qual || uc $qual } or next;
239                 $field_def .= " $qual";
240             }
241
242             # Null?
243             $field_def .= ' NOT NULL' unless $field->is_nullable;
244
245             # Default?  XXX Need better quoting!
246             my $default = $field->default_value;
247             if ( defined $default ) {
248                 if ( uc $default eq 'NULL') {
249                     $field_def .= ' DEFAULT NULL';
250                 } else {
251                     $field_def .= " DEFAULT '$default'";
252                 }
253             }
254
255             # auto_increment?
256             $field_def .= " auto_increment" if $field->is_auto_increment;
257             push @field_defs, $field_def;
258                 }
259
260         #
261         # Indices
262         #
263         my @index_defs;
264         my %indexed_fields;
265         for my $index ( $table->get_indices ) {
266             push @index_defs, join( ' ', 
267                 lc $index->type eq 'normal' ? 'INDEX' : $index->type,
268                 $index->name,
269                 '(' . join( ', ', $index->fields ) . ')'
270             );
271             $indexed_fields{ $_ } = 1 for $index->fields;
272         }
273
274         #
275         # Constraints -- need to handle more than just FK. -ky
276         #
277         my @constraint_defs;
278         my @constraints = $table->get_constraints;
279         for my $c ( @constraints ) {
280             my @fields = $c->fields or next;
281
282             if ( $c->type eq PRIMARY_KEY ) {
283                 push @constraint_defs,
284                     'PRIMARY KEY (' . join(', ', @fields). ')';
285             }
286             elsif ( $c->type eq UNIQUE ) {
287                 push @constraint_defs,
288                     'UNIQUE (' . join(', ', @fields). ')';
289             }
290             elsif ( $c->type eq FOREIGN_KEY ) {
291                 #
292                 # Make sure FK field is indexed or MySQL complains.
293                 #
294                 unless ( $indexed_fields{ $fields[0] } ) {
295                     push @index_defs, "INDEX ($fields[0])";
296                     $indexed_fields{ $fields[0] } = 1;
297                 }
298
299                 my $def = join(' ', 
300                     map { $_ || () } 'FOREIGN KEY', $c->name 
301                 );
302
303                 $def .= ' (' . join( ', ', @fields ) . ')';
304
305                 $def .= ' REFERENCES ' . $c->reference_table;
306
307                 my @rfields = map { $_ || () } $c->reference_fields;
308                 unless ( @rfields ) {
309                     my $rtable_name = $c->reference_table;
310                     if ( my $ref_table = $schema->get_table( $rtable_name ) ) {
311                         push @rfields, $ref_table->primary_key;
312                     }
313                     else {
314                         warn "Can't find reference table '$rtable_name' " .
315                             "in schema\n" if $show_warnings;
316                     }
317                 }
318
319                 if ( @rfields ) {
320                     $def .= ' (' . join( ', ', @rfields ) . ')';
321                 }
322                 else {
323                     warn "FK constraint on " . $table->name . '.' .
324                         join('', @fields) . " has no reference fields\n" 
325                         if $show_warnings;
326                 }
327
328                 if ( $c->match_type ) {
329                     $def .= ' MATCH ' . 
330                         ( $c->match_type =~ /full/i ) ? 'FULL' : 'PARTIAL';
331                 }
332
333                 if ( $c->on_delete ) {
334                     $def .= ' ON DELETE '.join( ' ', $c->on_delete );
335                 }
336
337                 if ( $c->on_update ) {
338                     $def .= ' ON UPDATE '.join( ' ', $c->on_update );
339                 }
340
341                 push @constraint_defs, $def;
342             }
343         }
344
345         $create .= join(",\n", map { "  $_" } 
346             @field_defs, @index_defs, @constraint_defs
347         );
348
349         #
350         # Footer
351         #
352         $create .= "\n)";
353         my $mysql_table_type = $table->extra('mysql_table_type');
354         my $charset          = $table->extra('mysql_charset');
355         my $collate          = $table->extra('mysql_collate');
356         $create .= " Type=$mysql_table_type" if $mysql_table_type;
357         $create .= " DEFAULT CHARACTER SET $charset" if $charset;
358         $create .= " COLLATE $collate" if $collate;
359         $create .= ";\n\n";
360     }
361
362     return $create;
363 }
364
365 1;
366
367 # -------------------------------------------------------------------
368
369 =pod
370
371 =head1 SEE ALSO
372
373 SQL::Translator, http://www.mysql.com/.
374
375 =head1 AUTHORS
376
377 darren chamberlain E<lt>darren@cpan.orgE<gt>,
378 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
379
380 =cut