Fix after typo in merge
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
1 package SQL::Translator::Producer::SQLite;
2
3 # -------------------------------------------------------------------
4 # $Id: SQLite.pm,v 1.15 2006-08-26 11:35:31 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.15 $ =~ /(\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         my @defs = create_table($table, { no_comments => $no_comments,
73                                           add_drop_table => $add_drop_table,});
74         my $create = shift @defs;
75         $create .= ";\n";
76         push @table_defs, $create, map( { "$_;" } @defs), "";
77     }
78
79 #    $create .= "COMMIT;\n";
80
81     return wantarray ? ($create, @table_defs, "COMMIT;\n") : join("\n", ($create, @table_defs, "COMMIT;\n"));
82 }
83
84 # -------------------------------------------------------------------
85 sub mk_name {
86     my ($basename, $type, $scope, $critical) = @_;
87     my $basename_orig = $basename;
88     my $max_name      = $type 
89                         ? $max_id_length - (length($type) + 1) 
90                         : $max_id_length;
91     $basename         = substr( $basename, 0, $max_name ) 
92                         if length( $basename ) > $max_name;
93     $basename         =~ s/\./_/g;
94     my $name          = $type ? "${type}_$basename" : $basename;
95
96     if ( $basename ne $basename_orig and $critical ) {
97         my $show_type = $type ? "+'$type'" : "";
98         warn "Truncating '$basename_orig'$show_type to $max_id_length ",
99             "character limit to make '$name'\n" if $WARN;
100         $truncated{ $basename_orig } = $name;
101     }
102
103     $scope ||= \%global_names;
104     if ( my $prev = $scope->{ $name } ) {
105         my $name_orig = $name;
106         $name        .= sprintf( "%02d", ++$prev );
107         substr($name, $max_id_length - 3) = "00" 
108             if length( $name ) > $max_id_length;
109
110         warn "The name '$name_orig' has been changed to ",
111              "'$name' to make it unique.\n" if $WARN;
112
113         $scope->{ $name_orig }++;
114     }
115
116     $scope->{ $name }++;
117     return $name;
118 }
119
120 sub create_table
121 {
122     my ($table, $options) = @_;
123
124     my $table_name = $table->name;
125     my $no_comments = $options->{no_comments};
126     my $add_drop_table = $options->{add_drop_table};
127
128     debug("PKG: Looking at table '$table_name'\n");
129
130     my ( @index_defs, @constraint_defs, @trigger_defs );
131     my @fields = $table->get_fields or die "No fields in $table_name";
132
133     my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
134     #
135     # Header.
136     #
137     my $create = '';
138     $create .= "--\n-- Table: $table_name\n--\n" unless $no_comments;
139     $create .= qq[DROP TABLE $table_name;\n] if $add_drop_table;
140     $create .= "CREATE ${temp}TABLE $table_name (\n";
141
142     #
143     # Comments
144     #
145     if ( $table->comments and !$no_comments ){
146         $create .= "-- Comments: \n-- ";
147         $create .= join "\n-- ",  $table->comments;
148         $create .= "\n--\n\n";
149     }
150
151     #
152     # How many fields in PK?
153     #
154     my $pk        = $table->primary_key;
155     my @pk_fields = $pk ? $pk->fields : ();
156
157     #
158     # Fields
159     #
160     my ( @field_defs, $pk_set );
161     for my $field ( @fields ) {
162         push @field_defs, create_field($field);
163     }
164
165     if ( 
166          scalar @pk_fields > 1 
167          || 
168          ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs ) 
169          ) {
170         push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
171     }
172
173     #
174     # Indices
175     #
176     my $idx_name_default = 'A';
177     for my $index ( $table->get_indices ) {
178         push @index_defs, create_index($index);
179     }
180
181     #
182     # Constraints
183     #
184     my $c_name_default = 'A';
185     for my $c ( $table->get_constraints ) {
186         next unless $c->type eq UNIQUE; 
187         push @constraint_defs, create_constraint($c);
188     }
189
190     $create .= join(",\n", map { "  $_" } @field_defs ) . "\n)";
191
192     return ($create, @index_defs, @constraint_defs, @trigger_defs );
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);
282
283     my $type   = $index->type eq 'UNIQUE' ? "UNIQUE " : ''; 
284
285     # strip any field size qualifiers as SQLite doesn't like these
286     my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
287     (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
288     warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
289     my $index_def =  
290     "CREATE ${type}INDEX $name ON " . $index_table_name .
291         ' (' . join( ', ', @fields ) . ')';
292
293     return $index_def;
294 }
295
296 sub create_constraint
297 {
298     my ($c, $options) = @_;
299
300     my $name   = $c->name;
301     $name      = mk_name($c->table->name, $name);
302     my @fields = $c->fields;
303     (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
304     warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
305
306     my $c_def =  
307     "CREATE UNIQUE INDEX $name ON " . $index_table_name .
308         ' (' . join( ', ', @fields ) . ')';
309
310     return $c_def;
311 }
312
313 sub alter_table { } # Noop
314
315 sub add_field {
316   my ($field) = @_;
317
318   return sprintf("ALTER TABLE %s ADD COLUMN %s",
319       $field->table->name, create_field($field))
320 }
321
322 sub alter_create_index {
323   my ($index) = @_;
324
325   # This might cause name collisions
326   return create_index($index);
327 }
328
329 sub alter_create_constraint {
330   my ($constraint) = @_;
331
332   return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
333 }
334
335 sub alter_drop_constraint { alter_drop_index(@_) }
336
337 sub alter_drop_index {
338   my ($constraint) = @_;
339
340   return sprintf("DROP INDEX %s ON %s",
341       $constraint->name, $constraint->table->name);
342 }
343
344 sub batch_alter_table {
345   my ($table, $diffs) = @_;
346
347   $DB::single = 1 if $table->name eq 'deleted'; 
348
349   # If we have any of the following
350   #
351   #  rename_field
352   #  alter_field
353   #  drop_field
354   #
355   # we need to do the following <http://www.sqlite.org/faq.html#q11>
356   #
357   # BEGIN TRANSACTION;
358   # CREATE TEMPORARY TABLE t1_backup(a,b);
359   # INSERT INTO t1_backup SELECT a,b FROM t1;
360   # DROP TABLE t1;
361   # CREATE TABLE t1(a,b);
362   # INSERT INTO t1 SELECT a,b FROM t1_backup;
363   # DROP TABLE t1_backup;
364   # COMMIT;
365   #
366   # Fun, eh?
367
368   if ( @{$diffs->{rename_field}} == 0 &&
369        @{$diffs->{alter_field}}  == 0 &&
370        @{$diffs->{drop_field}}   == 0) {
371     return join("\n", map { 
372         my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
373         map { my $sql = $meth->(ref $_ eq 'ARRAY' ? @$_ : $_); $sql ?  ("$sql;") : () } @{ $diffs->{$_} }
374         
375       } grep { @{$diffs->{$_}} } keys %$diffs);
376   }
377
378
379   my @sql;
380   
381   do {
382     local $table->{name} = $table->name . '_temp_alter';
383     # We only want the table - dont care about indexes on tmp table
384     my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
385     push @sql,$table_sql;
386   };
387
388   push @sql, "INSERT INTO @{[$table]}_temp_alter SELECT @{[ join(', ', $table->get_fields)]} FROM @{[$table]}",
389              "DROP TABLE @{[$table]}",
390              create_table($table, { no_comments => 1 }),
391              "INSERT INTO @{[$table]} SELECT @{[ join(', ', $table->get_fields)]} FROM @{[$table]}_temp_alter",
392              "DROP TABLE @{[$table]}_temp_alter";
393
394   return join(";\n", @sql, "");
395 }
396
397 sub drop_table {
398   my ($table) = @_;
399   return "DROP TABLE $table;";
400 }
401
402 1;
403
404 =pod
405
406 =head1 SEE ALSO
407
408 SQL::Translator, http://www.sqlite.org/.
409
410 =head1 AUTHOR
411
412 Ken Y. Clark C<< <kclark@cpan.orgE> >>.
413
414 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.
415
416 =cut