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