- Removed use of $Revision$ SVN keyword to generate VERSION variables; now sub-module...
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / SQLite.pm
1 package SQL::Translator::Producer::SQLite;
2
3 # -------------------------------------------------------------------
4 # $Id$
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-2009 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[ $DEBUG $WARN ];
46
47 $DEBUG = 0 unless defined $DEBUG;
48 $WARN = 0 unless defined $WARN;
49
50 my %used_identifiers = ();
51 my $max_id_length    = 30;
52 my %global_names;
53 my %truncated;
54
55 sub produce {
56     my $translator     = shift;
57     local $DEBUG       = $translator->debug;
58     local $WARN        = $translator->show_warnings;
59     my $no_comments    = $translator->no_comments;
60     my $add_drop_table = $translator->add_drop_table;
61     my $schema         = $translator->schema;
62     my $producer_args  = $translator->producer_args;
63     my $sqlite_version  = $producer_args->{sqlite_version} || 0;
64
65     debug("PKG: Beginning production\n");
66
67     my @create = ();
68     push @create, header_comment unless ($no_comments);
69     push @create, 'BEGIN TRANSACTION';
70
71     for my $table ( $schema->get_tables ) {
72         push @create, create_table($table, { no_comments => $no_comments,
73                                              sqlite_version => $sqlite_version,
74                                           add_drop_table => $add_drop_table,});
75     }
76
77     for my $view ( $schema->get_views ) {
78       push @create, create_view($view, {
79         add_drop_view => $add_drop_table,
80         no_comments   => $no_comments,
81       });
82     }
83
84     return wantarray ? (@create, "COMMIT") : join(";\n\n", (@create, "COMMIT;\n"));
85 }
86
87 # -------------------------------------------------------------------
88 sub mk_name {
89     my ($basename, $type, $scope, $critical) = @_;
90     my $basename_orig = $basename;
91     my $max_name      = $type 
92                         ? $max_id_length - (length($type) + 1) 
93                         : $max_id_length;
94     $basename         = substr( $basename, 0, $max_name ) 
95                         if length( $basename ) > $max_name;
96     $basename         =~ s/\./_/g;
97     my $name          = $type ? "${type}_$basename" : $basename;
98
99     if ( $basename ne $basename_orig and $critical ) {
100         my $show_type = $type ? "+'$type'" : "";
101         warn "Truncating '$basename_orig'$show_type to $max_id_length ",
102             "character limit to make '$name'\n" if $WARN;
103         $truncated{ $basename_orig } = $name;
104     }
105
106     $scope ||= \%global_names;
107     if ( my $prev = $scope->{ $name } ) {
108         my $name_orig = $name;
109         $name        .= sprintf( "%02d", ++$prev );
110         substr($name, $max_id_length - 3) = "00" 
111             if length( $name ) > $max_id_length;
112
113         warn "The name '$name_orig' has been changed to ",
114              "'$name' to make it unique.\n" if $WARN;
115
116         $scope->{ $name_orig }++;
117     }
118
119     $scope->{ $name }++;
120     return $name;
121 }
122
123 sub create_view {
124     my ($view, $options) = @_;
125     my $add_drop_view = $options->{add_drop_view};
126
127     my $view_name = $view->name;
128     debug("PKG: Looking at view '${view_name}'\n");
129
130     # Header.  Should this look like what mysqldump produces?
131     my $extra = $view->extra;
132     my $create = '';
133     $create .= "--\n-- View: ${view_name}\n--\n" unless $options->{no_comments};
134     $create .= "DROP VIEW IF EXISTS $view_name;\n" if $add_drop_view;
135     $create .= 'CREATE';
136     $create .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
137     $create .= ' VIEW';
138     $create .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
139     $create .= " ${view_name}";
140
141     if( my $sql = $view->sql ){
142       $create .= " AS\n    ${sql}";
143     }
144     return $create;
145 }
146
147
148 sub create_table
149 {
150     my ($table, $options) = @_;
151
152     my $table_name = $table->name;
153     my $no_comments = $options->{no_comments};
154     my $add_drop_table = $options->{add_drop_table};
155     my $sqlite_version = $options->{sqlite_version} || 0;
156
157     debug("PKG: Looking at table '$table_name'\n");
158
159     my ( @index_defs, @constraint_defs, @trigger_defs );
160     my @fields = $table->get_fields or die "No fields in $table_name";
161
162     my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
163     #
164     # Header.
165     #
166     my $exists = ($sqlite_version >= 3.3) ? ' IF EXISTS' : '';
167     my @create;
168     push @create, "--\n-- Table: $table_name\n--\n" unless $no_comments;
169     push @create, qq[DROP TABLE$exists $table_name] if $add_drop_table;
170     my $create_table = "CREATE ${temp}TABLE $table_name (\n";
171
172     #
173     # Comments
174     #
175     if ( $table->comments and !$no_comments ){
176         $create_table .= "-- Comments: \n-- ";
177         $create_table .= join "\n-- ",  $table->comments;
178         $create_table .= "\n--\n\n";
179     }
180
181     #
182     # How many fields in PK?
183     #
184     my $pk        = $table->primary_key;
185     my @pk_fields = $pk ? $pk->fields : ();
186
187     #
188     # Fields
189     #
190     my ( @field_defs, $pk_set );
191     for my $field ( @fields ) {
192         push @field_defs, create_field($field);
193     }
194
195     if ( 
196          scalar @pk_fields > 1 
197          || 
198          ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs ) 
199          ) {
200         push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
201     }
202
203     #
204     # Indices
205     #
206     my $idx_name_default = 'A';
207     for my $index ( $table->get_indices ) {
208         push @index_defs, create_index($index);
209     }
210
211     #
212     # Constraints
213     #
214     my $c_name_default = 'A';
215     for my $c ( $table->get_constraints ) {
216         next unless $c->type eq UNIQUE; 
217         push @constraint_defs, create_constraint($c);
218     }
219
220     $create_table .= join(",\n", map { "  $_" } @field_defs ) . "\n)";
221
222     return (@create, $create_table, @index_defs, @constraint_defs, @trigger_defs );
223 }
224
225 sub create_field
226 {
227     my ($field, $options) = @_;
228
229     my $field_name = $field->name;
230     debug("PKG: Looking at field '$field_name'\n");
231     my $field_comments = $field->comments 
232         ? "-- " . $field->comments . "\n  " 
233         : '';
234
235     my $field_def = $field_comments.$field_name;
236
237     # data type and size
238     my $size      = $field->size;
239     my $data_type = $field->data_type;
240     $data_type    = 'varchar' if lc $data_type eq 'set';
241     $data_type  = 'blob' if lc $data_type eq 'bytea';
242
243     if ( lc $data_type =~ /(text|blob)/i ) {
244         $size = undef;
245     }
246
247 #             if ( $data_type =~ /timestamp/i ) {
248 #                 push @trigger_defs, 
249 #                     "CREATE TRIGGER ts_${table_name} ".
250 #                     "after insert on $table_name\n".
251 #                     "begin\n".
252 #                     "  update $table_name set $field_name=timestamp() ".
253 #                        "where id=new.id;\n".
254 #                     "end;\n"
255 #                 ;
256 #
257 #            }
258
259     #
260     # SQLite is generally typeless, but newer versions will
261     # make a field autoincrement if it is declared as (and
262     # *only* as) INTEGER PRIMARY KEY
263     #
264     my $pk        = $field->table->primary_key;
265     my @pk_fields = $pk ? $pk->fields : ();
266
267     if ( 
268          $field->is_primary_key && 
269          scalar @pk_fields == 1 &&
270          (
271           $data_type =~ /int(eger)?$/i
272           ||
273           ( $data_type =~ /^number?$/i && $size !~ /,/ )
274           )
275          ) {
276         $data_type = 'INTEGER PRIMARY KEY';
277         $size      = undef;
278 #        $pk_set    = 1;
279     }
280
281     $field_def .= sprintf " %s%s", $data_type, 
282     ( !$field->is_auto_increment && $size ) ? "($size)" : '';
283
284     # Null?
285     $field_def .= ' NOT NULL' unless $field->is_nullable;
286
287     # Default?  XXX Need better quoting!
288     my $default = $field->default_value;
289     if (defined $default) {
290         SQL::Translator::Producer->_apply_default_value(
291             \$field_def,
292             $default, 
293             [
294              'NULL'              => \'NULL',
295              'now()'             => 'now()',
296              'CURRENT_TIMESTAMP' => 'CURRENT_TIMESTAMP',
297             ],
298         );
299     }
300
301     return $field_def;
302
303 }
304
305 sub create_index
306 {
307     my ($index, $options) = @_;
308
309     my $name   = $index->name;
310     $name      = mk_name($index->table->name, $name);
311
312     my $type   = $index->type eq 'UNIQUE' ? "UNIQUE " : ''; 
313
314     # strip any field size qualifiers as SQLite doesn't like these
315     my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
316     (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
317     warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
318     my $index_def =  
319     "CREATE ${type}INDEX $name ON " . $index_table_name .
320         ' (' . join( ', ', @fields ) . ')';
321
322     return $index_def;
323 }
324
325 sub create_constraint
326 {
327     my ($c, $options) = @_;
328
329     my $name   = $c->name;
330     $name      = mk_name($c->table->name, $name);
331     my @fields = $c->fields;
332     (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
333     warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
334
335     my $c_def =  
336     "CREATE UNIQUE INDEX $name ON " . $index_table_name .
337         ' (' . join( ', ', @fields ) . ')';
338
339     return $c_def;
340 }
341
342 sub alter_table { } # Noop
343
344 sub add_field {
345   my ($field) = @_;
346
347   return sprintf("ALTER TABLE %s ADD COLUMN %s",
348       $field->table->name, create_field($field))
349 }
350
351 sub alter_create_index {
352   my ($index) = @_;
353
354   # This might cause name collisions
355   return create_index($index);
356 }
357
358 sub alter_create_constraint {
359   my ($constraint) = @_;
360
361   return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
362 }
363
364 sub alter_drop_constraint { alter_drop_index(@_) }
365
366 sub alter_drop_index {
367   my ($constraint) = @_;
368
369   return sprintf("DROP INDEX %s",
370       $constraint->name);
371 }
372
373 sub batch_alter_table {
374   my ($table, $diffs) = @_;
375
376   # If we have any of the following
377   #
378   #  rename_field
379   #  alter_field
380   #  drop_field
381   #
382   # we need to do the following <http://www.sqlite.org/faq.html#q11>
383   #
384   # BEGIN TRANSACTION;
385   # CREATE TEMPORARY TABLE t1_backup(a,b);
386   # INSERT INTO t1_backup SELECT a,b FROM t1;
387   # DROP TABLE t1;
388   # CREATE TABLE t1(a,b);
389   # INSERT INTO t1 SELECT a,b FROM t1_backup;
390   # DROP TABLE t1_backup;
391   # COMMIT;
392   #
393   # Fun, eh?
394   #
395   # If we have rename_field we do similarly.
396
397   my $table_name = $table->name;
398   my $renaming = $diffs->{rename_table} && @{$diffs->{rename_table}};
399
400   if ( @{$diffs->{rename_field}} == 0 &&
401        @{$diffs->{alter_field}}  == 0 &&
402        @{$diffs->{drop_field}}   == 0
403        ) {
404 #    return join("\n", map { 
405     return map { 
406         my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
407         map { my $sql = $meth->(ref $_ eq 'ARRAY' ? @$_ : $_); $sql ?  ("$sql") : () } @{ $diffs->{$_} }
408         
409       } grep { @{$diffs->{$_}} } 
410     qw/rename_table
411        alter_drop_constraint
412        alter_drop_index
413        drop_field
414        add_field
415        alter_field
416        rename_field
417        alter_create_index
418        alter_create_constraint
419        alter_table/;
420   }
421
422
423   my @sql;
424   my $old_table = $renaming ? $diffs->{rename_table}[0][0] : $table;
425   
426   do {
427     local $table->{name} = $table_name . '_temp_alter';
428     # We only want the table - dont care about indexes on tmp table
429     my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
430     push @sql,$table_sql;
431   };
432
433   push @sql, "INSERT INTO @{[$table_name]}_temp_alter SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$old_table]}",
434              "DROP TABLE @{[$old_table]}",
435              create_table($table, { no_comments => 1 }),
436              "INSERT INTO @{[$table_name]} SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$table_name]}_temp_alter",
437              "DROP TABLE @{[$table_name]}_temp_alter";
438
439   return @sql;
440 #  return join("", @sql, "");
441 }
442
443 sub drop_table {
444   my ($table) = @_;
445   return "DROP TABLE $table";
446 }
447
448 sub rename_table {
449   my ($old_table, $new_table, $options) = @_;
450
451   my $qt = $options->{quote_table_names} || '';
452
453   return "ALTER TABLE $qt$old_table$qt RENAME TO $qt$new_table$qt";
454
455 }
456
457 # No-op. Just here to signify that we are a new style parser.
458 sub preproces_schema { }
459
460 1;
461
462 =pod
463
464 =head1 SEE ALSO
465
466 SQL::Translator, http://www.sqlite.org/.
467
468 =head1 AUTHOR
469
470 Ken Y. Clark C<< <kclark@cpan.orgE> >>.
471
472 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.
473
474 =cut