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