1 package SQL::Translator::Producer::SQLite;
3 # -------------------------------------------------------------------
4 # $Id: SQLite.pm,v 1.15 2006-08-26 11:35:31 schiffbruechige Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 SQLFairy Authors
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.
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.
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
21 # -------------------------------------------------------------------
25 SQL::Translator::Producer::SQLite - SQLite producer for SQL::Translator
31 my $t = SQL::Translator->new( parser => '...', producer => 'SQLite' );
36 This module will produce text output of the schema suitable for SQLite.
42 use SQL::Translator::Schema::Constants;
43 use SQL::Translator::Utils qw(debug header_comment);
45 use vars qw[ $VERSION $DEBUG $WARN ];
47 $VERSION = sprintf "%d.%02d", q$Revision: 1.15 $ =~ /(\d+)\.(\d+)/;
48 $DEBUG = 0 unless defined $DEBUG;
49 $WARN = 0 unless defined $WARN;
51 my %used_identifiers = ();
52 my $max_id_length = 30;
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;
64 debug("PKG: Beginning production\n");
67 push @create, header_comment unless ($no_comments);
68 push @create, 'BEGIN TRANSACTION';
70 for my $table ( $schema->get_tables ) {
71 push @create, create_table($table, { no_comments => $no_comments,
72 add_drop_table => $add_drop_table,});
75 for my $view ( $schema->get_views ) {
76 push @create, create_view($view, {
77 add_drop_view => $add_drop_table,
78 no_comments => $no_comments,
82 return wantarray ? (@create, "COMMIT") : join(";\n\n", (@create, "COMMIT;\n"));
85 # -------------------------------------------------------------------
87 my ($basename, $type, $scope, $critical) = @_;
88 my $basename_orig = $basename;
90 ? $max_id_length - (length($type) + 1)
92 $basename = substr( $basename, 0, $max_name )
93 if length( $basename ) > $max_name;
94 $basename =~ s/\./_/g;
95 my $name = $type ? "${type}_$basename" : $basename;
97 if ( $basename ne $basename_orig and $critical ) {
98 my $show_type = $type ? "+'$type'" : "";
99 warn "Truncating '$basename_orig'$show_type to $max_id_length ",
100 "character limit to make '$name'\n" if $WARN;
101 $truncated{ $basename_orig } = $name;
104 $scope ||= \%global_names;
105 if ( my $prev = $scope->{ $name } ) {
106 my $name_orig = $name;
107 $name .= sprintf( "%02d", ++$prev );
108 substr($name, $max_id_length - 3) = "00"
109 if length( $name ) > $max_id_length;
111 warn "The name '$name_orig' has been changed to ",
112 "'$name' to make it unique.\n" if $WARN;
114 $scope->{ $name_orig }++;
122 my ($view, $options) = @_;
123 my $add_drop_view = $options->{add_drop_view};
125 my $view_name = $view->name;
126 debug("PKG: Looking at view '${view_name}'\n");
128 # Header. Should this look like what mysqldump produces?
129 my $extra = $view->extra;
131 $create .= "--\n-- View: ${view_name}\n--\n" unless $options->{no_comments};
132 $create .= "DROP VIEW IF EXISTS $view_name;\n" if $add_drop_view;
134 $create .= " TEMPORARY" if exists($extra->{temporary}) && $extra->{temporary};
136 $create .= " IF NOT EXISTS" if exists($extra->{if_not_exists}) && $extra->{if_not_exists};
137 $create .= " ${view_name}";
139 if( my $sql = $view->sql ){
140 $create .= " AS\n ${sql}";
148 my ($table, $options) = @_;
150 my $table_name = $table->name;
151 my $no_comments = $options->{no_comments};
152 my $add_drop_table = $options->{add_drop_table};
154 debug("PKG: Looking at table '$table_name'\n");
156 my ( @index_defs, @constraint_defs, @trigger_defs );
157 my @fields = $table->get_fields or die "No fields in $table_name";
159 my $temp = $options->{temporary_table} ? 'TEMPORARY ' : '';
164 push @create, "--\n-- Table: $table_name\n--\n" unless $no_comments;
165 push @create, qq[DROP TABLE $table_name] if $add_drop_table;
166 my $create_table = "CREATE ${temp}TABLE $table_name (\n";
171 if ( $table->comments and !$no_comments ){
172 $create_table .= "-- Comments: \n-- ";
173 $create_table .= join "\n-- ", $table->comments;
174 $create_table .= "\n--\n\n";
178 # How many fields in PK?
180 my $pk = $table->primary_key;
181 my @pk_fields = $pk ? $pk->fields : ();
186 my ( @field_defs, $pk_set );
187 for my $field ( @fields ) {
188 push @field_defs, create_field($field);
192 scalar @pk_fields > 1
194 ( @pk_fields && !grep /INTEGER PRIMARY KEY/, @field_defs )
196 push @field_defs, 'PRIMARY KEY (' . join(', ', @pk_fields ) . ')';
202 my $idx_name_default = 'A';
203 for my $index ( $table->get_indices ) {
204 push @index_defs, create_index($index);
210 my $c_name_default = 'A';
211 for my $c ( $table->get_constraints ) {
212 next unless $c->type eq UNIQUE;
213 push @constraint_defs, create_constraint($c);
216 $create_table .= join(",\n", map { " $_" } @field_defs ) . "\n)";
218 return (@create, $create_table, @index_defs, @constraint_defs, @trigger_defs );
223 my ($field, $options) = @_;
225 my $field_name = $field->name;
226 debug("PKG: Looking at field '$field_name'\n");
227 my $field_comments = $field->comments
228 ? "-- " . $field->comments . "\n "
231 my $field_def = $field_comments.$field_name;
234 my $size = $field->size;
235 my $data_type = $field->data_type;
236 $data_type = 'varchar' if lc $data_type eq 'set';
237 $data_type = 'blob' if lc $data_type eq 'bytea';
239 if ( lc $data_type =~ /(text|blob)/i ) {
243 # if ( $data_type =~ /timestamp/i ) {
244 # push @trigger_defs,
245 # "CREATE TRIGGER ts_${table_name} ".
246 # "after insert on $table_name\n".
248 # " update $table_name set $field_name=timestamp() ".
249 # "where id=new.id;\n".
256 # SQLite is generally typeless, but newer versions will
257 # make a field autoincrement if it is declared as (and
258 # *only* as) INTEGER PRIMARY KEY
260 my $pk = $field->table->primary_key;
261 my @pk_fields = $pk ? $pk->fields : ();
264 $field->is_primary_key &&
265 scalar @pk_fields == 1 &&
267 $data_type =~ /int(eger)?$/i
269 ( $data_type =~ /^number?$/i && $size !~ /,/ )
272 $data_type = 'INTEGER PRIMARY KEY';
277 $field_def .= sprintf " %s%s", $data_type,
278 ( !$field->is_auto_increment && $size ) ? "($size)" : '';
281 $field_def .= ' NOT NULL' unless $field->is_nullable;
283 # Default? XXX Need better quoting!
284 my $default = $field->default_value;
285 if ( defined $default ) {
286 if ( uc $default eq 'NULL') {
287 $field_def .= ' DEFAULT NULL';
288 } elsif ( $default eq 'now()' ||
289 $default eq 'CURRENT_TIMESTAMP' ) {
290 $field_def .= ' DEFAULT CURRENT_TIMESTAMP';
291 } elsif ( $default =~ /val\(/ ) {
294 $field_def .= " DEFAULT '$default'";
304 my ($index, $options) = @_;
306 my $name = $index->name;
307 $name = mk_name($index->table->name, $name);
309 my $type = $index->type eq 'UNIQUE' ? "UNIQUE " : '';
311 # strip any field size qualifiers as SQLite doesn't like these
312 my @fields = map { s/\(\d+\)$//; $_ } $index->fields;
313 (my $index_table_name = $index->table->name) =~ s/^.+?\.//; # table name may not specify schema
314 warn "removing schema name from '" . $index->table->name . "' to make '$index_table_name'\n" if $WARN;
316 "CREATE ${type}INDEX $name ON " . $index_table_name .
317 ' (' . join( ', ', @fields ) . ')';
322 sub create_constraint
324 my ($c, $options) = @_;
327 $name = mk_name($c->table->name, $name);
328 my @fields = $c->fields;
329 (my $index_table_name = $c->table->name) =~ s/^.+?\.//; # table name may not specify schema
330 warn "removing schema name from '" . $c->table->name . "' to make '$index_table_name'\n" if $WARN;
333 "CREATE UNIQUE INDEX $name ON " . $index_table_name .
334 ' (' . join( ', ', @fields ) . ')';
339 sub alter_table { } # Noop
344 return sprintf("ALTER TABLE %s ADD COLUMN %s",
345 $field->table->name, create_field($field))
348 sub alter_create_index {
351 # This might cause name collisions
352 return create_index($index);
355 sub alter_create_constraint {
356 my ($constraint) = @_;
358 return create_constraint($constraint) if $constraint->type eq 'UNIQUE';
361 sub alter_drop_constraint { alter_drop_index(@_) }
363 sub alter_drop_index {
364 my ($constraint) = @_;
366 return sprintf("DROP INDEX %s",
370 sub batch_alter_table {
371 my ($table, $diffs) = @_;
373 # If we have any of the following
379 # we need to do the following <http://www.sqlite.org/faq.html#q11>
382 # CREATE TEMPORARY TABLE t1_backup(a,b);
383 # INSERT INTO t1_backup SELECT a,b FROM t1;
385 # CREATE TABLE t1(a,b);
386 # INSERT INTO t1 SELECT a,b FROM t1_backup;
387 # DROP TABLE t1_backup;
392 # If we have rename_field we do similarly.
394 my $table_name = $table->name;
395 my $renaming = $diffs->{rename_table} && @{$diffs->{rename_table}};
397 if ( @{$diffs->{rename_field}} == 0 &&
398 @{$diffs->{alter_field}} == 0 &&
399 @{$diffs->{drop_field}} == 0
401 # return join("\n", map {
403 my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
404 map { my $sql = $meth->(ref $_ eq 'ARRAY' ? @$_ : $_); $sql ? ("$sql") : () } @{ $diffs->{$_} }
406 } grep { @{$diffs->{$_}} }
408 alter_drop_constraint
415 alter_create_constraint
421 my $old_table = $renaming ? $diffs->{rename_table}[0][0] : $table;
424 local $table->{name} = $table_name . '_temp_alter';
425 # We only want the table - dont care about indexes on tmp table
426 my ($table_sql) = create_table($table, {no_comments => 1, temporary_table => 1});
427 push @sql,$table_sql;
430 push @sql, "INSERT INTO @{[$table_name]}_temp_alter SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$old_table]}",
431 "DROP TABLE @{[$old_table]}",
432 create_table($table, { no_comments => 1 }),
433 "INSERT INTO @{[$table_name]} SELECT @{[ join(', ', $old_table->get_fields)]} FROM @{[$table_name]}_temp_alter",
434 "DROP TABLE @{[$table_name]}_temp_alter";
437 # return join("", @sql, "");
442 return "DROP TABLE $table";
446 my ($old_table, $new_table, $options) = @_;
448 my $qt = $options->{quote_table_names} || '';
450 return "ALTER TABLE $qt$old_table$qt RENAME TO $qt$new_table$qt";
454 # No-op. Just here to signify that we are a new style parser.
455 sub preproces_schema { }
463 SQL::Translator, http://www.sqlite.org/.
467 Ken Y. Clark C<< <kclark@cpan.orgE> >>.
469 Diff code added by Ash Berlin C<< <ash@cpan.org> >>.