Splitting of MySQL, Postgres and SQLite producers into sub methods
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
1 package SQL::Translator::Producer::SQLite;
2
3 # -------------------------------------------------------------------
4 # $Id: SQLite.pm,v 1.14 2006-07-23 14:03:52 schiffbruechige 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::SQLite - SQLite producer for SQL::Translator
26
27 =head1 SYNOPSIS
28
29   use SQL::Translator;
30
31   my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
32   $t->translate;
33
34 =head1 DESCRIPTION
35
36 This module will produce text output of the schema suitable for SQLite.
37
38 =cut
39
40 use strict;
41 use Data::Dumper;
42 use SQL::Translator::Schema::Constants;
43 use SQL::Translator::Utils qw(debug header_comment);
44
45 use vars qw[ $VERSION $DEBUG $WARN ];
46
47 $VERSION = sprintf "%d.%02d", q$Revision: 1.14 $ =~ /(\d+)\.(\d+)/;
48 $DEBUG = 0 unless defined $DEBUG;
49 $WARN = 0 unless defined $WARN;
50
51 my %used_identifiers = ();
52 my $max_id_length    = 30;
53 my %global_names;
54 my %truncated;
55
56 sub produce {
57     my $translator     = shift;
58     local $DEBUG       = $translator->debug;
59     local $WARN        = $translator->show_warnings;
60     my $no_comments    = $translator->no_comments;
61     my $add_drop_table = $translator->add_drop_table;
62     my $schema         = $translator->schema;
63
64     debug("PKG: Beginning production\n");
65
66     my $create = '';
67     $create .= header_comment unless ($no_comments);
68     $create .= "BEGIN TRANSACTION;\n\n";
69
70     my @table_defs = ();
71     for my $table ( $schema->get_tables ) {
72         push @table_defs, create_table($table, { no_comment => $no_comments,
73                                                  add_drop_table => $add_drop_table,});
74     }
75
76 #    $create .= "COMMIT;\n";
77
78     return wantarray ? ($create, @table_defs, "COMMIT;\n") : join("\n", ($create, @table_defs, "COMMIT;\n"));
79 }
80
81 # -------------------------------------------------------------------
82 sub mk_name {
83     my ($basename, $type, $scope, $critical) = @_;
84     my $basename_orig = $basename;
85     my $max_name      = $type 
86                         ? $max_id_length - (length($type) + 1) 
87                         : $max_id_length;
88     $basename         = substr( $basename, 0, $max_name ) 
89                         if length( $basename ) > $max_name;
90     my $name          = $type ? "${type}_$basename" : $basename;
91
92     if ( $basename ne $basename_orig and $critical ) {
93         my $show_type = $type ? "+'$type'" : "";
94         warn "Truncating '$basename_orig'$show_type to $max_id_length ",
95             "character limit to make '$name'\n" if $WARN;
96         $truncated{ $basename_orig } = $name;
97     }
98
99     $scope ||= \%global_names;
100     if ( my $prev = $scope->{ $name } ) {
101         my $name_orig = $name;
102         $name        .= sprintf( "%02d", ++$prev );
103         substr($name, $max_id_length - 3) = "00" 
104             if length( $name ) > $max_id_length;
105
106         warn "The name '$name_orig' has been changed to ",
107              "'$name' to make it unique.\n" if $WARN;
108
109         $scope->{ $name_orig }++;
110     }
111
112     $scope->{ $name }++;
113     return $name;
114 }
115
116 sub create_table
117 {
118     my ($table, $options) = @_;
119
120     my $table_name = $table->name;
121     my $no_comments = $options->{no_comments};
122     my $add_drop_table = $options->{add_drop_table};
123
124     debug("PKG: Looking at table '$table_name'\n");
125
126     my ( @index_defs, @constraint_defs, @trigger_defs );
127     my @fields = $table->get_fields or die "No fields in $table_name";
128
129     #
130     # Header.
131     #
132     my $create = '';
133     $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
134     $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
135     $create .= "CREATE TABLE $table_name (\n";
136
137     #
138     # Comments
139     #
140     if ( $table->comments and !$no_comments ){
141         $create .= "-- Comments: \n-- ";
142         $create .= join "\n-- ",  $table->comments;
143         $create .= "\n--\n\n";
144     }
145
146     #
147     # How many fields in PK?
148     #
149     my $pk        = $table->primary_key;
150     my @pk_fields = $pk ? $pk->fields : ();
151
152     #
153     # Fields
154     #
155     my ( @field_defs, $pk_set );
156     for my $field ( @fields ) {
157         push @field_defs, create_field($field);
158     }
159
160     if ( 
161          scalar @pk_fields > 1 
162          || 
163          ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs ) 
164          ) {
165         push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
166     }
167
168     #
169     # Indices
170     #
171     my $idx_name_default = 'A';
172     for my $index ( $table->get_indices ) {
173         push @index_defs, create_index($index);
174     }
175
176     #
177     # Constraints
178     #
179     my $c_name_default = 'A';
180     for my $c ( $table->get_constraints ) {
181         next unless $c->type eq UNIQUE; 
182         push @constraint_defs, create_constraint($c);
183     }
184
185     $create .= join(",\n", map { "  $_" } @field_defs ) . "\n);\n";
186
187     $create .= "\n";
188
189     for my $def ( @index_defs, @constraint_defs, @trigger_defs ) {
190         $create .= "$def\n";
191     }
192     return $create;
193 }
194
195 sub create_field
196 {
197     my ($field, $options) = @_;
198
199     my $field_name = $field->name;
200     debug("PKG: Looking at field '$field_name'\n");
201     my $field_comments = $field->comments 
202         ? "-- " . $field->comments . "\n  " 
203         : '';
204
205     my $field_def = $field_comments.$field_name;
206
207     # data type and size
208     my $size      = $field->size;
209     my $data_type = $field->data_type;
210     $data_type    = 'varchar' if lc $data_type eq 'set';
211     $data_type  = 'blob' if lc $data_type eq 'bytea';
212
213     if ( lc $data_type =~ /(text|blob)/i ) {
214         $size = undef;
215     }
216
217 #             if ( $data_type =~ /timestamp/i ) {
218 #                 push @trigger_defs, 
219 #                     "CREATE TRIGGER ts_${table_name} ".
220 #                     "after insert on $table_name\n".
221 #                     "begin\n".
222 #                     "  update $table_name set $field_name=timestamp() ".
223 #                        "where id=new.id;\n".
224 #                     "end;\n"
225 #                 ;
226 #
227 #            }
228
229     #
230     # SQLite is generally typeless, but newer versions will
231     # make a field autoincrement if it is declared as (and
232     # *only* as) INTEGER PRIMARY KEY
233     #
234     my $pk        = $field->table->primary_key;
235     my @pk_fields = $pk ? $pk->fields : ();
236
237     if ( 
238          $field->is_primary_key && 
239          scalar @pk_fields == 1 &&
240          (
241           $data_type =~ /int(eger)?$/i
242           ||
243           ( $data_type =~ /^number?$/i && $size !~ /,/ )
244           )
245          ) {
246         $data_type = 'INTEGER PRIMARY KEY';
247         $size      = undef;
248 #        $pk_set    = 1;
249     }
250
251     $field_def .= sprintf " %s%s", $data_type, 
252     ( !$field->is_auto_increment && $size ) ? "($size)" : '';
253
254     # Null?
255     $field_def .= ' NOT NULL' unless $field->is_nullable;
256
257     # Default?  XXX Need better quoting!
258     my $default = $field->default_value;
259     if ( defined $default ) {
260         if ( uc $default eq 'NULL') {
261             $field_def .= ' DEFAULT NULL';
262         } elsif ( $default eq 'now()' ||
263                   $default eq 'CURRENT_TIMESTAMP' ) {
264             $field_def .= ' DEFAULT CURRENT_TIMESTAMP';
265         } elsif ( $default =~ /val\(/ ) {
266             next;
267         } else {
268             $field_def .= " DEFAULT '$default'";
269         }
270     }
271
272     return $field_def;
273
274 }
275
276 sub create_index
277 {
278     my ($index, $options) = @_;
279
280     my $name   = $index->name;
281     $name      = mk_name($index->table->name, $name); #  || ++$idx_name_default);
282
283     # strip any field size qualifiers as SQLite doesn't like these
284     my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
285     my $index_def =  
286     "CREATE INDEX $name on " . $index->table->name .
287         ' (' . join( ', ', @fields ) . ');';
288
289     return $index_def;
290 }
291
292 sub create_constraint
293 {
294     my ($c, $options) = @_;
295
296     my $name   = $c->name;
297     $name      = mk_name($c->table->name, $name); # || ++$idx_name_default);
298     my @fields = $c->fields;
299
300     my $c_def =  
301     "CREATE UNIQUE INDEX $name on " . $c->table->name .
302         ' (' . join( ', ', @fields ) . ');';
303
304     return $c_def;
305 }
306
307 1;
308
309 =pod
310
311 =head1 SEE ALSO
312
313 SQL::Translator, http://www.sqlite.org/.
314
315 =head1 AUTHOR
316
317 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
318
319 =cut