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